最近项目中连接蓝牙之后接收蓝牙设备发出的指令功能,在连接设备之后,创建RfcommSocket连接时候报java.io.IOException: read failed, socket might closed or timeout, read ret: -1错误,下面说一下我的解决方法,希望对各位有一点帮助。
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的连接了,本来我是在一个子线程中做的这些:
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(); }