我的服務產生一個新線程,並根據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