omaraflak / Bluetooth-Library

Bluetooth client library for Android.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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

martialDevOrange opened this issue · comments

I have this problem and I found a fix on stackoverflow

The problem is with the socket.mPort parameter. When you create your socket using socket = device.createRfcommSocketToServiceRecord(SERIAL_UUID); , the mPort gets integer value "-1", and this value seems doesn't work for android >=4.2 , so you need to set it to "1".

try {
           socket.connect();
           Log.e("","Connected");
    } catch (IOException e) {
           Log.e("",e.getMessage());
           try {
                    Log.e("","trying fallback...");

                    socket =(BluetoothSocket) device.getClass().getMethod("createRfcommSocket", new Class[] {int.class}).invoke(device,1);
                    socket.connect();

                    Log.e("","Connected");
               } catch (Exception e2) {
                 Log.e("", "Couldn't establish Bluetooth connection!");
               }
     }

so, If you can add this workaround in your library, it will be helpful...

This issue was opened a long time ago. Still, for future visitors, I updated the library. You can now use this "trick", although not recommended, using the following methods :

bluetooth.connectToNameWithPortTrick("name");
bluetooth.connectToAddressWithPortTrick("address");
bluetooth.connectToDeviceWithPortTrick(device);