问题
I have a background thread in my app. Now when the screen goes off(after say 15 seconds), the thread is running and hence does not behave as I prefer. So, in which method of the Activity life cycle do I have to stop the thread when the screen goes off. I know how to stop the thread but do not know when to stop it. Thanks in advance.
回答1:
Do you want it to run when the app is in the background (if the user is in another app)? If not, onPause. If so, then you'd need a BroadcastReceiver to capture the screen turning off, and stop it in respect to that.
IntentFilter screenStateFilter = new IntentFilter();
screenStateFilter.addAction(Intent.ACTION_SCREEN_ON);
screenStateFilter.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(mScreenStateReceiver, screenStateFilter);
Java file :
onReceive(Intent i) {
if( i.getAction().equals(Intent.ACTION_SCREEN_ON) ) {
// turn your thread start if you want or anything else
} else if( i.getAction().equals(Intent.ACTION_SCREEN_OFF) ) {
// turn your thread cancel here
}
}
And just in case you don't know, a warning- do not use thread.stop() to stop it. It can cause crashes, memory/resource leaks, and deadlocks. Cancel the thread instead and have the thread poll to see if its canceled.
来源:https://stackoverflow.com/questions/29180979/how-to-stop-a-background-thread-when-the-screen-in-android-device-goes-off