简体   繁体   中英

Service v/w Gatt connection in Android BLE API

I am noticing in the adb logs that the services are discovered first and then the (gatt) connection is made with the device . Is it true? Isn't the gatt connection is made first and then the services are discovered from the slave device.

Explanation:

First you can get device connection state in onConnectionStateChange , Then if your device is connected state, you can Discover your device using gatt.discoverServices() . Then you can get service discovered response in onServicesDiscovered as state BluetoothGatt.GATT_SUCCESS . Now You can write on your device.

Code example:

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

I hope it's helps you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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