How to stop AlarmManager

I have activity A, it registers AlarmManager to start another BroadcastReceiver B. When the time is reached, onReceive () from B is called and another action C is triggered. A can be closed when C. starts.

My problem: - C do not know how pendingIntent in A, how can I call alarmManager.cancel (pendingIntent) in C? - Or, how can I pass a pendingIntent from A to B to C?

Help Pls.

+4
source share
4 answers

In my application, I created a static method that returned the PendingIntent needed for the AlarmManager , and then I can call it from any class. If you have a PendingIntent that does not change between the moments, it is called, this may work for you. For example, I have:

 public static PendingIntent getSyncPendingIntent(Context context) { Intent i = new Intent(context, <classname>.class); PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0); return pi; } 

And I can just call this from any class to get the same PendingIntent .

+2
source

It would be much easier to control the alarm and its intent in one single service than to try to transfer it from activity to activity and much less fragile (you could enter Activity D somewhere in the middle without creating an intention chain further).

0
source

You can register the broadcast receiver in to listen to the custom action that broadcasts when C starts up.

In action A

 private BroadcastReceiver onActivityCStartedReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { //cancel the pendingIntent for the alarm here } }; 

register receiver

 registerReceiver(onActivityCStartedReceiver , new IntentFilter(ACTIVITY_C_STARTED_ACTION)); 

In action C call

 Intent i = new Intent(ACTIVITY_C_STARTED_ACTION); context.sendBroadcast(i); 

try it! use the messaging system for your product: D

0
source

To cancel / destroy all the services that you generated, you usually need the same pendingInetent and AlarmManager variables that you used to start these services, for example, if your previous variable is am_mngr and pndngInt, then use it in stopervice method.

  am_mngr.cancel(pndngInt); // this will cancel the previous servicse... 
0
source

All Articles