我正在尝试连续读取 BLE 设备的特性。
我在我的服务类中创建了一个 Runnable:
private class BackgroundRunnableForRead implements Runnable
{
private volatile boolean isRunning = true ;
@Override
public void run() {
try {
BluetoothLeService.this.backgroundRunID = Thread.currentThread().getId();
while( isRunning) {
List<BluetoothGattService> gattServices = BluetoothLeService.this.getSupportedGattServices();
if (gattServices != null && gattServices.size() > 0) {
BluetoothGattCharacteristic characteristic = getCharacteristic(gattServices);
if (characteristic != null && (characteristic.getProperties() & 2) > 0) {
BluetoothLeService.this.readCharacteristic(characteristic);
}
}
}
}
catch(Exception e)
{
isRunning= false;
e.printStackTrace();
}
}
public void kill()
{
this.isRunning = false;
}
}
在成功发现我调用的服务时:
public void startReadingCharacteristics()
{
System.out.println("BluetoothLeService.startReadingCharacteristics");
this.mBackgroundRunnable = new BackgroundRunnableForRead();
mReadThread = new Thread(mBackgroundRunnable);
mReadThread.start();
}
这是我的特征读取回调 -
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic,
int status) {
System.out.println("BluetoothLeService.onCharacteristicRead" + status);
if (status == BluetoothGatt.GATT_SUCCESS) {
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}
}
该应用程序在 Nexus 5、Nexus 4 和 Motorola G 上运行良好。
当我在 Samsung S6 上运行这段代码时它不起作用,onCharacteristicRead()
没有被调用。
我读到,连续调用 readCharacteristics()
会在等待 onCharacteristicRead 执行时导致问题。
最佳答案
建议一次只执行一个 gatt 命令,因为 commands are not stacked .因此,您必须实现某种机制,以便在获得当前读取回调后调用下一次读取。
请记住,gatt 回调可以来自不同的线程,但如果您将读取的值保存在回调中,然后从那里触发下一次读取,这应该没有问题。
关于Android 蓝牙 LE - 读取特性不适用于三星,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36658001/