问题描述
我是从应用程序的主线程产生新的工作线程。这些线程正在不断需要做一些操作,只要该应用程序是活的。而且,当应用程序退出,我也想被正确地清理所有工作线程(这意味着什么)。为了做到这一点,是生命周期方法的唯一的地方?是否有被接收的应用程序退出时,意图/通知?如果是的话,我们可以登记在这样的意图/通知的广播接收器做必要的清理工作?
I'm spawning new worker threads from the 'main' thread of the application. These threads are constantly required to do some operation, as long as the application is alive. And, when the application exits, I do want all the worker threads to be cleaned up (whatever that means) properly. In order to do this, are life cycle methods the only place? Are there are intents/notifications which are received when an application exits ? If yes, can we register a broadcast receiver on such intents/notifications to do the required cleanup?
谢谢,
阿肖克。
Code Snippet:
进口android.app.Activity;
进口android.os.Bundle;
进口android.util.Log;
import android.app.Activity;import android.os.Bundle;import android.util.Log;
公共类SomeThreadTest延伸活动{
/ **当第一次创建活动调用。 * /
线程t = NULL;
public class SomeThreadTest extends Activity { /** Called when the activity is first created. */ Thread t = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
t = new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
Thread.sleep(15000);
Log.d("SomeThreadTest", "Thread wokeup now");
} catch (InterruptedException e) {
Log.d("SomeThreadTest", "Thread interrupted exception called!");
e.printStackTrace();
return;
}
if (Thread.interrupted()) {
Log.d("SomeThreadTest", "I'm interrupted!");
}
}
}
}, "TestThread");
t.setDaemon(true);
t.start();
}
}
推荐答案
考虑调用workerThread.setDaemon(真)告诉那就是线程是一个服务提供商,如果非守护进程的主线程退出来杀我。
Consider calling workerThread.setDaemon(true) which tells the thread that is is a service provider and to KILL ME if the non daemon main thread quits.
这篇关于什么钩做我们才能做应用程序退出工作线程终止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!