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.
Asked
Active
Viewed 262 times
1 Answers
0
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.

pRaNaY
- 24,642
- 24
- 96
- 146
-
Thanks for the answer.But how is it possible that the I am getting the logs for the service discovery before the connection. Is there any other official(spec or Android Documentation) document to prove this? – Raulp May 07 '17 at 04:00
-
I have given answer as per my experience to connect BLE device and read-write data. Which lib you are using? – pRaNaY May 07 '17 at 04:01