Android BluetoothSocket.connent超时

时间:2011-12-14 08:29:26

标签: android bluetooth timeout

我遇到了这种罕见的情况,我试图将BluetoothSocket连接到服务器,并且connect方法不会返回。这是我的代码:

            device = _adapter.getRemoteDevice(_address);
            socket = device.createInsecureRfcommSocketToServiceRecord(_uuid);                           
            _adapter.cancelDiscovery();
            socket.connect();

这是在AsyncTask中运行,任务永远不会完成,因为连接永远被阻止...这也阻止了重新连接到服务器(我还没想到我是否完全不能使用BT或者不能使用相同的目标地址和UUID重新连接)。有没有办法连接超时?

1 个答案:

答案 0 :(得分:2)

解决问题的一种方法是让另一个线程通过调用cancel(true)(它将中断AsyncTask线程)或通过调用Socket上的close()来中断AsyncTask。例如,可以通过主线程完成,通过在socket.connect()之前向其处理程序发布延迟回调,并在之后直接删除。

所以在你的情况下

post timeout callback to handler, with reference to socket or to this (AsyncTask)
try {
    socket.connect();
} catch (IOException e) { // and/or InterruptedException
    couldn't connect
} finally {
    remove callback (this must be done here as the IO exception might be caused by something other than the timeout callback)
}