问题描述
|
我有一个在后台运行自己的线程的服务。我想终止该服务,包括线程。
我创建了这样的线程并运行它。
public class DaemonService extends Service {
private DaemonThread thread;
class DaemonThread extends Thread {
public void run()
{
runDaemon(mArgv.toArray(),mConfig);
}
}
public void onStart(Intent intent,int startId) {
thread = new DaemonThread();
thread.start();
}
}
如何终止服务和线程?我不必担心数据安全性。
解决方法
杀死线程,我想你可以这样:
myService.getThread().interrupt();
注意:方法“ 2”已弃用
编辑::尝试这个
public void stopThread(){
if(myService.getThread()!=null){
myService.getThread().interrupt();
myService.setThread(null);
}
}
, 方法Thread.stop()
已过时,可以使用
Thread.currentThread().interrupt();
并设定set6ѭ。
, 使用服务的Context.stopService()
或stopSelf()
方法。
, 使用服务的onDestroy方法进行操作
http://developer.android.com/reference/android/app/Service.html#onDestroy()
public void onDestroy(){
thread.stop();
super.onDestroy();
}
然后使用stopService()停止服务; (这将调用onDestroy());
http://developer.android.com/reference/android/content/Context.html#stopService(android.content.Intent)
, @Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Thread.currentThread().interrupt();
}