Android:BluetoothSocket readLine超时

时间:2011-11-10 10:19:06

标签: android sockets bluetooth timeout

我应该在readLine上为蓝牙输入流插入超时。

    BluetoothDevice device = BluetoothAdapter.getDefaultAdapter()
            .getRemoteDevice("00:00:00:00:00:00");

    sock = device.createInsecureRfcommSocketToServiceRecord(UUID
            .fromString(insecureUUID));
    sock.connect();

    in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
    String line = in.readLine(); //if no answer from device..i'll wait here forever

    do { [...]

    } while ((line = in.readLine()) != null);

连接工作正常,但我有一个链接到另一台设备的蓝牙串行转换器。如果第二个关闭,我会在readLine上永远等待。我有机会抛出异常或超时吗? 谢谢!

1 个答案:

答案 0 :(得分:1)

我遇到了同样的问题,我通过创建一个扩展Thread的ResponderThread来解决它。该线程等待一段时间,然后检查输入流变量是否已更改。

try {
    bufferedReader = new BufferedReader(new InputStreamReader(
            bluetoothSocket.getInputStream()));

    responderThread = new ResponderThread(bluetoothSocket, ACCESS_RESPONSE);
    responderThread.start();
    response= bufferedReader.read();

} catch (IOException ioe) {
    // Handle the exception.
}

在我的情况下,如果在3秒内没有响应,则responderThread会关闭套接字,并且执行进入我创建responderThread的类的catch块。然后处理异常。