近期项目中连接蓝牙之后接收蓝牙设备发出的指令功能,在连接设备之后,创建RfcommSocket连接时候报java.io.IOException: read failed, socket might closed or timeout, read ret: -1错误。以下说一下我的解决方法,希望对各位有一点帮助。
private BluetoothSocket mSocket; private InputStream mInputSream; private UUID mUUID = UUID .fromString("00001101-0000-1000-8000-00805F9B34FB");
//找到蓝牙设备并推断是否连接上蓝牙,并创建socket
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); Setsets = adapter.getBondedDevices(); Iterator iterator = sets.iterator(); while (iterator.hasNext()) { BluetoothDevice device = iterator.next(); if (mUtils.isConnected(device)) try { mBluetoothDevice = device; mSocket = mBluetoothDevice .createRfcommSocketToServiceRecord(mUUID);
接下来就是socket的连接了,本来我是在一个子线程中做的这些:
public void run() { try { if (mSocket != null) mSocket.connect(); if (mSocket != null) { mInputSream = mSocket.getInputStream(); mIsRunning = true; } while (mIsRunning) { byte[] buffer = new byte[16]; while (mInputSream != null && mInputSream.read(buffer) > 0 && mIsRunning) { String val = new String(buffer); Log.i("SPP", val); Intent intent = new Intent(); if (val.contains("+PTT=P")) { intent.setAction("android.intent.action.PTT.down"); } else if (val.contains("+PTT=R")) { intent.setAction("android.intent.action.PTT.up"); } mContext.sendBroadcast(intent); Arrays.fill(buffer, (byte) 0); } } } catch (IOException e) { try { if (mInputSream != null) mInputSream.close(); if (mSocket != null) { mSocket.close(); mSocket = null; } } catch (Exception e2) { // TODO: handle exception } } }可是这样在socket连接的时候还是会报java.io.IOException: read failed, socket might closed or timeout, read ret: -1错误,
查了各种资料也没找到解决方法。经过自己多次实验发如今
mSocket.connect()时候还须要在还有一个子线程中处理才正常连接上接收到指令。也就是例如以下代码:
这里仅仅是找到了解决方法,可是还不知道原因,也查了各种资料,没有得到为什么在子线程中做,connect的时候还须要再开一个子线程。public void run() { new Thread(new Runnable() { @Override public void run() { try { if (mSocket != null) mSocket.connect(); if (mSocket != null) { mInputSream = mSocket.getInputStream(); mIsRunning = true; } while (mIsRunning) { byte[] buffer = new byte[16]; while (mInputSream != null && mInputSream.read(buffer) > 0 && mIsRunning) { String val = new String(buffer); Log.i("SPP", val); Intent intent = new Intent(); if (val.contains("+PTT=P")) { intent.setAction("android.intent.action.PTT.down"); } else if (val.contains("+PTT=R")) { intent.setAction("android.intent.action.PTT.up"); } mContext.sendBroadcast(intent); Arrays.fill(buffer, (byte) 0); } } } catch (IOException e) { try { if (mInputSream != null) mInputSream.close(); if (mSocket != null) { mSocket.close(); mSocket = null; } } catch (Exception e2) { // TODO: handle exception } } } }).start(); }