android 设备中的屏幕关闭时如何停止后台线程

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

我的应用程序中有一个后台线程。现在,当屏幕关闭时(比如 15 秒后),线程为 运行,因此不会像我喜欢的那样运行。那么,在 Activity 生命周期的哪个方法中,我必须在屏幕关闭时停止线程。我知道如何停止线程但不知道何时停止。提前致谢。

当应用程序处于后台时(如果用户在另一个应用程序中),您希望它 运行 吗?如果没有,就暂停。如果是这样,那么您需要一个 BroadcastReceiver 来捕获屏幕关闭,并就此停止它。

IntentFilter screenStateFilter = new IntentFilter();
screenStateFilter.addAction(Intent.ACTION_SCREEN_ON);
screenStateFilter.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(mScreenStateReceiver, screenStateFilter);

Java 文件:

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() 来阻止它。它可能导致崩溃、memory/resource 泄漏和死锁。改为取消线程并让线程轮询以查看其是否已取消。