尝试创建蓝牙服务器套接字时,我的蓝牙服务器崩溃了。 我已经搜索了很多,并找到了我尝试过的几个答案,但没有任何效果。 我在几个不同的设备上尝试了代码,但是到处都出现了相同的错误。
...
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为null:
tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(Var.SERVICE_NAME, UUID.fromString("a70aec2c-19e4-4804-8e3c-557de4e3f558"));
答案 0 :(得分:0)
listenUsingRfcommWithServiceRecord failed and rasied IOException, which was ignored and AcceptThread started anyway. mmServerSocket was set to null.
This should fix it:
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;
}
...
}
The IOException that you got, happens quite often, for example when other devices fails to connect in time, or you are connecting to wrong bluetooth device. In my case it was my neighbours TV set.