我正在使用 Google Bluetooth Chat Example 中的代码设置蓝牙监听服务器。我希望应用程序始终监听传入连接。当应用程序看到连接请求时,它将接受连接,读取远程设备将发送的字符串,然后通过发送文件进行响应。
问题是应用程序从不接受连接。它在 socket = mmServerSocket.accept();
处阻塞,并且永远不会继续前进。请参阅以下行后的代码 if(D) System.out.println("Waiting to connect************");
为了测试它,我启动了 Activity 它启动线程,然后尝试连接我的笔记本电脑并发送文件。当我这样做时,整个 Android 蓝牙管理器会看到该文件并有效地绕过我的 Android 设备下载它。这是测试它的唯一方法吗?我无法确定这是测试问题还是编码问题。
private class AcceptThread extends Thread {
// The local server socket
private final BluetoothServerSocket mmServerSocket;
public AcceptThread() {
BluetoothServerSocket tmp = null;
// Create a new listening server socket
try {
tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
} catch (IOException e) {
Log.e(TAG, "listen() failed", e);
}
mmServerSocket = tmp;
}
public void run() {
if (D) Log.d(TAG, "BEGIN mAcceptThread" + this);
setName("AcceptThread");
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
if(D) System.out.println("Waiting to connect************");
socket = mmServerSocket.accept();
if(D) System.out.println("We have accepted connection and are connected***************");
} catch (IOException e) {
Log.e(TAG, "accept() failed", e);
break;
}
// If a connection was accepted
if (socket != null) {
synchronized (BluetoothServer.this) {
switch (mState) {
case STATE_LISTEN:
case STATE_CONNECTING:
// Situation normal. Start the connected thread.
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;
}
}
}
}
if (D) Log.i(TAG, "END mAcceptThread");
}
最佳答案
此问题的解决方案位于您的 androidmanifest.xml
文件中;
uses-permission android:name="android.permission.BLUETOOTH_ADMIN"
uses-permission android:name="android.permission.BLUETOOTH"
手机未授予您的程序权限
我实际上添加了一些代码,但我猜它被编辑掉了
关于android - 蓝牙创建套接字但在 connect() 处阻塞 ANDROID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3917076/