当设备从USB电缆拔出时,Android HandlerThread停止工作
我的应用程序包括一个生成HandlerThread的服务,该线程定期从LocationManager请求位置更新。每次收到位置更新后,我都会禁用位置更新,并向Hander发送一条延迟消息,该消息将在将来再次启动更新:当设备从USB电缆拔出时,Android HandlerThread停止工作,android,multithreading,service,usb,location,Android,Multithreading,Service,Usb,Location,我的应用程序包括一个生成HandlerThread的服务,该线程定期从LocationManager请求位置更新。每次收到位置更新后,我都会禁用位置更新,并向Hander发送一条延迟消息,该消息将在将来再次启动更新: public class VMLocator extends HandlerThread implements LocationListener { ... private final class VMHandler extends Handler { public
public class VMLocator extends HandlerThread implements LocationListener {
...
private final class VMHandler extends Handler
{
public VMHandler(Looper looper)
{
super(looper);
}
@Override
public void handleMessage(Message msg)
{
if(MSG_START_LOCATION_UPDATES == msg.what)
{
startLocationUpdates();
}
}
}
...
@Override
public void onLocationChanged(Location location) {
...
stopLocationUpdates();
// Schedule updates to start again in the future.
Message msg = new Message();
msg.what = MSG_START_LOCATION_UPDATES;
handler.sendMessageDelayed(msg, 5000); // <-- Testing value. Will be much larger.
...
}
公共类VMLocator扩展HandlerThread实现LocationListener{
...
私有最终类VMHandler扩展了处理程序
{
公共VMHandler(活套-活套)
{
超级(活套);
}
@凌驾
公共无效handleMessage(消息消息消息)
{
if(MSG\u START\u LOCATION\u UPDATES==MSG.what)
{
startLocationUpdates();
}
}
}
...
@凌驾
已更改位置上的公共无效(位置){
...
stopLocationUpdates();
//安排更新在将来重新开始。
Message msg=新消息();
msg.what=msg\u开始位置\u更新;
handler.sendMessageDelayed(msg,5000);//应用程序->正在运行的服务始终表示我的服务仍在运行
我已经为调试干杯;据我所知,我的服务没有被破坏,但是HandlerThread的消息队列停止处理消息
我尝试在断开连接的情况下从手机上运行,并禁用USB调试,但结果相同。我感觉到我错过的文档中有一些简单的东西,因为我认为从Eclipse运行/调试安装了应用程序,并且无论USB电缆是否插入,应用程序都应该正常运行。 谢谢dragonroot,你的建议帮助我意识到了问题所在
问题是我在HandlerThread中调用了Debug.waitForDebugger();
。一旦USB电缆断开,这个调用就会永远停止,因为找不到调试器连接
事后看来,这是一个非常基本的错误,希望这能帮助其他人避免它。您如何确切地知道线程停止/似乎没有运行?其工作的最终结果是什么?每次onLocationChanged()或handleMessage()都是被称为“我显示祝酒辞”。拔下USB电缆后,祝酒辞将不再显示,并在重新插入USB电缆后恢复。这可能是由于祝酒辞由于某种原因而未显示的问题,而不是服务被暂停的问题。请尝试添加Log.d()
调用您的代码,并使用类似于aLogcat的应用程序在正在运行的设备上查看它们。