Android Service for Bluetooth® Low Energy

Last modified by Microchip on 2023/11/09 08:53

The BLE functionality is enabled through an Android Service by the app so that the BLE can be active in the background to perform operations such as maintaining an existing connection and continue performing access operations when the app is not in the foreground. BLEService class in BLEService.java file in the MCHPTransparentUART Android app example provides the BLE service with methods and callbacks.

An Android Service is an application component that can perform long-running operations in the background and doesn't provide a user interface. Another application component can start a service and can continue to run in the background even if the user switches to another application. Additional information on Services can be found on the "Services Overview" page.

The Android service must be declared in the Android manifest as one of the application components.

App manifest AndroidManifest.xml in the MCHPTransparentUART Android app example declares the BLE service. The BLE service declared in the AndroidManifest.xml is highlighted in the accompanying image.

BLE service declared in the AndroidManifest.xml

The PeripheralControlActivity activity uses BLEService for all the BLE operations. The PeripheralControlActivity being the client of the BLEService binds to the service by calling the bindService() method in the onStart() method at the start of the activity. The bindService() call with the BLEService connects to the BLEService application service, creating the service if needed.

The bindService() call with the BLEService

The PeripheralControlActivity can disconnect from the BLEService by calling the unbindService() with the BLEService connection handle.

BLEService connection handle

It should be noted that bindService() and unbindService() should be called in matching Android activity state callbacks at the beginning (e.g. onStart()) and ending (e.g. onStop()).

Back to Top