当设备从USB电缆拔出时,Android HandlerThread停止工作

时间:2011-10-18 23:33:09

标签: android multithreading service usb location

我的应用程序包含一个产生HandlerThread的服务,该服务器定期从LocationManager请求位置更新。每次收到更新的位置时,我都会禁用位置更新,并向管理员发送延迟消息,以便将来再次启动更新:

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.
    ...
}

我目前正在使用运行2.3.3的HTC Desire S手机进行测试,使用Eclipse进行开发。手机通过USB线连接到我的开发机器时,一切正常。但是:

  • 如果我从Eclipse启动应用程序(调试或运行),一切正常,直到我拔下USB线,此时我的HandlerThread似乎停止了。
  • 如果我从手机本身启动应用程序,断开USB连接线后,服务就会启动,但线程似乎没有运行。

注意事项:

  • 在上述任何一种情况下,如果我重新插入USB线,它会立即重新开始工作。
  • 在上述任何一种情况下,设置 - &gt;应用程序 - &gt; “运行服务”始终表示我的服务仍在运行
  • 我在周围撒了一些调试Toast;据我所知,我的服务没有被销毁,但HandlerThread的消息队列停止处理消息。

我已经尝试在断开连接的情况下从手机上运行并禁用USB调试,结果相同。我觉得我错过的文档中有一些简单的东西,因为我认为Eclipse的运行/调试安装了应用程序,无论USB电缆是否插入,应用程序都应该正常运行。

1 个答案:

答案 0 :(得分:1)

感谢dragonroot,你的建议帮助我意识到问题所在。

问题是我在HandlerThread中调用了Debug.waitForDebugger();。一旦USB电缆断开,此呼叫就会永久停止,因为无法找到调试器连接。

事后看来是一个非常基本的错误,希望这会帮助其他人避免它。

相关问题