近期项目中链接蓝牙以后接收蓝牙设备发出的指令功能,在链接设备以后,建立RfcommSocket链接时候报java.io.IOException: read failed, socket might closed or timeout, read ret: -1错误。如下说一下个人解决方法,但愿对各位有一点帮助。java
private BluetoothSocket mSocket; <span style="white-space:pre"> </span>private InputStream mInputSream; <span style="white-space:pre"> </span>private UUID mUUID = UUID <span style="white-space:pre"> </span>.fromString("00001101-0000-1000-8000-00805F9B34FB");
//找到蓝牙设备并推断是否链接上蓝牙,并建立socket
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); Set<BluetoothDevice> sets = adapter.getBondedDevices(); Iterator<BluetoothDevice> iterator = sets.iterator(); while (iterator.hasNext()) { BluetoothDevice device = iterator.next(); if (mUtils.isConnected(device)) try { mBluetoothDevice = device; mSocket = mBluetoothDevice .createRfcommSocketToServiceRecord(mUUID);
接下来就是socket的链接了,原本我是在一个子线程中作的这些:android
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错误,
查了各类资料也没找到解决方法。<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">通过本身屡次实验发现在</span>
mSocket.connect()时候还需要在还有一个子线程中处理才正常链接上接收到指令。也就是例如如下代码:
<pre name="code" class="java">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(); }这里仅仅是找到了解决方法,但是还不知道缘由,也查了各类资料,没有获得为何在子线程中作,connect的时候还需要再开一个子线程。