Bluetooth Low Energy

BLE is wireless technology.It gives context to the environment around you.It perfect for devices that run for long periods on power sources, such as coin cell batteries.

Key Benefit

  • low power consumption.
  • small size.
  • connectivity to mobile phones.
  • low cost,robust,efficient.
  • multi-vendor interoperability.
  • global availability, license free.


BLE device remains in sleep mode constantly except for when a connection is initiated. The actual connection times are only a few ms, while Bluetooth takes ~100ms. The reason the connections are short is that the data rates are high at 1 Mb/s.

  • keeping the radio off.
  • Lower standby time, Faster connection, Lower peak power.
  • BLE technology uses only 3 advertising channels.

Bluetooth Low Energy example

In the example, the Android app running on an Android device is the GATT client. The app gets data from the GATT server, which is a BLE Battery Level Detector that supports the Battery Level Service.

BLE Permissions

You need BLUETOOTH permission to perform requesting a connection, accepting a connection, and transferring data.You must also declare the BLUETOOTH_ADMIN permission for device discovery or manipulate Bluetooth settings.

Android 6.0+ (API level 23+), users grant permissions to apps while the app is running, not when they install the app.

Get the BluetoothAdapter

The BluetoothAdapter represents the device’s Bluetooth adapter.There’s one Bluetooth adapter for the entire system, and your application can interact with it using this object.

Enable Bluetooth

If Bluetooth but disabled, then you can request that the user enable Bluetooth without leaving your application.

Scan BLE Devices

To scan BLE devices, you use the startScan() method.Scanning is battery-intensive, you should observe the following guidelines:

  • After finding the desired device, stop scanning.
  • Set a time limit on your scan. A device that was previously available may have moved out of range, and continuing to scan drains the battery.

startScan() method takes a ScanCallback as a parameter. You must implement this callback for results are returned.

The following snippet shows how to start and stop a scan

In this example, app provides an activity BluetoothDetectorActivity to connect and display data and display GATT services and characteristics supported by the device.

Ble Client
Battery Level Detector

Connecting to a GATT Server(BLE Device)

Based on user input, Activity communicates with a Service called BluetoothLEService, which interacts with the BLE device via the Android BLE API

BluetoothGattCallback: Used to deliver results to the client, such as connection status, as well as any further GATT client operations. 

The first step in interacting with a BLE device is connecting to the GATT server on the device. To connect to a GATT server on a BLE device, you use the connectGatt() method.

When a particular callback is triggered, it calls the broadcastUpdate() helper method and passes it an action. Data parsing in this section is performed in accordance with the Bluetooth Battery Service Measurement profile specifications

To enable or disable notifications for a given characteristic setCharacteristicNotification to
BluetoothGatt.Reads the requested characteristic from the associated remote device set

In BatteryDetectorActivity, these events are handled by a BroadcastReceiver.

The Following snippet show display Gatt connected service

Connect Bluetooth service

Closing the Client App

Once your app has finished using a BLE device, it should call close() so the app can release resources appropriately.

How to test BLE Client?

The BLE Peripheral Simulator is an Android app that allows developers to try out new features of app Bluetooth without the need for a BLE Peripheral Device.

BLE Peripheral with one of three services:

  • Battery Service
  • Heart Rate Service
  • Health Thermometer Service

Use the  Bluetooth features to connect to the app to Read and Write Characteristics, Subscribe to Notifications for when the Characteristics change, and Read and Write Descriptors.

The device in the central role scans, looking for advertisement of Battery Level Detector.

The device in the peripheral role makes the advertisement of Battery Level.

Download this project from GitHub.



Android MQTT Client

MQTT is a machine-to-machine /Internet of Things connectivity protocol. It’s designed to following use case.

  1. Lightweight publish-subscribe based messaging protocol for use on top of the TCP/IP protocol.
  2. Connections to remote locations where a small code is required or the network bandwidth are limited.

MQTT Broker

The publish-subscribe messaging pattern requires a message broker. The broker is responsible for distributing messages to interested clients based on the topic of a message.It also holds the session of all persisted clients including subscriptions and missed messages.

There is a publically accessible sandbox server for the Eclipse IoT projects available at

MQTT Client

Eclipse Paho project provides open-source client implementations of MQTT.Paho Android Service is an MQTT client library written in Java for developing applications on Android.

The MQTT connection is encapsulated within an Android Service that runs in the background of the Android application, keeping it alive when the Android application is switching between different Activities.The Paho Android Service is an interface to the Paho Java MQTT Client library for the Android Platform.


Download  Paho Android Service and Android MQTT Client library.Go to your libs folder inside app folder and paste all your .jar

To add the Paho Android Service as a dependency to you app add the following parts to your gradle file.


The Paho Android Service needs the following permissions to work.

To be able to create a binding to the Paho Android Service, the service needs to be declared in the AndroidManifest.xml. Add the following within the <application> tag

MQTT Connection Option

MqttAndroidClient will connect with MQTT 3.1.1 by default. To intentionally connect with MQTT 3.1  MqttConnectOptions object can be supplied to the connect method

Clean session

On connection, a client sets the “clean session” flag.If the clean session is set to false, means when the client disconnects, any subscriptions it has will remain and any subsequent QoS 1 or 2 messages will be stored until it connects again in the future. If the clean session is true, then all subscriptions will be removed from the client when it disconnects.

Automatic Reconnect

Sets whether the client will automatically attempt to reconnect to the server if the connection is lost.It will initially wait 1 second before it attempts to reconnect, for every failed to reconnect attempt, the delay will double until it is at 2 minutes at which point the delay will stay at 2 minutes.


When a client connects to a broker, it may inform the broker that it has a will. This is a message that it wishes the broker to send when the client disconnects unexpectedly. The will message has a topic, QoS and retains status just the same as any other message.

Receive MQTT Message

Disconnect Options

Messages published to the topic if the connection is available, but if it disconnects and connects again offline messages send.Holds the set of options that govern the behavior of Offline (or Disconnected) buffering of messages.

Create MQTT Client

Creates an instance of an Android MQTT client, that will bind to the Paho Android Service. By calling the connect method of the MqttAndroidClient the client will asynchronously try to connect to the MQTT broker and return a token. That token can be used to register callbacks, to get notified when either the MQTT-connection gets connected or an error occurs

Publish Message

The MqttAndroidClient allows messages to be published via its publish method.


Subscriptions can be created via the MqttAndroidClient.subscribe method, which takes the topic and the QOS as parameters and returns a IMqttToken.


Disconnect MQTT Client

Download this project from GitHub.


MQTTBox enables you to create MQTT clients to publish or subscript topics, create MQTT virtual device networks, load test MQTT devices or brokers.

Config MQTT Client

1.Create MQTT client

2.Config MQTT client

Host :

Protocol : mqtt/tcp

MQTT Protocol



Creating and Monitoring Geofences

Geofencing is a location-based service, that sends a notification to a smartphone who enter a defined geographic area.

For example, human resource department to monitor employees working in special locations or child location services can notify parents if a child leaves a designated area.

1.Set up for Permission

To use geofencing, your app must request ACCESS_FINE_LOCATION.To request this permission, add the following element as a child element of the <manifest> element in your app manifest

2.Google Play Service

Google Play services are used for access the location provider.Download and install the Google Play services component via the SDK Manager and add the library to your project. For details, see the guide to Setting Up Google Play Services.

3.Connect to Google Play Services

Create an instance of Google API Client in activity’s onCreate() method. Use GoogleApiClient.Builderclass to add the LocationServices API, as the following code snippet shows.

Android 6.0+ (API level 23+), users grant permissions to apps while the app is running, not when they install the app.

Here is an example activity that implements the callback interfaces that adds  to the Google API Client

To connect, call connect() from the activity’s onStart() method. To disconnect, call disconnect() from the activity’s onStop() method.

4.Request Location Updates

Your app must connect to location services and make then a location request.Once a location request is in place you can start the regular updates by calling requestLocationUpdates().

Do this in the onConnected() callback provided by Google API Client, which is called when the client is ready.

Stop Location Updates

whether you want to stop the location updates when the activity is no longer in focus.

5.Create geofence objects

To create geofence object you need Latitude, Longitude, and Radius, Expiration time, Transition type, Geofence ID

Your app needs to create and add geofences using the location API’s builder class for creating Geofence objects, and the convenience class for adding them.

Specify geofences and initial triggers

The following snippet uses the GeofencingRequest class and its nested GeofencingRequestBuilder class to specify the geofences to monitor and to set how related geofence events are triggered

Geofence triggers

  1. GEOFENCE_TRANSITION_ENTER: Triggers when a device enters a geofence
  2. GEOFENCE_TRANSITION_EXIT: Triggers when a device exits a geofence.
  3. INITIAL_TRIGGER_ENTER: Tells Location services that should be triggered if the device is already inside the geofence.
  4. INITIAL_TRIGGER_DWELL: Triggers events only when the user stops for a defined duration within a geofence. This approach can help reduce “alert spam” resulting from large numbers notifications.

6.Handle Geofence Transitions

When Location Services detects that the user has entered or exited a geofence, it sends out the Intent contained in the PendingIntent you included in the request to add geofences. This Intent is received by a Service which obtains the geofencing event from the intent, determines the type of Geofence transition(s), and determines which of the defined geofences was triggered. It then sends a notification as the output.

IntentService to listen for geofence transitions, add an element specifying the service name. This element must be a child of the <application> element:

The following snippet shows how to define an IntentService that log when a geofence transition occurs. You can define notification. When the user clicks the notification, the app’s main activity appears

Define an Intent for geofence transitions

The Intent sent from Location Services can trigger various actions in your app.IntentService is a good way to handle the intent. An IntentService can post a notification, do long-running background work, send intents to other services, or send a broadcast intent. The following snippet shows how to define a PendingIntent that starts an IntentService:

Add geofences

To add geofences, use the GeofencingApi.addGeofences() method. Provide the Google API client, the GeofencingRequest object, and the PendingIntent. The following snippet, which processes the results in onResult(),  implements ResultCallback:

7.Stop Geofence Monitoring

The following snippet removes geofences by PendingIntent, stopping all further notification when the device enters or exits previously added geofences:

When geofences required  Re-register?

Registered geofences are kept in the process owned by the package.

  • The device is rebooted.
  • The app is uninstalled and re-installed.
  • The app’s data is cleared.
  • Google Play services data is cleared.
  • The app has received a GEOFENCE_NOT_AVAILABLE alert. This typically happens after NLP (Android’s Network Location Provider) is disabled.



Download this project from GitHub.