【问题标题】:Android Bluetooth Socket Connect HangsAndroid 蓝牙 Socket 连接挂起
【发布时间】:2012-03-01 05:10:12
【问题描述】:

我遇到一个问题,当我调用 sock.connect() 时,它只是无限期挂起。没有异常,也没有超时。

try
    {
        Method m = dev.getClass().getMethod("createRfcommSocket", new     Class[] {int.class});          
        sock = (BluetoothSocket) m.invoke(dev, 1); 
        sock.connect();
        Thread.sleep(100);
        in = sock.getInputStream();
        out = sock.getOutputStream();
    }
    catch(ConnectTimeoutException ex)
    {
        return false;
    }
    catch(IOException ex)
    {
        return false;
    }
    catch(Exception ex)
    {
        return false;
    }

原因是另一个应用程序已经在使用蓝牙设备。我试图让我的连接失败,至少抛出一个异常或其他东西让我知道该设备已被另一个应用程序使用。

对于解决这个问题还有其他建议吗?

谢谢。

【问题讨论】:

  • 你能解决吗?我面临着类似的问题。

标签: android bluetooth connection rfcomm


【解决方案1】:

为什么要调用 Thread.Sleep? BluetoothSocket.connect 是一个阻塞调用。这意味着在 connect 返回成功连接或引发异常之前,不会调用 Thread.Sleep。

您是在活动中调用它吗?因为这会挂起你的活动。您应该有 3 个线程来处理蓝牙,一个接受线程,一个连接线程和一个连接线程。就像这里的 BluetoothChat 示例一样:

http://developer.android.com/resources/samples/BluetoothChat/index.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-27
    相关资源
    最近更新 更多