簡體   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