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

时间:2017-05-06 17:47:25

标签: android android-bluetooth android-ble

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

1 个答案:

答案 0 :(得分:0)

<强>解释

首先,您可以在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
        }
    }
};

我希望它可以帮助你。