Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect Bluetooth state change using a broadcast receiver?

I am trying to make an app that shows a toast when the device's Bluetooth turned on. I wanna do that even when my app is not running. So I should use a broadcast receiver, add some permissions, an intent-filter to android manifest and make a java class but I don't know the details.

What should I do? Which permissions should I use?

like image 249
Mohammad H Avatar asked Jul 22 '14 12:07

Mohammad H


People also ask

How a notification manager and broadcast receiver works under Android?

Broadcast in android is the system-wide events that can occur when the device starts, when a message is received on the device or when incoming calls are received, or when a device goes to airplane mode, etc. Broadcast Receivers are used to respond to these system-wide events.

How do I know if my broadcast receiver is registered Android?

A simple solution to this problem is to call the registerReceiver() in your Custom Application Class. This will ensure that your Broadcast receiver will be called only one in your entire Application lifecycle.

What are the different ways and scenarios through which a broadcast receiver can be registered?

6.1. Receiver can be registered via the Android manifest file. You can also register and unregister a receiver at runtime via the Context. registerReceiver() and Context. unregisterReceiver() methods.


1 Answers

AS far as permissions go, to detect the state change of bluetooth you need to add this to your AndroidManifest.xml.

<uses-permission android:name="android.permission.BLUETOOTH" /> 

An example receiver would look like this, you add this code to where you want to handle the broadcast, for example an activity:

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {             public void onReceive (Context context, Intent intent) {                 String action = intent.getAction();                  if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {                     if(intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1)      == BluetoothAdapter.STATE_OFF)     // Bluetooth is disconnected, do handling here }  }          }; 

To use the receiver, you need to register it. Which you can do as follows. I register the receiver in my main activity.

registerReceiver(this, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED)); 

You could also decide to add all of it to your AndroidManifest.xml. This way you can make a special class for the receiver and handle it there. No need to register the receiver, just make the class and add the below code to the AndroidManifest

<receiver         android:name=".packagename.NameOfBroadcastReceiverClass"         android:enabled="true">     <intent-filter>         <action android:name="android.bluetooth.adapter.action.STATE_CHANGED"/>     </intent-filter> </receiver> 
like image 121
paNji Avatar answered Sep 29 '22 02:09

paNji