通过阅读官方的nRF Toolbox APP的源码, 按照它的初始化方法对指定的UUID服务蓝牙对象进行初始化,就可以接收消息了:
具体代码如下:
@Override
public void onServicesDiscovered(final BluetoothGatt bleGatt, int status) {
Log.d(TAG, "onServicesDiscovered: services size: " + bleGatt.getServices().size());
List<BluetoothGattService> serviceList = bleGatt.getServices();
Observable.from(serviceList)
.flatMap(new Func1<BluetoothGattService, Observable<BluetoothGattCharacteristic>>() {
@Override
public Observable<BluetoothGattCharacteristic> call(BluetoothGattService bleGattService) {
return Observable.from(bleGattService.getCharacteristics());
}
})
.filter(new Func1<BluetoothGattCharacteristic, Boolean>() {
@Override
public Boolean call(BluetoothGattCharacteristic bleGattChar) {
Log.e(TAG, "cc: " + bleGattChar.getUuid().toString());
if(bleGattChar.getUuid().toString().equals(UUID_RECEIVE)){
// bleGatt.requestMtu(0);
// boolean b = bleGatt.setCharacteristicNotification(bleGattChar, true);
enableNotifications(bleGatt, bleGattChar);
// service.SET
//Log.e(TAG, "boolean bleGattChar:" + b);
}
return bleGattChar.getUuid().toString().equals(UUID_SEND);
}
})
.subscribe(new Action1<BluetoothGattCharacteristic>() {
@Override
public void call(BluetoothGattCharacteristic bleGattChar) {
/* if(bleGattChar.getUuid().toString().equals(UUID_RECEIVE)){
bleGatt.setCharacteristicNotification(bleGattChar, true);
Log.e(TAG, "CC bleGattChar: " + bleGattChar.getUuid().toString());
}*/
if(bleGattChar.getUuid().toString().equals(UUID_SEND)){
mBleGattChar = bleGattChar;
}
}
});
}protected final boolean enableNotifications( BluetoothGatt gatt ,final BluetoothGattCharacteristic characteristic) {
if (gatt == null || characteristic == null)
return false;// Check characteristic property
final int properties = characteristic.getProperties();
if ((properties & BluetoothGattCharacteristic.PROPERTY_NOTIFY) == 0)
return false;Log.d("BLE", "gatt.setCharacteristicNotification(" + characteristic.getUuid() + ", true)");
gatt.setCharacteristicNotification(characteristic, true);
final BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID);
if (descriptor != null) {
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
Log.v("BLE", "Enabling notifications for " + characteristic.getUuid());
Log.d("BLE", "gatt.writeDescriptor(" + CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID + ", value=0x01-00)");
return gatt.writeDescriptor(descriptor);
}
return false;
}