【发布时间】:2012-03-02 23:26:18
【问题描述】:
我正在开发基于BluetoothChat exemple 的Android 蓝牙应用程序。我正在启动蓝牙服务器并监听设备(不是电话)以通过不安全的 rfcomm 连接连接到我的应用程序。
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();
//...等待
- 如果设备已配对,为什么还要等待?
- 如何建立连接,因为我也试过反射,还是没有结果
- HTC 的蓝牙堆栈有问题吗?有没有人使用其他安卓手机建立连接?
【问题讨论】:
-
您是否可以在您尝试连接的设备上编辑蓝牙软件?
-
您需要在两台设备上设置您的应用,然后您会看到它们可以相互通信
标签: android bluetooth connection rfcomm