Connecting to a GATT Server

suggest change

Once you have the BluetoothDevice, connect with connectGatt(). Pass a Context, whether to connect automatically when the device is available, and a BluetoothGattCallback that receives connection events and operation results. The four-argument form, including TRANSPORT_AUTO, exists from API 23.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        device.connectGatt(context, false, bluetoothGattCallback, BluetoothDevice.TRANSPORT_AUTO);
    } else {
        device.connectGatt(context, false, bluetoothGattCallback);
    }

Override onConnectionStateChange to receive connection and disconnection events. A STATE_CONNECTED result is not ready for characteristic reads until you call gatt.discoverServices(). Check status as well as newState. GATT_SUCCESS is the status that means the state change succeeded.

BluetoothGattCallback bluetoothGattCallback =
    new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status,
        int newState) {
    if (status != BluetoothGatt.GATT_SUCCESS) {
        Log.i(TAG, "GATT connection change failed: " + status);
        return;
    }
    if (newState == BluetoothProfile.STATE_CONNECTED) {
        Log.i(TAG, "Connected to GATT server.");
        gatt.discoverServices();
    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        Log.i(TAG, "Disconnected from GATT server.");
    }
}
};

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents