Java 蓝牙Gatt回调异常“;注册回调失败";
每当我试图在我想要接收数据的设备上连接以使用connect gatt时,就会收到一条错误消息,说注册回调失败。我看到了关于这个问题的另一个主题(),这个问题的解决方案应该是使connectgatt或其他与gattcallback相关的函数在UIthread中运行。我也试过了,但还是收到了同样的错误 下面是我如何调用connectGatt方法的Java 蓝牙Gatt回调异常“;注册回调失败";,java,android-studio,bluetooth-gatt,Java,Android Studio,Bluetooth Gatt,每当我试图在我想要接收数据的设备上连接以使用connect gatt时,就会收到一条错误消息,说注册回调失败。我看到了关于这个问题的另一个主题(),这个问题的解决方案应该是使connectgatt或其他与gattcallback相关的函数在UIthread中运行。我也试过了,但还是收到了同样的错误 下面是我如何调用connectGatt方法的 connectBtn.setOnClickListener(new View.OnClickListener() {
connectBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
bluetoothDevice.connectGatt(getApplicationContext(),false,Gatt);
}
});
}
});
以及我如何实例化gattcallback:
private BluetoothGattCallback Gatt= new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
super.onConnectionStateChange(gatt, status, newState);
if (status == GATT_SUCCESS) {
if (newState == BluetoothProfile.STATE_CONNECTED) {
int bondstate = bluetoothDevice.getBondState();
if (bondstate == BOND_NONE || bondstate == BOND_BONDED) {
Log.d("BLE", String.format(Locale.ENGLISH, "discovering services of '%s' with delay", bluetoothDevice.getName()));
boolean result = gatt.discoverServices();
if (!result) {
Log.i("BLE", "discoverServices failed to start");
}
} else if (bondstate == BOND_BONDING) {
// Bonding process in progress, let it complete
Log.i("BLE", "waiting for bonding to complete");
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
gatt.close();
} else {
gatt.close();
}
} else {
gatt.close();
}
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
Log.i("BLE", "OnServiceDiscovered");
super.onServicesDiscovered(gatt, status);
if (status == BluetoothGatt.GATT_SUCCESS) {
bluetoothGatt = gatt;
for (BluetoothGattService gattService : bluetoothGatt.getServices()) {
Log.i("BLE", "Service");
for (BluetoothGattCharacteristic characteristic : gattService.getCharacteristics()) {
Log.i("BLE", "characteristic");
for (BluetoothGattDescriptor gattDescriptor: characteristic.getDescriptors()) {
Log.i("BLE", "notifs");
bluetoothGatt.setCharacteristicNotification(characteristic, true);
gattDescriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
gatt.writeDescriptor(gattDescriptor);
}
}
}
}
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
super.onCharacteristicChanged(gatt, characteristic);
Log.i("BLE", "message reçu"+characteristic.getStringValue(0));
message.setText(characteristic.getStringValue(0));
}
};
}
根据我的调试,一旦程序离开ConnectionStateChange方法,就会出现错误“注册回调失败”。
你能帮我找出为什么我会犯这个错误吗?谢谢你的阅读