微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 TinyB 的线程安全并发蓝牙LE

如何解决使用 TinyB 的线程安全并发蓝牙LE

有很多关于 Android BluetoothLE 编程的信息,但我正在设计一个使用 TinyB (github page,Java documentation) 的小型蓝牙应用程序,它具有与 Android 类似的 API BluetoothLE 库。

我是 Java 并发编程的新手,并且在这里和那里阅读了一些关于最佳实践的章节。不过,我不确定的是处理多个蓝牙连接的最佳做法。

为了连接设备,过程相当简单:

// Get the bluetooth manager and start discovery
BluetoothManager manager = BluetoothManager.getBluetoothManager().startdiscovery();



BluetoothDevice device = null ;
List<BluetoothDevice> list = manager.getDevices() ; 

for(Bluetooth device : list){
    // find your device based on what address you're looking for
}

// find the GATT service and characteristic you want to write to
BluetoothGattService tempService = getService(device,"xxxxx-xxxxx-xxxx-xxxx");
BluetoothGattCharacteristic tempValue = getCharacteristic(tempService,"xxxx-xxxx-xxxx-xxxx");

// write to the characteristic
byte[] config = {0x01} ;
tempValue.writeValue(config) ;

代码主要取自Intel-iot-devkit's hello TinyB

所以这非常适合一次连接到一台设备。对于多个连接,我想我可以有一个 ExecutorService 来运行创建连接或配对的任务,但是如果多个线程尝试同时使用 BluetoothManager 怎么办?这是允许的还是应该同步 BluetoothManager

编辑

没有阅读我引用的程序的评论,我感到很惭愧,但显然一次只能引用一个 BluetoothManager。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。