我遇到連接問題。起初它起作用,而不是起作用,除非我解開設備。 我已經得到了可能發生的一切可能的異常,套接字關閉,管道關閉,連接被拒絕,端口已被使用等。藍牙配對設備連接問題
我知道在Android 4.2(https://code.google.com/p/android/issues/detail?id=37725)上有藍牙問題。
即我在與連接這些設備的問題的設備:
- HTC的一個(機器人4.2)
- 三星Galaxy S2(機器人4.1.2)
- 關係4(4.3)
- 三星Galaxy S4(4.2)
另一個次要的問題是,所述配對的設備沒有存儲(主要是上的聯繫4和SGS2)。
這裏是我的代碼:
private static final UUID MY_UUID_SECURE = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); //this is the other one that I've tried: fa87c0d0-afac-11de-8a39-0800200c9a66");
private static final String NAME = "BluetoothConnector";
public void listenForConnection() throws IOException, BluetoothException {
//first close the socket if it is open
closeSocket();
BluetoothServerSocket mServerSocket = null;
try {
mServerSocket = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID_SECURE); //ioexception here!
} catch (IOException e) {
if (Build.VERSION.SDK_INT >= 9) {
try { //this is a stupid hack, http://stackoverflow.com/questions/6480480/rfcomm-connection-between-two-android-devices
Method m = mBluetoothAdapter.getClass().getMethod("listenUsingRfcommOn", new Class[] { int.class });
mServerSocket = (BluetoothServerSocket) m.invoke(mBluetoothAdapter, PORT);
} catch (Exception ex) {
Log.e(ex);
throw e;
}
} else {
throw e;
}
}
while (!isCancelled) {
try {
socket = mServerSocket.accept();
} catch (IOException e) {
if (socket != null) {
try {
socket.close();
} finally {
socket = null;
}
}
throw e;
}
if (socket == null) {
throw new BluetoothException("Socket connection connected, but null");
} else {
isConnected = true;
break; // everything is ok
}
}
}
public void connect(String address) throws IOException, BluetoothException {
mBluetoothAdapter.cancelDiscovery();
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
try {
socket = device.createRfcommSocketToServiceRecord(MY_UUID_SECURE);
} catch (IOException e1) {
Log.e(e1);
if (Build.VERSION.SDK_INT >= 9) {
try {
Method m = device.getClass().getMethod("createRfcommSocket", new Class[] { int.class });
socket = (BluetoothSocket) m.invoke(device, PORT);
} catch (Exception e) {
Log.e(e);
throw e1;
}
} else {
throw e1;
}
}
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
socket.connect();
} catch (IOException e) {
Log.e(e);
// Close the socket
try {
socket.close();
} catch (IOException e2) {
Log.e(e2);
Log.wtf("unable to close() socket during connection failure");
}
throw e;
}
}
private void closeSocket() {
try {
if (socket != null) {
socket.close();
socket = null;
Log.d("Socket closed");
}
} catch (IOException e) {
Log.e(e);
Log.wtf("close() of connect socket failed");
}
}
我試圖改變UUID(隨機的也可以),試圖尋找在舊的SDK樣本。 那麼這裏可能會出現什麼問題?
編輯:試圖澄清:當已經配對,連接的2臺設備進行了一些成功的通信,斷開連接(由用戶)時,通常會出現問題。之後,除非重新啓動或手動取消配對,否則無法重新連接。
走出谷底所有可用的配對設備不會在我的情況下才有意義。我希望用戶連接到特定設備。 – Tamas
k你會在列表視圖中顯示你的配對設備,然後點擊你想要的配對設備來配對該設備...我發佈了一些代碼連接配對設備看到它... – Satheesh