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

后端 未结 16 2115
天涯浪人
天涯浪人 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条回答
  • 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.

    0 讨论(0)
  • 2020-11-22 04:53

    On newer versions of Android, I was receiving this error because the adapter was still discovering when I attempted to connect to the socket. Even though I called the cancelDiscovery method on the Bluetooth adapter, I had to wait until the callback to the BroadcastReceiver's onReceive() method was called with the action BluetoothAdapter.ACTION_DISCOVERY_FINISHED.

    Once I waited for the adapter to stop discovery, then the connect call on the socket succeeded.

    0 讨论(0)
  • 2020-11-22 04:53

    I've had this problem and the solution was to use the special magic GUID.

                val id: UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB") // Any other GUID doesn't work.
                val device: BluetoothDevice = bta!!.bondedDevices.first { z -> z.name == deviceName }
    
                bts = device.createRfcommSocketToServiceRecord(id) // mPort is -1
                bts?.connect()
                // Start processing thread.
    

    I suspect that these are the UUIDs that work:

    var did: Array<ParcelUuid?> = device.uuids
    

    However, I have not tried them all.

    0 讨论(0)
  • 2020-11-22 04:55

    If another part of your code has already made a connection with the same socket and UUID, you get this error.

    0 讨论(0)
提交回复
热议问题