我正在尝试检测当前是否已使用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%的时间内返回“false”。有什么我做不对的事情吗?

最佳答案

我相信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。在这种情况下,只需尝试向套接字写入内容,然后检查是否没有异常。

关于Android BluetoothSocket.isConnected始终返回false,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14792040/

10-09 03:01