如何编写一个将执行BLE请求并返回相应响应的方法?

时间:2019-06-05 08:41:03

标签: android bluetooth-lowenergy

在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;
}

该怎么做?

1 个答案:

答案 0 :(得分:1)

最好的解决方案是使用Interface:

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)
                {

                }
            });