这是我的代码:
Thread connectThread = new Thread(new Runnable() {
@Override
public void run() {
try {
boolean gotuuid = btDevices.getItem(position)
.fetchUuidsWithSdp();
if (gotuuid){
UUID uuid = btDevices.getItem(position).getUuids()[0]
.getUuid();
mbtSocket = btDevices.getItem(position)
.createRfcommSocketToServiceRecord(uuid);
mbtSocket.connect();
} else {
Log.e("ID22", "There is no uuid");
}
} catch (IOException ex) {
runOnUiThread(socketErrorRunnable);
try {
mbtSocket.close();
} catch (IOException e) {
// e.printStackTrace();
}
mbtSocket = null;
return;
} finally {
runOnUiThread(new Runnable() {
@Override
public void run() {
finish();
}
});
}
}
});
connectThread.start();
}
当我尝试使用mbtSocket.connect();
连接到蓝牙soccket时,它会停止并抛出socketErrorRunnable
异常。你知道如何解决这个问题吗?我搜索了一下,但没有什么对我有用。
答案 0 :(得分:0)
如果您遇到麻烦,请参阅官方Android Bluetooth Chat示例中的一些代码:
服务器端:
public class BluetoothServer {
private final static String TAG = "BluetoothServer";
private final BluetoothServerSocket serverSocket;
// I would recommand defining a secure connexion so forget the unsecore UUID
private static final UUID MY_UUID_SECURE =
UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66"); // choose another UUID go to a site that generates a random UUI ;-)
private static final UUID MY_UUID_INSECURE =
UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66"); // choose another UUID go to a site that generates a random UUI ;-)
// BUT THIS WILL BE THE UUID YOU NEED TO CONNECT TO IN YOUR CLIENT APP -> createRfcommSocketToServiceRecord(UUID.fromString("0800200c9a66"));
// Name for the SDP record when creating server socket
private static final String NAME_SECURE = "BluetoothChatSecure";
private static final String NAME_INSECURE = "BluetoothChatInsecure";
public BluetoothServer(BluetoothAdapter adapter, boolean secure) {
try {
if (secure) {
this.serverSocket = adapter.listenUsingRfcommWithServiceRecord(NAME_SECURE,
MY_UUID_SECURE);
} else {
this.serverSocket = adapter.listenUsingInsecureRfcommWithServiceRecord(
NAME_INSECURE, MY_UUID_INSECURE);
}
} catch (IOException e) {
Log.e(TAG, "Socket Type: " + (secure ? "secure" : "insecure") + "listen() failed", e);
}
}
public void asyncStartServer() {
new Thread(new Runnable() {
@Override
public void run() {
try {
final BluetoothSocket socket = serverSocket.accept(); // blocks/wait until your phone connects
// at this point, your phone is connected
final InputStream is = socket.getInputStream();
// and now start reading
} catch (IOException ioe) {
Log.getStackTraceString(ioe);
}
}
}).start();
}
}