Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
705 views
in Technique[技术] by (71.8m points)

bluetooth - java.io.IOException: read failed, socket might closed or timeout, read ret: -1 on Android 5.0.1 Lollipop version

I am making Bluetooth socket connection to Bluetooth device and want to read bytes from the device.

I have established connection correctly :

 try {
         Method m = mmDevice.getClass().getMethod("createRfcommSocket", new Class[] { int.class });
          temp = (BluetoothSocket) m.invoke(mmDevice, 1);
 } catch (Exception e) {
 }

I am reading bytes correctly from Bluetooth device.

I am getting the exception :

java.io.IOException: read failed, socket might closed or timeout, read ret: -1

Due to this, the connection is broken and the communication is also over between my device and Bluetooth device.

This problem is coming on Android 5.0.1 Lollipop especially

Can anyone have workaround ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use createRfcommSocketToServiceRecord instead of createRfcommSocket

createRfcommSocketToServiceRecord takes the UUID you pass and uses SDP to decide what radio channel to use for the connection. It also checks to make sure that a server is listening on the remote endpoint, with the same UUID. In this way, it's the most reliable way to get a connection: it'll always use the correct channel, and if opening the connection succeeds, you know something at the other end can understand your protocol.

In contrast, createRfcommSocket just connects to the channel you tell it. There's no way to know whether anything is listening on the remote endpoint: you only know the device is there. Also, your choice of radio channel may be completely inappropriate. That's why this function is not published in the API, and the other function is preferred.

createRfcommSocket may appear at first to be more reliable, but it's because it's not checking for the presence of a listener at the other endpoint: it's ignoring some error cases. This might be alright for experimenting, but it's no use for a production system, because often the user will forget to start the server on the other endpoint, and your app will fail in confusing ways.

Of course, as createRfcommSocket isn't published in the API, you've no guarantee it will continue to work at all in future releases of Android.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...