Connecting to a GATT Server
suggest changeOnce 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.");
}
}
};
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents