1

我正在开发一项服务,它扩展了 Service 类并使用单独的线程来处理传入的消息,因此,我的 onCreate 方法中有以下内容

thread = new HandlerThread("MYSERVICE-THREAD",
        Process.THREAD_PRIORITY_BACKGROUND);

thread.start();
serviceLooper = thread.getLooper();
serviceHandler = new ServiceHandler(mServiceLooper);

在这个线程中,我创建了一个 LocationManager 并将其设置为监听位置变化。不过,我有点担心线程的生命周期。这就是为什么:

如果我从服务的 onDestroy 方法中的位置管理器中删除位置侦听器,并通过 telnet 强制更新位置,那么一切正常。我发现这很奇怪,并尝试在服务的 onDestroy 方法中使用 thread.quit() 显式结束线程。所以,现在当从 telnet 进行位置更新时,我收到了我一开始就期待的警告。处理程序正在死线程上调用处理程序。

从位置管理器中删除位置侦听器显然可以解决这个问题,但是,这似乎暗示我,如果我不明确关闭线程,则线程将在服务被销毁后继续运行。这个对吗?在 developer.android.com 上的示例中,他们没有明确关闭他们的线程,所以我认为 VM 在这种情况下会处理它。

4

2 回答 2

3

Oh yes. This is the case. The same goes for Activities too. Threads stay open until Android explicitly kills them to free up resources unless you close them yourself. In a technical sense, Activities and Services are never closed when popped from the stack. It just tells the OS that all the resources that they were using can now be reclaimed when it's needed so that memory pool will be the first place the OS looks. If a thread of any kind is still running however, it will continue to run (and take up CPU resources) until the memory is reclaimed which could be anywhere between 1 second and eternity.

于 2012-05-26T15:10:16.237 回答
2

this seems to hint to me that if I dont explicitly close the thread, the thread will continue to run after the service is destroyed. Is this correct?

Absolutely. If you fork the thread, you have to clean it up.

so I thought the VM would take care of it in this case.

Well, it will, eventually, insofar as the OS will eventually terminate the whole process for your app. That being said, you do not want to leak threads, and you really do not want to leak a requestLocationUpdates() call (or whatever it is that you are using with LocationManager), as that can keep the location provider powered on (e.g., GPS).

In the examples on developer.android.com they dont explicitly close their thread

Which examples are you referring to?

于 2012-05-26T15:12:29.063 回答