您的位置:首页 > 移动开发 > Android开发

android蓝牙开发read failed, socket might closed or timeout, read ret: -1

2016-10-09 15:22 453 查看
read failed, socket might closed or timeout, read ret: -1

这个问题的原因有很多种可能。

一、如果设备1没开启接收服务,设备2连接它理所当然会连接失败,此时当设备1开启服务,设备2再连接也可能会失败,
http://stackoverflow.com/questions/18657427/ioexception-read-failed-socket-might-closed-bluetooth-on-android-4-3
原因:well, i had the same problem with my code, and it's because since android 4.2 bluetooth stack has changed. so my code was running fine on devices with android < 4.2 , on the other devices i was getting the famous exception "read
failed, socket might closed or timeout, read ret: -1"

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". The bad news is that 
createRfcommSocketToServiceRecord
 only
accepts UUID as parameter and not 
mPort
 so
we have to use other aproach. The answer posted by @matthes also worked for me, but i simplified it: 
socket
=(BluetoothSocket) device.getClass().getMethod("createRfcommSocket", new Class[] {int.class}).invoke(device,1);
. We need to use both socket attribs , the second one as a fallback.

So the code is (for connecting to a SPP on an ELM327 device):

解决方法:

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!");
}
}

通过反射把端口改成1

二、服务器监听端口可能不是1
http://simonlei.iteye.com/blog/1522196
解决方法:

Method listenMethod = btClass.getMethod("listenUsingRfcommOn", new Class[]{int.class});

BluetoothServerSocket returnValue = ( BluetoothServerSocket) listenMethod.invoke(btAdapter, new Object[]{ 29});

三、设备1在搜索的时候设备2连接它会失败
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: