Android and Bluetooth (3)

by luca
0 comment

Here’s a new post in my course about developing Android apps with Bluetooth functionalities. In this tutorial I’m going to show you how to detect a state change of the Bluetooth module.

Android is a multitasking operating system: while our application is running, the user or a different application may change the state of the Bluetooth module, for example it can be disabled.

In my first post, you’ve already learned how to ask Android to activate the Bluetooth functionality; in a similar way you can also ask again Android to notify to our app any changes.

First, create a BroadcastReceiver that will receive the notifications from the O.S.

mReceiver = new BroadcastReceiver() {

in the receiver’s onReceive() method, verify if the incoming message is about a state change of the Bluetooth module:

public void onReceive(Context context, Intent intent) {
  String action = intent.getAction();
  if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {

if so, you can obtain the actual state from the Intent‘s extra parameters. The state is an int value, therefore you must use the getIntExtra method, specifying the parameter’s name and a default value, the method will return if no parameter with the given name is found:

int actualState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 

remember to register the Receiver as in the previous examples:

IntentFilter stateChangedfilter = 
 new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mReceiver, stateChangedfilter);

Four different states are defined for the Bluetooth module:

  • BluetoothAdapter.STATE_ON
  • BluetoothAdapter.STATE_OFF
  • BluetoothAdapter.STATE_TURNING_ON
  • BluetoothAdapter.STATE_TURNING_OFF

I wrote an app as example for this tutorial: the app displays – using text and icons – the actual state and it automatically updates if the state changes:

As usual the source code is available on Github!

Related Posts

Leave a Comment

16 − 13 =