How to stop a background thread when the screen in android device goes off

限于喜欢 提交于 2019-12-25 08:49:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!