我有一个Service
,它生成一个Thread
来连接到第三方,并且运行良好。但是,如果我进入设置并停止该服务,它会继续运行。它从设置中的正在运行的服务中消失,并调用了 onDestroy
方法,但我仍然看到 Service
中的每个方法都被调用。我假设我没有正确使用Thread
,但我不明白为什么服务会继续运行......除非它继续运行直到所有线程都完成。
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
,并且它们每个都处于 wait
状态,因此我假设它们正在完成而不是正在完成被杀死,这可能会阻止我的服务停止。有谁知道问题发生的原因,或者知道如何解决它?
编辑:我现在开始认为这可能是因为我需要在某个地方调用 Looper.quit()
。我需要阅读更多关于 Looper 和 Handler 的内容。我开始研究 HandlerThread,但我还不太清楚 Loopers 的用途。将 Handler
传递给我的 ConnectThread
是一个坏主意吗?
最佳答案
你必须在stopConnectThread()中停止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();
关于java - Android服务在强制停止后继续运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5476924/