我正在针对BLE设备实现一系列特征读取.因为readCharacteristic()异步执行,并且因为我们必须等待直到完成才发出另一个“读”调用,所以我用了一个锁来等待()然后在’onCharacteristicRead()中我通知()锁,让事情再次发生.
当我等待()调用readCharacteristic()后,我从未得到onCharacteristicRead()的调用.如果我不等待(),那么我会调用onCharacteristicRead()并且报告正确的值.
这是相关的代码似乎阻止对onCharacteristicRead()的回调:
private void doRead() {
//....internal accounting stuff up here....
characteristic = mGatt.getService(mCurrServiceUUID).getCharacteristic(mCurrCharacteristicUUID);
isReading = mGatt.readCharacteristic(characteristic);
showToast("Is reading in progress? " + isReading);
showToast("On thread: " + Thread.currentThread().getName());
// Wait for read to complete before continuing.
while (isReading) {
synchronized (readLock) {
try {
readLock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public void onCharacteristicRead(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic,int status) {
showToast("onCharacteristicRead()");
showToast("On thread: " + Thread.currentThread().getName());
byte[] value = characteristic.getValue();
StringBuilder sb = new StringBuilder();
for (byte b : value) {
sb.append(String.format("%02X",b));
}
showToast("Read characteristic value: " + sb.toString());
synchronized (readLock) {
isReading = false;
readLock.notifyAll();
}
}
如果我只是删除上面的while()语句,我成功地得到读回调.当然,这阻止我等待进一步阅读,所以我不能等待前进.
由于readCharacteristic()是异步的,为什么执行调用线程与实际执行读取的能力有关,还是调用回调的能力?
为了使事情变得更加混乱,我会在调用readCharacteristic()时以及onCharacteristicRead()被调用时显示一个标识线程的吐司.这两个线程具有不同的名称.我以为可能是因为某些原因在调用线程上调用了回调,但是似乎并非如此.那么这里的线程是怎么回事?