问题
I've a Broadcast Receiver into my application that waits for the screen to go on/off. What I want to do is:
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
pause some seconds...
...do something
}
}
How can I stop the current thread into the onReceive method?
回答1:
You can't and you shouldn't pause the BrodcastReceiver neither postDelayed to a Handler();
You shouldn't stop it because that thread needs to do other stuff, so don't block it because it's a bad design.
and you can't postDelay because from the docs:
Once you return from onReceive(), the BroadcastReceiver is no longer active, and its hosting process is only as important as any other application components that are running in it. This is especially important because if that process was only hosting the BroadcastReceiver (a common case for applications that the user has never or not recently interacted with), then upon returning from onReceive() the system will consider its process to be empty and aggressively kill it so that resources are available for other more important processes.
that means that the moment it returns from onReceive() all this will likely be killed very fast.
If you want something to happen some time after the broadcast you can start a service, and that service wait the amount of time, or if the amount of time you want to wait is longer than a few seconds, you should just put the launch of this service in the AlarmManager and let the AlarmManager launch the service for you.
回答2:
As per our short clarification, I suggest than in onReceive()
you use the AlarmManager with set(RTC, System.currentTimeMillis()+10000, thePendingIntentToNotifyYou)
. This way, you'll be informed after ten seconds unless the device goes to sleep. (Use RTC_WAKEUP
otherwise.)
Via your broadcast receivers, you'll also be informed about the screen being turned off and on (you'll need to listen for that as well to stop the timer if you don't do it already) and will have to maintain a small state machine so as to know whether the condition you're looking for (screen off for ten seconds) holds upon triggering of thePendingIntentToNotifyYou
.
回答3:
use Handler.postDelayed method.
So your code will be something like this
Handler h = new Handler();
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
h.postDelayed(new Runnable(){
public void run(){
// do something
}
},pause_time_in_milis);
}
}
来源:https://stackoverflow.com/questions/16037720/android-pausing-a-broadcast-receiver