我有一个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
是一个坏主意?