Android BLE 读取特性

Posted

技术标签:

【中文标题】Android BLE 读取特性【英文标题】:Android BLE Reading characrteristics 【发布时间】:2017-03-26 21:34:45 【问题描述】:

我目前正在开发一个 android 应用程序以从远程设备读取温度。在远程设备上,我有一台服务器正在运行设备信息服务和健康温度计服务。我的 Android 应用程序可以扫描并检测服务及其特征。我的应用程序上有一个按钮,单击该按钮应从远程服务器请求温度。下面是在按钮单击时执行的代码。

public void readCustomCharacteristic() 
    if (mBluetoothAdapter == null || mBluetoothGatt == null) 
        Log.w(TAG, "BluetoothAdapter not initialized");
        return;
    
    /*check if the service is available on the device*/
    BluetoothGattService mCustomService = mBluetoothGatt.getService(UUID.fromString("00001809-0000-1000-8000-00805f9b34fb"));
    if(mCustomService == null)
        Log.w(TAG, "Custom BLE Service not found");
        return;
    

    /*get the read characteristic from the service*/
    BluetoothGattCharacteristic mReadCharacteristic = mCustomService.getCharacteristic(UUID.fromString("00002a1c-0000-1000-8000-00805f9b34fb"));
    Log.i(TAG, mReadCharacteristic.toString());
    BluetoothGattDescriptor descriptor = mReadCharacteristic.getDescriptor(
            UUID.fromString(GattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
    Log.i(TAG, descriptor.toString());
   // final byte[] data = descriptor.getValue();
   // Log.i(TAG, data.toString());
   // descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
    if(mBluetoothGatt.readCharacteristic(mReadCharacteristic) == false)
        Log.w(TAG, "Failed to read characteristic");
    

代码与描述符一起正确检测服务,但在读取特征时,返回的值为 false,并且我收到 Failed to read features 作为日志消息。有什么我没有做的。对此的任何建议肯定会有所帮助。 谢谢

【问题讨论】:

【参考方案1】:

正如您在https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/bluetooth/BluetoothGatt.java#919 的源代码中所见,调用返回 false 的原因基本上有三个: 1.特征不具备读属性 2. 已经有一个正在进行的 gatt 操作正在运行,您必须先等待它完成 3. gatt 对象已经关闭

【讨论】:

以上是关于Android BLE 读取特性的主要内容,如果未能解决你的问题,请参考以下文章

在 GATT Android 中获取 BLE 特性的值

GATT特性BLE读取速度慢

如何在同一个界面页面读取两个服务的两个BLE特性?

如何在Android中为BLE编写快速稳定的特性?

使用 Android BLE 读取特征值

Android BLE 无法从设备接收 Gatt 特性通知