我試圖讀取存儲在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
我會更新我的答案,給我第二個 –