近期項目中鏈接藍牙以後接收藍牙設備發出的指令功能,在鏈接設備以後,建立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的時候還需要再開一個子線程。