接收服务时,以下功能会尝试连接服务
@Override
public void uiAvailableServices(BluetoothGatt gatt, BluetoothDevice device, List<BluetoothGattService> services) {
BluetoothGattCharacteristic c;
BluetoothGattDescriptor d;
c = gatt.getService(ForaBgGATTUUIDs.Service.SERVICE_SENSORS).getCharacteristic(ForaBgGATTUUIDs.Characteristic.CHARACTERISTIC_DATA);
byte[] data = new byte[]{0x26};
mBleWrapper.writeDataToCharacteristic(c, data);
mBleWrapper.setNotificationForCharacteristic(c,true);
mBleWrapper.requestCharacteristicValue(c);
}
将数据写入特征
public void writeDataToCharacteristic(final BluetoothGattCharacteristic ch, final byte[] dataToWrite) {
if (mBluetoothAdapter == null || mBluetoothGatt == null || ch == null) {
return;
}
// first set it locally....
ch.setValue(dataToWrite);
// ... and then "commit" changes to the peripheral
mBluetoothGatt.writeCharacteristic(ch);
}
启用描述符
的通知
public void setNotificationForCharacteristic(BluetoothGattCharacteristic ch, boolean enabled) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
return;
}
boolean success = mBluetoothGatt.setCharacteristicNotification(ch, enabled);
if(!success) {
Log.e("------", "Seting proper notification status for characteristic failed!");
}
// This is also sometimes required (e.g. for heart rate monitors) to enable notifications/indications
// see: https://developer.bluetooth.org/gatt/descriptors/Pages/DescriptorViewer.aspx?u=org.bluetooth.descriptor.gatt.client_characteristic_configuration.xml
BluetoothGattDescriptor descriptor = ch.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
if(descriptor != null) {
byte[] val = enabled ? BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE : BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE;
descriptor.setValue(val);
mBluetoothGatt.writeDescriptor(descriptor);
}
}
请求数据
public void requestCharacteristicValue(BluetoothGattCharacteristic ch) {
Log.d(TAG, "requestCharacteristicValue");
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
return;
}
mBluetoothGatt.readCharacteristic(ch);
// new value available will be notified in Callback Object
}
我期望它会在回调函数中执行上述操作后将结果发送给我,但在回调函数中它通常会告诉我已成功编写了特性。