我试图读取存储在BluetoothGattCharacteristic
中的值。以下是我的BluetoothGattCallback
代码,其中大部分动作发生:从BluetoothGattCharacteristic读取失败
private final BluetoothGattCallback mGattCallback =
new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status,
int newState) {
if (newState == BluetoothProfile.STATE_CONNECTED) {
Log.i(TAG, "Connected to GATT server.");
Log.i(TAG, "Getting services....");
gatt.discoverServices();
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
Log.i(TAG, "Disconnected from GATT server.");
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
BluetoothGattService serv = gatt.getService(Constants.MY_UUID);
if (serv != null) {
BluetoothGattCharacteristic characteristic = serv.getCharacteristic(Constants.ANOTHER_UUID);
boolean res = gatt.readCharacteristic(characteristic);
if (res) {
Log.d(TAG, "res was true");
} else {
Log.d(TAG, "res was false");
}
}
} else {
Log.w(TAG, "onServicesDiscovered received: " + status);
}
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic,
int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
Log.d(TAG, "Succesfully read characteristic: " + characteristic.getValue().toString());
} else {
Log.d(TAG, "Characteristic read not successful");
}
}
};
所以从特征看,我尝试使用gatt.readCharacteristic()
方法,该方法的特性,并返回一个布尔值,指示成功是否操作。在这里,此方法返回false
(打印“res was false”),表示失败。
没有打印出错信息。阅读特征的正确方法是什么?为什么这种方法返回false
?
编辑: 如地狱建议,说干就干,下载所需要的资源,然后在BluetoothGatt
readCharacteristic()
方法设置断点:
这里采用的是Android-23的readCharacteristic()
方法.. \ BluetoothGatt
public boolean readCharacteristic(BluetoothGattCharacteristic characteristic) {
if ((characteristic.getProperties() &
BluetoothGattCharacteristic.PROPERTY_READ) == 0) return false;
(characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_READ)
正在返回0因此false
正在被立即返回。现在根据调试器characteristic.getProperties()
返回的值为8
,而BluetoothGattCharacteristic.PROPERTY_READ
的静态int值为0x02
。
据我所知,0x08 & 0x02
== 0.由于PROPERTY_READ
是硬编码值,我假设从characteristic.getProperties()
返回的值有问题。这里可能会出现什么问题?
即使'gatt.readCharacteristic()'返回'false',回调'onCharacteristicRead()'也会发生吗? –
不,它不会被调用。 – Orbit
我会更新我的答案,给我第二个 –