我正在開發基於BluetoothChat exemple的Android藍牙應用程序。我正在啓動藍牙服務器,並在不安全的rfcomm連接上監聽設備(而不是電話)以連接到我的應用程序。即使配對設備也不返回BluetoothServerSocket.accept()
private class AcceptThread extends Thread {
// The local server socket
private final BluetoothServerSocket mmServerSocket;
public AcceptThread(boolean secure) {
BluetoothServerSocket tmp = null;
// Create a new listening server socket
try {
tmp = mAdapter.listenUsingInsecureRfcommWithServiceRecord(mServiceName, MY_UUID_INSECURE);
} catch (Exception e) {
Log.e(TAG, ".AcceptThread # listen() failed", e);
}
mmServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
// Listen to the server socket if we're not connected
while (mState != STATE_CONNECTED) {
try {
// This is a blocking call and will only return on a
// successful connection or an exception
Log.d(TAG, ".AcceptThread.run # ...accepting server socket conn");
socket = mmServerSocket.accept(); //FIXME: it blocks here
Log.d(TAG, ".AcceptThread.run # server socket connection accepted");
} catch (Exception e) {
MMLog.e(TAG, ".run # accept() failed: "+e);
connectionFailed();
break;
}
// If a connection was accepted
if (socket != null) {
synchronized (BluetoothService.this) {
switch (mState) {
case STATE_LISTEN:
case STATE_CONNECTING:
// starting the thread where i will receive input
// streams from the other device
connected(socket, socket.getRemoteDevice());
break;
case STATE_NONE:
case STATE_CONNECTED:
// Either not ready or already connected. Terminate new socket.
try {
socket.close();
} catch (IOException e) {
Log.e(TAG, "Could not close unwanted socket", e);
}
break;
}
}
}
}
}
public void cancel() {
try {
if(mmServerSocket != null) {
mmServerSocket.close();
}
} catch (IOException e) {
Log.e(TAG, ".cancel # Could not close server socket: ", e);
}
}
}
我正在使用HTC Desire S,android 2.3.5。設備已配對,但我沒有收到數據,因爲連接在'.accept()'方法中被阻止。它只是繼續等待。
socket = mmServerSocket.accept();
//...and等待
- 爲何仍等待,如果設備配對?
- 我如何建立連接,因爲我也試過反射,但仍然沒有結果
- HTC的藍牙堆棧有問題嗎?有沒有人建立連接也許使用另一個Android手機?
您是否有能力在您嘗試連接的設備上編輯藍牙軟件? – JPM 2012-02-14 00:23:13
您需要在兩臺設備上設置您的應用,之後您會看到他們可以互相溝通 – 2014-01-15 17:40:21