【发布时间】:2020-03-05 14:30:17
【问题描述】:
我有一个问题导致需要从一件事到另一件事按顺序等待。我目前通过设置 3 个具有不同延迟的可运行对象来做到这一点,以允许数据的顺序流出现在我的蓝牙连接上。然而,虽然这确实有效,但我觉得必须有一个更好/更清洁的实现。我现在的代码如下。
我的代码是这样工作的:
- 写命令1
- 等到命令写入
- 写命令2
- 等到命令写入
- 写命令3
- 等到命令写入
请您给我一些建议,告诉我如何以更好的方式一个接一个地执行我的写入功能。
Handler h =new Handler() ;
h.postDelayed(new Runnable() {
public void run() {
Log.d(TAG, "Write 1");
mBluetoothLeService.writeCharacteristic(10);
}
}, 1000);
Handler h1 =new Handler() ;
final int Command_to_run = value;
h1.postDelayed(new Runnable() {
public void run() {
Log.d(TAG, "Write 2");
mBluetoothLeService.writeCharacteristic(Command_to_run);
}
}, 2000);
Handler h2 =new Handler() ;
h2.postDelayed(new Runnable() {
public void run() {
Log.d(TAG, "Write 3");
mBluetoothLeService.writeCharacteristic(20);
}
}, 3000);
编写代码
public void writeCharacteristic(int Data) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
byte[] value = intToByteArray(Data);
BluetoothGattService mCustomService =
mBluetoothGatt.getService(UUID.fromString("f3641400-00b0-4240-ba50-
05ca45bf8abc"));
if(mCustomService == null){
Log.w(TAG, "Custom BLE Service not found");
return;
}
/*get the read characteristic from the service*/
BluetoothGattCharacteristic characteristic =
mCustomService.getCharacteristic(UUID.fromString("f3641401-00b0-4240-
ba50-05ca45bf8abc"));
characteristic.setValue(value);
mBluetoothGatt.writeCharacteristic(characteristic);
}
【问题讨论】:
-
我认为像这样的
mBluetoothLeService.writeCharacteristic(10);调用已经阻塞了线程,因此在不需要处理程序的情况下按顺序使用它们可以成为您的解决方案。我不认为那个函数是异步的,所以如果它返回true,你可以写下一个。它们是boolean函数,所以如果它返回true,你可以切换到下一个。 -
不幸的是,我不这么认为。我已经修改了我的主要问题以包括函数本身。其中,返回无效。话虽如此,我认为我可以更改代码以包含来自 mBluetoothGatt.writeCharacteristic 的嵌入式布尔返回。但是,一旦完成,这会返回 true 吗?
-
我相信是的。我检查了源代码,如果它在其中抛出异常,它会返回 false。否则,无论成功与否,都会返回。
-
邪恶的我会考虑改变它。您能否将其发布为答案。
-
@FurkanYurdakul 我已经实现了一个布尔检查写入是否完成,这解决了我的问题并加快了传输速度。请您将其发布为答案。
标签: java android bluetooth-lowenergy delay wait