Android BluetoothSocket.isConnected总是返回false

我试图检测蓝牙设备当前是否连接到使用API​​ 14或更高版本的Android设备。 看起来我应该可以使用BluetoothSocket.isConnected()方法,但无论我做了什么,到目前为止,我只是为了任何东西,连接或不连接而返回假。

AndroidManifest包含以下行:

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

<!-- Locale 4.x supports API 14 or greater. -->
<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="17" />

<uses-feature android:name="android.hardware.bluetooth" />

有问题的代码:

protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();

    for (BluetoothDevice device : pairedDevices) {
        Log.i(Constants.LOG_TAG, String.format(Locale.US, "Device: %s connected: %b", device.getName(), isConnected(device))); //$NON-NLS-1$z
    }
}

private boolean isConnected(BluetoothDevice device) {
    BluetoothSocket socket = null;

    // Get a BluetoothSocket for a connection with the given BluetoothDevice
    UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    try {
        socket = device.createRfcommSocketToServiceRecord(SPP_UUID);
    } catch (IOException e) {
        Log.e(Constants.LOG_TAG, e.getMessage()); //$NON-NLS-1$z
        return false;
    }

    Log.i(Constants.LOG_TAG, socket.toString()); //$NON-NLS-1$z

    return socket.isConnected();
}

没有错误被抛出,它只是100%的时间返回“假”。 有没有我不擅长的事情?


我相信jkane001已经解决了他的问题,所以我希望这个答案能够帮助别人。

首先在套接字创建后

socket = device.createRfcommSocketToServiceRecord(SPP_UUID);

你应该通过初始化连接

socket.connect();

之后,您将能够使用socket.isConnected()检查连接状态

由于connect()方法没有被阻塞,所以在套接字可能尚未连接之后立即进行。 我建议使用这样的东西

while(!socket.isConnected() && trial++ < 3){
    try {
        Thread.sleep(300);
    } catch (Exception e) {}
}

顺便说一下,我发现在某些android设备上, isConnected()总是返回false。 在这种情况下,只需尝试将某些内容写入套接字并检查是否没有异常。


显然有isConnected()实现的设备和/或Android版本(即函数存在,你可以调用它),但更糟糕的是因为它总是返回false。 我在运行Android 4.2.2的桌面上安装了Alcatel手机,该手机展现了这种行为。

我的代码假设它已断开连接,所以导致我的连接线程中断,这让我很长时间都很疯狂。 但是,我删除了isConnected()调用,并假定它已连接,并且一切正常! 我没有找到更好的方法来检查有效的连接,而不是等待错误并声明连接已经死亡。 线程中被阻塞的read()最终会失败。

我们从现场报道听起来相似,并且我们知道该版本的2个问题设备中的2个也在4.2.2上。 尚未部署修复程序,因此不确定它是否修复了这些情况。


首先,你为什么要使用反射? 这是我的一面红旗。 这些API允许你通过蓝牙与其他设备通话,看到这个链接,你就不应该使用反射。

在调用connect方法之前,套接字总是返回不连接。 看起来你的代码获取套接字,但从来没有试图与它建立连接。 你首先需要调用这个方法。

链接地址: http://www.djcxy.com/p/69159.html

上一篇: Android BluetoothSocket.isConnected always returns false

下一篇: WPF: Scroll Itemcontrol Content Fixed Header