在我的应用程序中执行以下代码:
gatt[0] = bluetoothAdapter.getRemoteDevice(macAddress).connectGatt(context, true, new AbstractCallback(subscriber) {
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
... // do something with new characteristic value
}
})
AbstractCallback的位置是:
private abstract class AbstractScaleCallback extends BluetoothGattCallback {
... // fields and constants
private final byte[] TURN_ON_COMMAND = ...
private static final String COMMAND_CHARACTERISTIC_UUID = ...
private BluetoothGattCharacteristic commandCharacteristic;
private Subscription subscriber;
AbstractScaleCallback(Subscription subscriber) {
this.subscriber = subscriber;
}
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
if (newState == BluetoothProfile.STATE_CONNECTED) {
gatt.discoverServices();
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
gatt.close();
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
... // find other characteristics
commandCharacteristic = measurementService.getCharacteristic(UUID.fromString(COMMAND_CHARACTERISTIC_UUID));
commandCharacteristic.setValue(TURN_ON_COMMAND);
gatt.writeCharacteristic(commandCharacteristic);
}
}
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
if (characteristic.getUuid().equals(UUID.fromString(COMMAND_CHARACTERISTIC_UUID)) && Arrays.equals(characteristic.getValue(), TURN_ON_COMMAND)) {
if (status == BluetoothGatt.GATT_SUCCESS) {
... // set up characteristic notifications
} else {
... // throw error
}
}
}
}
在我的所有测试设备上,代码从应用程序端产生相同的结果 - 所有回调都按正确的顺序调用, gatt.writeCharacteristic(commandCharacteristic)方法返回' true& #39 ;.但似乎在某些设备上,外围设备的特征值保持不变。即便如此,特征变更通知似乎也可行 从我发现的,所有有问题的设备似乎共享相同系列的SoC - Snapdragon 600 有谁知道可能是什么问题以及如何解决它?