How to kill activity from a service
I have a main activity A1 running. It sets an alarm a1 that 开发者_如何学运维goes off at time t1. An alarm receiver AR1 that catches the a1 alarm and creates a service S1. Service S1 creates a dialog activity A2 and also sets an alarm a2 that goes off at time t2. Another alarm receiver AR2 catches the a2 alarm and I need AR2 to kill the dialog activity A2.
I cannot see how the service can get a handle on the activity in order to kill it or call its finish() method.
First, popping up activities from a BroadcastReceiver
is considered poor form except in unusual circumstances, since it will interrupt the user in the middle of whatever it is they are doing. I am going to assume, for the moment, that you are writing the 1,337th alarm clock application for Android, and therefore popping up an activity from a BroadcastReceiver
based on an AlarmManager
alarm is a reasonable choice (assuming the user requested it via preferences within your app).
Given that, you cannot "kill" an activity from a service.
However, you can send a message to the activity, if it is running, and then start it if it is not running.
For example, you could send an ordered broadcast. Have the activity implement a high-priority BroadcastReceiver
for your broadcast, and have it update itself to reflect the new alarm. Implement a low-priority BroadcastReceiver
elsewhere (e.g., in your manifest), and have it start the dialog activity in case the activity is not available, or take some other action based on user preferences (e.g., simply display a Notification
).
精彩评论