有时(经常)在连接到设备并调用discoverServices()之后,等待调用onServicesDiscovered()之后,尝试获取指定UUID的BluetoothGattService返回null。
@Override
public void onServicesDiscovered(final BluetoothGatt gatt, int status) {
EDLogger.e(this, "onServicesDiscovered");
if (status == BluetoothGatt.GATT_SUCCESS) {
mEDServiceHandler.postAtFrontOfQueue(() -> {
if (gatt.getServices() == null) {
Log.d(TAG, "GATT returned NULL services");
return;
}
// *** this is the call that often returns null ***
BluetoothGattService service = gatt.getService(UUID.fromString(myServiceUUID));
if (service == null) {
Log.d(TAG, "Service is NULL in onServicesDiscovered");
return;
}
BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString(EDAttributes.getDataPacket()));
if (characteristic != null) {
mNotifyCharacteristic = characteristic;
setCharacteristicNotification(characteristic, true);
}
});
}
}
UUID是正确的,并且最终上面的代码将起作用,但是通常,例如在打开设备后立即,上面的getService()调用将返回null。我知道该设备提供了这项服务,因为1.)它可以在iOS上运行,并且2.)如果我断开连接(调用BluetoothGatt.disconnect(),等待STATE_DISCONNECTED,然后调用BluetoothGatt.close()),并经常重新连接, getService()最终将返回实际的服务。我不知道我在做什么错。任何见识绝对值得赞赏!