The BluetoothDevice class is used to initiate a connection with the remote device that has been found and identified by the scanning procedure described in the previous section. The Bluetooth® adapter can be used to get the remote device to start a connection.
The BluetoothDevice object obtained from getDevice() method of the ScanResult class can be used to start a BLE connection. The Bluetooth address can also be used to obtain the BluetoothDevice object using the getRemoteDevice() method in the BluetoothAdapter class.
BluetoothDevice getRemoteDevice(String address)
The connectGatt() method of the BluetoothDevice class is used to create a connection with the desired remote device. The connectGatt() method takes the current context, the auto connect when the remote device is available option, the callback for the asynchronous callback for the GATT connection status result, and all the GATT client operations.
BluetoothGatt connectGatt(Context context, boolean autoConnect, BluetoothGattCallback callback)
The onConnectionStateChange() method of the BluetoothGattCallback class provides information on when the central device has connected/disconnected to/from the remote peripheral device. Other relevant methods of the BluetoothGattCallback class for different GATT operations will be discussed in the following sections as needed.
void onConnectionStateChange(BluetoothGatt gatt, int status, int newState)
The results provided by the onConnectionStateChange() method provide the status of the connect or disconnect operation (GATT_SUCCESS if operation succeeds) and the new connection state as indicated in the following table.
STATE_CONNECTED | In connected state |
STATE_CONNECTING | In connecting state |
STATE_DISCONNECTED | In disconnected state |
STATE_DISCONNECTING | In disconnecting state |
The BluetoothGatt class additionally provides disconnect() method to disconnect an active BLE connection or cancel a connection attempt currently in progress and the connect() method to be able to connect back to the remote device.
void disconnect()
boolean connect()
The MCHP Transparent UART Android™ app handles connection and discovery for BLE peripherals in the PeripheralControlActivity activity (PeripheralControlActivity.java). In PeripheralControlActivity, the connection to the peripheral device selected in the PeripheralScanActivity is attempted in the onServiceConnected() callback for the BLE service as shown in the screenshot below.
The connect() method in BLEService calls the BluetoothDevice.connect() method to attempt a BLE connection with the peripheral as shown in the screenshot below. BluetoothGatt.connect() method is called if the peripheral is previously connected.