我的蓝牙服务器在尝试创建蓝牙服务器套接字时崩溃。我已经在谷歌上搜索了很多,找到了几个我尝试过的答案,但没有任何效果。我在几个不同的设备上尝试了代码,但到处都出现相同的错误。
...
private class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;
public AcceptThread() {
// Use a temporary object that is later assigned to mmServerSocket,
// because mmServerSocket is final
BluetoothServerSocket tmp = null;
try {
// MY_UUID is the app's UUID string, also used by the client code
tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(Var.SERVICE_NAME, UUID.fromString("a70aec2c-19e4-4804-8e3c-557de4e3f558"));
} catch (IOException e) {
e.printStackTrace();
}
mmServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
// Keep listening until exception occurs or a socket is returned
while (true) {
try {
socket = mmServerSocket.accept();
} catch (IOException e) {
break;
}
...
错误信息:
08-01 16:14:48.361: E/AndroidRuntime(32417): FATAL EXCEPTION: Thread-8045
08-01 16:14:48.361: E/AndroidRuntime(32417): Process: ... .bluetoothserver, PID: 32417
08-01 16:14:48.361: E/AndroidRuntime(32417): java.lang.NullPointerException
08-01 16:14:48.361: E/AndroidRuntime(32417): at ... .bluetoothserver.communication.BluetoothChat$AcceptThread.run(BluetoothChat.java:103)
08-01 16:14:48.731: E/BluetoothSocket(32417): bindListen, fail to get port number, exception: java.io.IOException: read failed, socket might closed or timeout, read ret: -1
这里有什么问题?以下行中的 tmp 为空:
tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(Var.SERVICE_NAME, UUID.fromString("a70aec2c-19e4-4804-8e3c-557de4e3f558"));
listenUsingRfcommWithServiceRecord 失败并引发 IOException,该异常被忽略并且 AcceptThread 仍然启动。 mmServerSocket 设置为空。
这应该可以解决:
private class Server_Connect_Thread extends Thread {
private final BluetoothServerSocket mmServerSocket;
private boolean running = true;
public Server_Connect_Thread() {
BluetoothServerSocket tmp = null;
try {
tmp = bluetooth_adapter.listenUsingRfcommWithServiceRecord("NAME", uuid);
} catch (IOException e) {
bluetooth_show_message("Bluetooth Error! listenUsingRfcommWithServiceRecord failed. Reason:" + e);
running = false;
}
mmServerSocket = tmp;
}
public void run() {
while (running) {
try {
socket = mmServerSocket.accept();
} catch (IOException e) {
bluetooth_show_message("Bluetooth Error! Accepting a connection failed. Reason:" + e);
break;
}
...
}
您得到的 IOException 经常发生,例如当其他设备未能及时连接时,或者您连接到错误的蓝牙设备时。就我而言,这是我邻居的电视机。
我是一名优秀的程序员,十分优秀!