android - 使 READ、WRITE 和 NOTIFY 在 Android BLE(版本 21 及更高版本)上工作

标签 android bluetooth notifications bluetooth-lowenergy

在我的应用程序中,我获得了READWRITE 以处理特定的BluetoothGattCharacteristic 对象。 BluetoothGattCallback onCharacteristicWriteonCharacteristicRead 被正确调用。 然后我尝试设置 NOTIFY 选项,以便在设备上的特定特征发生变化时通知我的 Android 应用程序。 我已通过以下代码进行设置:

// Local notifications
mGatt.setCharacteristicNotification(statusTypeCharacteristic, notify);

// Remote notifications
BluetoothGattDescriptor desc = statusTypeCharacteristic.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));

Log.d("Descriptor", desc.toString());

boolean test;
test = desc.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);  // return value = true
test = mGatt.writeDescriptor(desc);  // return value = true

当特性发生变化时,回调:onCharacteristicChanged 正在按预期调用

但是,现在所有的READWRITE 操作都不再有效了。 当我评论处理描述符的行时,READWRITE 再次起作用。

我非常不清楚的部分是用于获取描述符的 UUID。这是正确的吗?我是否应该扫描特征中的所有描述符并在其中一个上启用通知?当我有多个返回时,我怎么知道要设置哪一个?

最佳答案

好的,所以我已经弄清楚了这个问题。 在我的应用程序开始时,我正在配置(即写入)许多描述符。 2个问题: 1- 一次只能写入一个描述符 2- 写入描述符时不会发生读/写操作

解决方法是创建一个写入描述符操作队列,并在 onDescriptorWrite 回调中执行下一个描述符写入。

private void writeGattDescriptor(BluetoothGattDescriptor d) {
    //put the descriptor into the write queue
    descriptorWriteQueue.add(d);
    //if there is only 1 item in the queue, then write it. If more than 1, we handle asynchronously in the
    // callback
    if(descriptorWriteQueue.size() == 1) {
        mGatt.writeDescriptor(d);
    }
}

然后在回调中:

@Override
    public void onDescriptorWrite (BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
        // Called when the descriptor is updated for notification
        Log.d("onDescriptorWrite", descriptor.getUuid().toString());

        // pop the item that we just finishing writing
        descriptorWriteQueue.remove();

        // if there is more to write, do it!
        if(descriptorWriteQueue.size() > 0) {
            mGatt.writeDescriptor(descriptorWriteQueue.element());
        }

        // Inform the framework that the scope has connected, configured and ready to process commands
        if(descriptorWriteQueue.size() == 0) {
            // Do something else, such as reads and writes
        }
    }

关于android - 使 READ、WRITE 和 NOTIFY 在 Android BLE(版本 21 及更高版本)上工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37082059/

相关文章:

iphone - Objective-c 重新路由来自蓝牙 HFP 的音频输入,以与耳机插孔中的音频混合

ios - 类型 'UITextField' 没有成员 'textDidBeginEditingNotification'

iphone - 委托(delegate)VS。 iPhoneOS 中的通知

android - 当我翻转手机时,Kivy Android APK 崩溃

java - 安卓数据表

ios - iOS 中的健康设备配置文件 (HDP) 支持

ruby-on-rails - 如何发送通知用户收到私有(private)消息

android - 不兼容的 gradle 依赖项

android - 使用 OpenGL ES 的 SurfaceView

swift - 试图在 Swift 中将类型 (BigEndian) 的 NSData 从 BlueTooth 转换为 Little Endian 类型的 Int