2011-03-29 92 views
1

我有一個Service產生Thread連接到第三方,它運行良好。但是,如果我轉到設置並停止服務,它將繼續運行。它從設置中的運行服務中消失,並調用onDestroy方法,但我仍然看到調用Service中的每個方法。我假設我沒有正確使用Thread,但我不明白爲什麼服務將繼續運行......除非它在所有線程完成之前一直運行。Android服務繼續運行後強制停止

public class DataProcessorService extends Service { 

    private ServiceState _state; 
    private ConnectThread _connectThread; 

    private Handler _handler = new Handler() { 
     public synchronized void handleMessage(Message msg) { 
      stopConnectThread(); 
      onNextState(); // Goes to state after Connecting 
     } 
    }; 

    @Override 
    public void onCreate() { 
     logger.debug("onCreate called"); 

     _state = ServiceState.readState(this); 

     switch (_state) { 
     ... 
     case CONNECTING: 
      onConnecting(); 
      break; 
     ... 
     } 
    } 

    @Override 
    public void onDestroy() { 
     logger.debug("onDestroy called"); 
     stopConnectThread(); 
     ServiceState.saveState(this, _state); 
    } 

    private void onConnecting() { 
     _state = ServiceState.CONNECTING; 
     logger.debug("onConnecting called"); 

     _connectThread = new ConnectThread(this, _handler); 
     _connectThread.setDaemon(true); 
     _connectThread.start(); 
    } 

    private void stopConnectThread() { 
     if (_connectThread != null) { 
      _connectThread.interrupt(); 
      _connectThread = null; 
     } 
    } 
} 

這是我的ConnectThread類(我也試着做什麼建議here這是註釋的部分):

public class ConnectThread extends Thread { 

    private final Context _context; 
    private final Handler _handler; 

// private volatile Thread runner; 

    public ConnectThread(Context context, Handler handler) { 
     super("ConnectThread"); 
     this._context = context; 
     this._handler = handler; 
    } 

// public synchronized void startThread() { 
//  if (runner == null) { 
//   runner = new Thread(this); 
//   runner.start(); 
//  } 
// } 
// 
// public synchronized void stopThread() { 
//  if (runner != null) { 
//   Thread moribund = runner; 
//   runner = null; 
//   moribund.interrupt(); 
//  } 
// } 

    @Override 
    public void run() { 
     Looper.prepare(); 
//  if (Thread.currentThread() == runner) { 
      logger.debug("Service started"); 

      Thread.sleep(5000); //inside try-catch 
//  } 
     Looper.loop(); 
    } 

} 

當我看着DDMS,它顯示了多個ConnectThread S和他們每個在wait的狀態,所以我假設他們正在完成,沒有被殺害,這可能會阻止我的服務停止。有沒有人看到問題發生的原因,或知道如何解決它?

編輯:我現在開始認爲這可能是因爲我需要撥打Looper.quit()某處。我需要更多地閱讀LooperHandler。我開始看HandlerThread,但我並不清楚Loopers是幹什麼的。是否將Handler傳遞給我的ConnectThread是一個壞主意?

回答

0

您必須停止在loopConnectThread()中循環的Looper。只要中斷線程不會停止Looper。試試這個:

在ConnectThread類添加

private Looper myLooper; // A reference to the Looper for this Thread 
public void stopLooper() { 
    // Tell Looper to stop looping 
    myLooper.quit(); 
} 
在ConnectThread.run

()方法中,在Looper.prepare()地址:

myLooper = Looper.myLooper(); // Get the Looper associated with this Thread 
在stopConnectThread()

,而不是_connectThread.interrupt();做到這一點:

_connectThread.stopLooper();