Skip to content Skip to sidebar Skip to footer

Is There A Way To Keep A Repeating Alarm Working After Existing The App That Uses A Broadcast Receiver?

I am new on Android. I am trying to create an application that uses BroadcastReceiver to execute a function on the main activity triggered by a repeating alarm. I read that I had t

Solution 1:

I think, the reason why your alarm stops working when your app isn't running is that you're registering your AlarmReceiver locally with registerReceiver. If you want to register your AlarmReceiver so that it keeps working even when your app isn't running, you need to register it inside AndroidManifest.xml.

Firstly, add your reciever into AndroidManifest.xml like this:

  <application>    
       //...
       <receiver android:name=".AlarmReceiver">
        </receiver>
       //...
  </application>

And set your alarm like this (Remember: Don't set alarm interval too short, set at least 1 minute; you set ur interval 1,5 second in ur code - it may not work):

    int interval = 60 * 1000;
    Intent intent=new Intent(this, AlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intent, 0);
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);

And just do what you want to do when alarm triggers inside onRecieve:

public class AlarmReceiver extends BroadcastReceiver {
     @Override
     public void onReceive(Context context, Intent intent) {

    AudioManager audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
    SharedPreferences sharedPreferences = context.getSharedPreferences("Settings", 0);
    int iDefValue=0; 
    int iDayAlarmVal= sharedPreferences.getInt("something", iDefValue); 
    // and so on...
                 }
         }

Post a Comment for "Is There A Way To Keep A Repeating Alarm Working After Existing The App That Uses A Broadcast Receiver?"