如何从服务正确管理线程的生命周期?
How to correctly manage a Thread's lifecycle from a Service?
我在阅读 Service
API
指南(更具体地说 this section)时注意到了一些事情。在下面的代码片段中,每次创建 Service
时都会创建并启动一个新的 HandlerThread
:
@Override
public void onCreate() {
// Start up the thread running the service. Note that we create a
// separate thread because the service normally runs in the process's
// main thread, which we don't want to block. We also make it
// background priority so CPU-intensive work will not disrupt our UI.
HandlerThread thread = new HandlerThread("ServiceStartArguments",
Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
// Get the HandlerThread's Looper and use it for our Handler
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
但此线程此后就再也没有停止过。所以,我的问题是:为什么没有对停止方法的任何显式调用?我问这个是因为我想知道如果 Service
本身被系统杀死,由 Service
创建的任何线程会发生什么。我怎样才能确保一切都被清理干净?
好吧,如果一个服务被杀死并从内存中取出,那么线程也会随之被杀死。队列中的任何消息都将被删除并中止。这可能就是为什么他们没有在 onDestroy
方法中显示正在退出的线程。
但是,如果要结束线程,HandlerThread 有方法 quit()
和 quitSafely()
(API >= 18)。您可以将它们放在服务的 onDestroy()
方法中。两者之间的区别是 quit()
会尽快终止线程,而 quitSafely()
会在所有消息完成后立即终止线程。但是,如前所述,线程可能会在此之前死掉。
编辑:
澄清一下,当系统杀死应用程序进程时,线程也会被杀死。对于具有如示例所示的永久工作线程的服务,不需要太多清理,因为无论如何都会清理所有内容。
更多的临时服务可能需要您手动关闭线程,因为您正在自行终止服务。发生这种情况时,应用程序进程仍将处于活动状态,这意味着您创建的线程仍将处于活动状态,因此必须按照原始答案中的说明关闭这些线程。 IntentService
虽然通常是更好的选择,因为它已经为您处理了所有线程。
我在阅读 Service
API
指南(更具体地说 this section)时注意到了一些事情。在下面的代码片段中,每次创建 Service
时都会创建并启动一个新的 HandlerThread
:
@Override
public void onCreate() {
// Start up the thread running the service. Note that we create a
// separate thread because the service normally runs in the process's
// main thread, which we don't want to block. We also make it
// background priority so CPU-intensive work will not disrupt our UI.
HandlerThread thread = new HandlerThread("ServiceStartArguments",
Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
// Get the HandlerThread's Looper and use it for our Handler
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
但此线程此后就再也没有停止过。所以,我的问题是:为什么没有对停止方法的任何显式调用?我问这个是因为我想知道如果 Service
本身被系统杀死,由 Service
创建的任何线程会发生什么。我怎样才能确保一切都被清理干净?
好吧,如果一个服务被杀死并从内存中取出,那么线程也会随之被杀死。队列中的任何消息都将被删除并中止。这可能就是为什么他们没有在 onDestroy
方法中显示正在退出的线程。
但是,如果要结束线程,HandlerThread 有方法 quit()
和 quitSafely()
(API >= 18)。您可以将它们放在服务的 onDestroy()
方法中。两者之间的区别是 quit()
会尽快终止线程,而 quitSafely()
会在所有消息完成后立即终止线程。但是,如前所述,线程可能会在此之前死掉。
编辑:
澄清一下,当系统杀死应用程序进程时,线程也会被杀死。对于具有如示例所示的永久工作线程的服务,不需要太多清理,因为无论如何都会清理所有内容。
更多的临时服务可能需要您手动关闭线程,因为您正在自行终止服务。发生这种情况时,应用程序进程仍将处于活动状态,这意味着您创建的线程仍将处于活动状态,因此必须按照原始答案中的说明关闭这些线程。 IntentService
虽然通常是更好的选择,因为它已经为您处理了所有线程。