在 android 中,我通过以下 API 将读取请求发送到 BLE 设备。
boolean success = bluetoothGatt.readCharacteristic(characteristic);
并得到onCharacteristicRead
回调函数的响应。
public class GattClientCallback extends BluetoothGattCallback {
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicRead(gatt, characteristic, status);
if (status == BluetoothGatt.GATT_SUCCESS) {
//characteristic.getValue() is the reponse.
} else {
}
}
}
但我希望响应作为请求函数的返回,如下所示:
public response_type readStatus(){
bluetoothGatt.readCharacteristic(characteristic);
// Processing
return response;
}
有什么方法可以做到这一点?
最好的解决方案是使用接口:
public class GattClientCallback extends BluetoothGattCallback
{
private GattClientCallBackInterface gattClientCallBackInterface;
public void setGattClientCallBackInterface(GattClientCallBackInterface gattClientCallBackInterface)
{
this.gattClientCallBackInterface = gattClientCallBackInterface;
}
public interface GattClientCallBackInterface{
public void onCharacteristicReadSuccess(byte[] bytes);
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicRead(gatt, characteristic, status);
if (status == BluetoothGatt.GATT_SUCCESS) {
//characteristic.getValue() is the reponse.
if (gattClientCallBackInterface != null)
{
gattClientCallBackInterface.onCharacteristicReadSuccess(characteristic.getValue());
}
} else {
}
}
}
现在你只需要实现这个 GattClientCallBackInterface 接口:
YourGattClientCallbackObject.setGattClientCallBackInterface(new GattClientCallBackInterface()
{
@Override
public void onCharacteristicReadSuccess(byte[] bytes)
{
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句