这个问题可以通过以下代码示例解决:
private BluetoothGattCallback mBluetoothGattCallback = new BluetoothGattCallback(){
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
//连接状态改变时的回调
if(newState == BluetoothProfile.STATE_CONNECTED){
//已连接
gatt.discoverServices();//开始搜索服务
}else if(newState == BluetoothProfile.STATE_DISCONNECTED){
//已断开
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
//服务搜索结束时的回调
if(status == BluetoothGatt.GATT_SUCCESS){
BluetoothGattCharacteristic characteristic = gatt.getService(UUID_SERVICE).getCharacteristic(UUID_CHARACTERISTIC);
//读取特征值
gatt.readCharacteristic(characteristic);
}
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
if(status == BluetoothGatt.GATT_SUCCESS){
byte[] value = characteristic.getValue();
//读取到的特征值处理
}
}
};
BluetoothDevice device;
BluetoothGatt connectGatt = device.connectGatt(context, false, mBluetoothGattCallback);
这样,就可以成功读取特征值并处理了。