• Home
  • pcDuino
  • WiKi
  • Store
  • Distributors
  • Home
  • pcDuino
  • WiKi
  • Store
  • Distributors
HomeProjectAndroid and Bluetooth (3)
Previous Next

Android and Bluetooth (3)

Posted by: Jia Qun , June 13, 2016

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, 
 BluetoothAdapter.STATE_OFF);

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:

and_and_bt_3-236x300

As usual the source code is available on Github!

For more details ,please refer to origianal post

http://www.lucadentella.it/en/2014/04/28/android-e-bluetooth-3/

Share!
Tweet

Jia Qun

About the author

Leave a Reply Cancel reply

You must be logged in to post a comment.

Category

  • Home
  • pcDuino
  • WiKi
  • Store
  • Distributors