我有一個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()
某處。我需要更多地閱讀Looper
和Handler
。我開始看HandlerThread
,但我並不清楚Loopers是幹什麼的。是否將Handler
傳遞給我的ConnectThread
是一個壞主意?