我建議你在訂閱特性時應該設置ENABLE_NOTIFICATION_VALUE。這是我的代碼來做到這一點:
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
List<BluetoothGattService> services = getSupportedGattServices();
for (BluetoothGattService service : services) {
if (!service.getUuid().equals(UUID_TARGET_SERVICE))
continue;
List<BluetoothGattCharacteristic> gattCharacteristics =
service.getCharacteristics();
// Loops through available Characteristics.
for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
if (!gattCharacteristic.getUuid().equals(UUID_TARGET_CHARACTERISTIC))
continue;
final int charaProp = gattCharacteristic.getProperties();
if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
setCharacteristicNotification(gattCharacteristic, true);
} else {
Log.w(TAG, "Characteristic does not support notify");
}
}
}
} else {
Log.w(TAG, "onServicesDiscovered received: " + status);
}
}
,那麼你可以訂閱與通知特點:
public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,
boolean enabled) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID_DESCRIPTOR);
descriptor.setValue(enabled?BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
:BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
mBluetoothGatt.writeDescriptor(descriptor);
}
在這之後,你可以開始編寫到設備:
@Override
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
if (descriptor.getCharacteristic().getUuid().equals(UUID_TARGET_CHARACTERISTIC)) {
Log.i(TAG, "Successfully subscribed");
}
byte[] data = <Your data here>;
BluetoothGattService Service = mBluetoothGatt.getService(UUID_TARGET_SERVICE);
BluetoothGattCharacteristic charac = Service
.getCharacteristic(UUID_TARGET_CHARACTERISTIC);
charac.setValue(data);
mBluetoothGatt.writeCharacteristic(charac);
} else {
Log.e(TAG, "Error subscribing");
}
}
而且您將收到用於閱讀的回調onCharactersticChanged
,無需實際調用讀取操作。
記住mBluetoohGatt一次只能處理1個操作,如果你執行另一個,而前一個未完成,它不會放入隊列,但會返回false。
你是什麼意思不斷?我認爲,ble是用於傳輸少量數據的。你可以這樣使用它,但你必須單獨讀取數據塊[例如](https://developer.android.com/guide/topics/connectivity/bluetooth-le.html#read)'format = BluetoothGattCharacteristic。 FORMAT_UINT16; int heartRate = characteristic.getIntValue(format,1);' –
是的,但我發送數據的字符串,也收到相同的問題是回調方法不調用像onCharactersticChanged()和onCharacteristicRead()等 – sushma1008
把你的代碼,而不是隻是一部分。 onCharacterticChanged and onCharacteristicRead –