java Android gatt回调示例。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java Android gatt回调示例。相关的知识,希望对你有一定的参考价值。

public class MyGattCallback extends BluetoothGattCallback {

    public MyGattCallback() {
    }

    /**
     * Call whenever BluetoothGatt changes it's state
     *
     * @param gatt     mGatt object
     * @param status   current status of Gatt
     * @param newState new stata of Gatt
     */
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        if (newState == BluetoothProfile.STATE_CONNECTED) {
            EventBus.getDefault().post(new Events.DeviceConnectedEvent());
            EventBus.getDefault().post(new Events.StateConnectedEvent(gatt));
        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
            EventBus.getDefault().post(new Events.DeviceDisconnectedEvent());
        }
    }

    /**
     * calls after new service discovered in GATT
     *
     * @param gatt   mGatt object
     * @param status current status
     */
    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        EventBus.getDefault().post(new Events.ServicesDiscoveredEvent(gatt));
    }

    /**
     * calls when write to gatt failed
     *
     * @param gatt           mGatt object
     * @param characteristic characteristic that failed
     * @param status         current status
     */
    @Override
    public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
        super.onCharacteristicWrite(gatt, characteristic, status);
        if (status != 0) {
            EventBus.getDefault().post(new Events.GattWriteFailedEvent(gatt));
        }
    }

    /**
     * calls whenever wired to notification GATT service's characteristics
     * changed it's own state
     *
     * @param gatt           mGatt object
     * @param characteristic changed characteristics object
     */
    @Override
    public void onCharacteristicChanged(BluetoothGatt gatt,
                                        BluetoothGattCharacteristic c) {
        EventBus.getDefault().post(new Events.CharacteristicChangedEvent(c));
    }

}

以上是关于java Android gatt回调示例。的主要内容,如果未能解决你的问题,请参考以下文章

Android BLE GATT 断开与设备断开

找出 Android 蓝牙 LE GATT 配置文件

使用绑定设备时的 gatt.writeDescriptor 错误状态回调

我在 Android 应用程序(Java)和 ESP32 BLE 服务器之间的 Gatt 连接有问题

无法使用 BLE gatt 回调函数连续读取数据

我想知道 BLE gatt 的设置完成时间,比如回调