多次成功连接后,Android GATT 服务返回 Null

jit*_*rma 5 android bluetooth bluetooth-lowenergy

我正在开发一个连接到 BLE 设备的 Android 应用程序,设备在大部分时间都连接,我能够捕获读数。但是在多次连接断开后的某个时候,蓝牙开/关,我的BluetoothGattCallback课堂方法

onServicesDiscovered(BluetoothGatt gatt, int status)
Run Code Online (Sandbox Code Playgroud)

状态为 0 [这意味着 GATT_SUCCESS]。

现在,当我尝试获取 BluetoothGattService 时:

BluetoothGattService service = gatt.getService(getServiceUUID());
Run Code Online (Sandbox Code Playgroud)

它返回null,因此我无法执行后续步骤。请帮我找出问题所在。

小智 4

您必须首先发现给定设备的所有服务,否则当您运行时BluetoothGattService service = gatt.getService(getServiceUUID());它将返回 null。

我建议您添加该onServicesDiscovered功能并使用gatt.discoverServices();

@Override
    // New services discovered
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
            for (BluetoothGattService gattService : gattServices) {
                Log.i(TAG, "Service UUID Found: " + gattService.getUuid().toString());
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)