繁体   English   中英

Android BLE API中的服务v / w Gatt连接

[英]Service v/w Gatt connection in Android BLE API

我在adb日志中注意到,首先发现了服务,然后与设备建立了(gatt)连接。 是真的吗 不是先建立gatt连接,然后从从设备中发现服务。

说明:

首先,您可以在onConnectionStateChange获得设备连接状态,然后,如果设备处于连接状态,则可以使用gatt.discoverServices()发现设备。 然后,您可以在onServicesDiscovered获取服务发现的响应,状态为BluetoothGatt.GATT_SUCCESS 现在您可以在设备上书写。

代码示例:

  private BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        super.onConnectionStateChange(gatt, status, newState);

        if (newState == BluetoothProfile.STATE_CONNECTED) {
                 // Device Connected, Now Discover your service
              gatt.discoverServices(); // You need to Discovered your gatt Service first
        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {

        }

    }

    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        super.onServicesDiscovered(gatt, status);
        if (status == BluetoothGatt.GATT_SUCCESS) {
            // You can get discovered gatt service here. Now you can WRITE on your gatt service
        } 
    }

    @Override
    public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
        super.onCharacteristicWrite(gatt, characteristic, status);
        if (status == BluetoothGatt.GATT_SUCCESS) {
          //You can get WRITE characteristic response here
        }
    }

    @Override

    public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
        super.onCharacteristicRead(gatt, characteristic, status);
        if (status == BluetoothGatt.GATT_SUCCESS) {
          //You can get READ characteristic response here
        }
    }
};

希望对您有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM