开发者

How to stop AlarmManager

I have a activity A, it regist开发者_StackOverflow中文版er AlarmManager to trigger another BroadcastReceiver B. When time is reached, onReceive() of B will be called, and start another activity C. A may be closed when C is started.

My problem is: - C don't know the pendingIntent in A, how can I call alarmManager.cancel(pendingIntent) in C? - Or, how can I pass pendingIntent from A to B to C?

Pls help.


In my application I created a static method that returned the PendingIntent required for the AlarmManager, and then I can call it from any class. If you have a PendingIntent that doesn't change between times it is called this can 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 that from any class to get the same PendingIntent.


It would be far easier to manage the Alarm and its intent in a singleton service than to try to pass it from activity to activity, and far less brittle (you could introduce Activity D somewhere in the middle without having to daisy chain the intent further).


You can register a broadcast receiver in A to listen for a custom action that is broadcasted when C is started

In Activity A

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

register the receiver

registerReceiver(onActivityCStartedReceiver , new IntentFilter(ACTIVITY_C_STARTED_ACTION));

In Activity C call

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

try it! make use of the messaging system for your good :D


To cancel/destroy all the services which you have generated, then generally you need the same "pendingInetent" and "AlarmManager" variable which you have used for starting those services, for example if your previous variable is am_mngr and pndngInt then use it like this in your stopservice method.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜