我试图读取存储在BluetoothGattCharacteristic
. 以下是我的BluetoothGattCallback
代码,大部分操作都在其中发生:
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
?
编辑:
按照 Inferno 的建议,继续下载所需的源代码,然后在BluetoothGatt
readCharacteristic()
方法中设置断点:
这是readCharacteristic()
android-23..\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()
. 这里可能出了什么问题?