Android BLE API中的服务V/W GATT连接



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

我希望对您有帮助。

最新更新