Search code examples
androidbroadcastreceiveralarmmanager

android pause and restart alarm manager in broadcast receiver


i create AlarmManager in my MainActivity like this

AlarmManager mgr = (AlarmManager) getApplicationContext()
                .getSystemService(Context.ALARM_SERVICE);
Intent notificationIntent = new Intent(getApplicationContext(),
                TransactionService.class);
PendingIntent   pendingIntent=PendingIntent.getService(getApplicationContext(), 0,   notificationIntent, 0);
       mgr.setInexactRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(), 2000, pendingIntent);

I want for some condition to stop this alarm manager in a broadcast receiver. Below the code of the broadcast receiver(whatever it is).

public class IncomingSms extends BroadcastReceiver {
private Intent notificationIntent;

public void onReceive(Context context, Intent intent) {
}
}
}

So how can i access this alarm manager and pause it into my broadcast receiver, and how can i restart it again ?


Solution

  • public class IncomingSms extends BroadcastReceiver {
        private Intent notificationIntent;
    
        public void onReceive(Context context, Intent intent) {
             AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
             Intent notificationIntent = new Intent(context, TransactionService.class);
             PendingIntent pendingIntent=PendingIntent.getService(getApplicationContext(), 0,   notificationIntent, 0);
             mgr.cancel(pendingIntent)
        }
    }
    

    You simply have to rebuild your PendingIntent and could pass it to the cancel()-method of the AlarmManager. The identification of your PendingIntent will be done by checking the id of your PendingIntent and if the containing Intent will meet the filterEquals()-requirements defined here: http://developer.android.com/reference/android/content/Intent.html#filterEquals%28android.content.Intent%29

    More information: http://developer.android.com/reference/android/app/AlarmManager.html#cancel%28android.app.PendingIntent%29

    If you want to restart, you simply have to register to your PendingIntent again.