標籤:android bluetooth bluetoothsocket
最近項目中串連藍芽之後接收藍牙裝置發出的指令功能,在串連裝置之後,建立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() {@Overridepublic 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的時候還需要再開一個子線程。
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
java.io.IOException: read failed, socket might closed or timeout, read ret: -1