IOException: read failed, socket might closed - Bluetooth on Android 4.3

后端 未结 16 2094
天涯浪人
天涯浪人 2020-11-22 04:08

Currently I am trying to deal with a strange Exception when opening a BluetoothSocket on my Nexus 7 (2012), with Android 4.3 (Build JWR66Y, I guess the second 4.3 update). I

16条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 04:53

    First, if you need to talk to a bluetooth 2.x device, this documentation states that :

    Hint: If you are connecting to a Bluetooth serial board then try using the well-known SPP UUID 00001101-0000-1000-8000-00805F9B34FB. However if you are connecting to an Android peer then please generate your own unique UUID.

    I didn't think that it would work, but only by replacing the UUID with 00001101-0000-1000-8000-00805F9B34FB it works. However, this code seems to handle the problem of SDK version, and you can just replace the function device.createRfcommSocketToServiceRecord(mMyUuid); with tmp = createBluetoothSocket(mmDevice); after defining the following method :

    private BluetoothSocket createBluetoothSocket(BluetoothDevice device)
        throws IOException {
        if(Build.VERSION.SDK_INT >= 10){
            try {
                final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
                return (BluetoothSocket) m.invoke(device, mMyUuid);
            } catch (Exception e) {
                Log.e(TAG, "Could not create Insecure RFComm Connection",e);
            }
        }
        return  device.createRfcommSocketToServiceRecord(mMyUuid);
    }
    

    The source code isn't mine, but comes from this website.

提交回复
热议问题