如何当Android设备屏幕熄灭停止后台线程 [英] How to stop a background thread when the screen in android device goes off
问题描述
我在我的应用程序在后台线程。现在,当屏幕熄灭(后说15秒),线程运行,因此不表现为我preFER。因此,在该活动的生命周期的方法,我必须当屏幕熄灭停止线程。我知道如何停止的线程,但不知道什么时候停止。先谢谢了。
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.
推荐答案
?如果不是,在onPause。如果是这样,那么你需要一个BroadcastReceiver捕捉到画面关闭,并就停止了这一点。
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的文件:
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
}
}
和万一你不知道,一个警告 - 不要用Thread.stop()以阻止它。它可能导致死机,内存/资源泄漏和死锁。取消线程来代替,而纷纷跟帖民意调查,看看它取消了。
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.
这篇关于如何当Android设备屏幕熄灭停止后台线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!