【发布时间】:2014-10-09 00:54:34
【问题描述】:
我正在对 BLE 设备执行一系列特征读取。因为readCharacteristic() 是异步执行的,而且我们必须等到它完成才能发出另一个“读取”调用,所以我使用了wait() 的锁,然后在'onCharacteristicRead() 中使用notify() 锁来让事情重新开始。
当我在拨打readCharacteristic() 之后wait() 时,我从来没有接到过onCharacteristicRead() 的电话。如果我不wait(),那么我会接到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() 是异步的,为什么调用线程的执行与实际执行读取的能力或调用回调的能力有任何关系?
为了让事情更加混乱,我展示了一个 toast,它在我调用 readCharacteristic() 以及调用 onCharacteristicRead() 时标识线程。这两个线程有不同的名称。我认为可能出于某种原因在调用线程上调用了回调,但事实并非如此。那么线程是怎么回事呢?
【问题讨论】:
标签: java android multithreading bluetooth-lowenergy android-bluetooth