我做的是關於藍芽串口的開發,開始串連裝置的時候用的是// btSocket = btDevice.createRfcommSocketToServiceRecord(UUID
// .fromString("00001101-0000-1000-8000-00805F9B34FB"));
用這句代碼、再次串連別的裝置時候就會出現java.io.IOException: Service discovery failed這個異常、解決方案是
/*
* 初始化Socket
*/
private void initSocket() {
BluetoothSocket temp = null;
try {
// temp =
// mTouchObject.bluetoothDevice.createRfcommSocketToServiceRecord(UUID.fromString(CONNECT_UUID));
// 以上取得socket方法不能正常使用, 用以下方法代替
Method m = btDevice.getClass().getMethod("createRfcommSocket",
new Class[] { int.class });
temp = (BluetoothSocket) m.invoke(btDevice, 1);
// 怪異錯誤: 直接賦值給socket,對socket操作可能出現異常, 要通過中間變數temp賦值給socket
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
btSocket = temp;
}
通過中間變數temp賦值給socket,
第二個問題就是在調用socket.close()這個方法時候出現了@@@ ABORTING: INVALID HEAP ADDRESS IN dlf這個錯誤,網上查詢這是記憶體對齊的問題,找了好久的原因是因為自己沒有對inputstream 正確關閉
try {
if (mmInStream != null) {
mmInStream.close();
}
} catch (IOException e1) {
e1.printStackTrace();
}
shutdownClient();
if (btAdapter != null && btAdapter.isDiscovering()) {
btAdapter.cancelDiscovery();
}
if (btSocket != null) {
try {
btSocket.close();// 結束socket
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
btSocket = null;
}
正確關閉就好了,恩這就是我解決這兩個問題的方法