【问题标题】:Android: BluetoothSocket readLine timeoutAndroid:BluetoothSocket readLine 超时
【发布时间】:2011-12-26 01:14:25
【问题描述】:

我应该在 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 上永远等待。我有机会抛出异常或超时吗? 谢谢!!

【问题讨论】:

    标签: android sockets bluetooth timeout


    【解决方案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 块。然后处理异常。

    【讨论】:

      猜你喜欢
      • 2015-09-19
      • 1970-01-01
      • 1970-01-01
      • 2020-04-06
      • 1970-01-01
      • 1970-01-01
      • 2012-05-18
      • 2018-09-22
      • 1970-01-01
      相关资源
      最近更新 更多