我的服务产生一个新线程,并根据interrupt()的typically recommended java方法停止它。当我停止服务时,我停止onDestroy()中的线程。服务停止,并且达到中断代码。但是,线程很快就会从Runnable的开头重新启动。为什么不停止线程?
public class DoScan extends Service {
public volatile Thread runner;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
startThread();
}
@Override
public void onDestroy() {
super.onDestroy();
android.util.Log.v("@@@@@@@@@@@@@@@@@@@@", "DoScan.onDestroy");
stopThread();
}
public synchronized void startThread(){
if(runner == null){
android.util.Log.v("@@@@@@@@@@@@@@@@@@@@", "DoScan.startthread");
runner = new Thread(new ScanningThread());
runner.start();
}
}
/* use a handler in a loop cycling through most of oncreate.
* the scanningthread does the work, then notifies the svc's uithread
*/
public synchronized void stopThread(){
if(runner != null){
android.util.Log.v("@@@@@@@@@@@@@@@@@@@@", "DoScan.stopthread");
Thread moribund = runner;
runner = null;
moribund.interrupt();
android.util.Log.v("@@@@@@@@@@@@@@@@@@@@", "interrupted?" + moribund.isInterrupted());
}
}
}
实际上,它不会抛出异常。如果某些调用检测到它们已被中断,则会返回异常,但在大多数情况下,您必须通过检查Thread.isInterrupted()何时适合中断工作来执行检测。 – Fredrik 2009-07-31 21:34:55