我对来自我的 Android 应用程序和一个外围设备的 ble 通信有一个疑问。该外围设备通过通知某个特性“A”发送数据,我可以在另一个特定特性“B”上写入数据。为此,我这样做:
Semaphore sem = new Semaphore(1);
void notifyActivation()
{bluetoothGatt.setCharacteristicNotification(characteristic, true);
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
if(descriptor != null )
{
try
{
sem.acquire();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
Log.i("debug","scrittura descrittore");
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
bluetoothGatt.writeDescriptor(descriptor);
}
}
@Override
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status)
{
super.onDescriptorWrite(gatt, descriptor, status);
Log.i("debug", "descriptor status: "+status);
sem.release();
}
public void write(final BluetoothGattCharacteristic characteristic)
{
new Thread(new Runnable() {
@Override
public void run() {
try {
//acquisisco il semaforo se è libero se no mi blocco
sem.acquire();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
boolean res=bluetoothGatt.writeCharacteristic(characteristic);
if(!res)
{
Log.i("debug","scrittura fallita");
//res=bluetoothGatt.writeCharacteristic(characteristic);
}
sem.release();
}
}).start();
}
我使用了信号量,因为如果我在调用 ondescriptorwrite 之前进行写入,则写入失败,但我想知道这样我是否会丢失一些通知。
信号量是否以正确的方式使用?或者它会给我带来一些问题?