Connecting to BLE Devices

TheBluetoothDevice 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.

device.png

TheBluetoothDevice object obtained fromgetDevice() method of theScanResult class can be used to start a BLE connection. The Bluetooth address can also be used to obtain theBluetoothDevice object using thegetRemoteDevice() method in theBluetoothAdapter class.

BluetoothDevicegetRemoteDevice(String address)

TheconnectGatt() method of theBluetoothDevice class is used to create a connection with the desired remote device. TheconnectGatt() 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.

BluetoothGattconnectGatt(Context context, boolean autoConnect,BluetoothGattCallback callback)

TheonConnectionStateChange() method of theBluetoothGattCallback class provides information on when the central device has connected/disconnected to/from the remote peripheral device. Other relevant methods of theBluetoothGattCallback class for different GATT operations will be discussed in the following sections as needed.

voidonConnectionStateChange(BluetoothGatt gatt, int status, int newState)

The results provided by theonConnectionStateChange() 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_CONNECTEDIn connected state
STATE_CONNECTINGIn connecting state
STATE_DISCONNECTEDIn disconnected state
STATE_DISCONNECTINGIn disconnecting state

TheBluetoothGatt class additionally providesdisconnect() method to disconnect an active BLE connection or cancel a connection attempt currently in progress and theconnect() method to be able to connect back to the remote device.

voiddisconnect()

booleanconnect()

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 theonServiceConnected() callback for the BLE service as shown in the screenshot below.

connect.png

Theconnect() method in BLEService calls theBluetoothDevice.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.

connectex.png