问题遇到的现象和发生背景
我在做 android bluetooth spp ota 的app项目 现在经典蓝牙的连接这里出了问题
用代码块功能插入代码,请勿粘贴截图
private class ClientThread extends Thread {
private final BluetoothDevice mDevice;
private BluetoothSocket mSocket;
@SuppressLint("MissingPermission")
public ClientThread(BluetoothDevice device) {
mDevice = device;
try {
//mSocket =(BluetoothSocket) device.getClass().getMethod("createRfcommSocketToServiceRecord", UUID.class).invoke(device,2);
mSocket = device.createInsecureRfcommSocketToServiceRecord(SerialPortServiceClass_UUID);
} catch ( IOException e) {
Log.e("ClientThread", "create failed", e);
mSocket = null;
}
}
@SuppressLint("MissingPermission")
public void run() {
Log.i("ClientThread", "BEGIN mConnectThread");
new Thread(() -> {
//先退出扫描再进行连接
if ( mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
try {
mSocket.connect();
Log.d("service","Bluetooth one running(connected)");
} catch (IOException e) {
e.printStackTrace();
try {
mSocket.close();
}catch (IOException e1){
e1.printStackTrace();
}
}
}).start();
}
}
运行结果及报错内容
2022-10-09 10:37:46.908 9899-11377/com.savitech.btota I/ClientThread: BEGIN mConnectThread
2022-10-09 10:37:46.910 9899-11378/com.savitech.btota W/BluetoothAdapter: getBluetoothService() called with no BluetoothManagerCallback
2022-10-09 10:37:47.747 9899-11378/com.savitech.btota W/System.err: java.io.IOException: read failed, socket might closed or timeout, read ret: -1
2022-10-09 10:37:47.747 9899-11378/com.savitech.btota W/System.err: at android.bluetooth.BluetoothSocket.readAll(BluetoothSocket.java:772)
2022-10-09 10:37:47.747 9899-11378/com.savitech.btota W/System.err: at android.bluetooth.BluetoothSocket.readInt(BluetoothSocket.java:786)
2022-10-09 10:37:47.747 9899-11378/com.savitech.btota W/System.err: at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:404)
2022-10-09 10:37:47.747 9899-11378/com.savitech.btota W/System.err: at com.savitech.btota.MainActivity$ClientThread.lambda$run$0$com-savitech-btota-MainActivity$ClientThread(MainActivity.java:179)
2022-10-09 10:37:47.747 9899-11378/com.savitech.btota W/System.err: at com.savitech.btota.MainActivity$ClientThread$$ExternalSyntheticLambda0.run(Unknown Source:2)
2022-10-09 10:37:47.747 9899-11378/com.savitech.btota W/System.err: at java.lang.Thread.run(Thread.java:919)
2022-10-09 10:37:47.747 9899-11378/com.savitech.btota D/BluetoothSocket: close() this: android.bluetooth.BluetoothSocket@701412e, channel: -1, mSocketIS: android.net.LocalSocketImpl$SocketInputStream@4f8f4cf, mSocketOS: android.net.LocalSocketImpl$SocketOutputStream@fb17e5cmSocket: android.net.LocalSocket@a3b0565 impl:android.net.LocalSocketImpl@7e4423a fd:java.io.FileDescriptor@b3a0eeb, mSocketState: INIT
我想要达到的结果
想要其能正常连接上蓝牙设备