Friday, July 22, 2016

BroadcastReceiver in Android

BroadcastReceiver in Android are the component which you can use to get broadcast messages from other Android Application or even Android System and perform some action.
Example:
We can register an event for broadcast message "battery is low" or "screen is turned off" etc.
BroadcastReceiver in Android

Lifecycle of BroadcastReceiver in Android

Just like Activity & Services in Android, BroadcastReceiver have onReceive() method which is called when broadcast message is received.

2 Steps to use BroadcastReceiver

STEP 1: Create a custom BroadcastReceiver

First you have to create your custom BroadcastReceiver and to do that just create a new Java file in Android Studio and implement your custom BroadcastReceiver as subclass of BroadcastReceiver class.
We have already discussed in Android Application Components that BroadcastReceiver in Android is implemented as a subclass of BroadcastReceiver class.
This is how you can create your custom BroadcastReceiver


STEP 2: Register a BroadcastReceiver

Once you have created a custom BroadcastReceiver (let say myCustomReceiver), you have to register it in Android Manifest file as shown below.


Some of system generated events
  1. android.intent.action.BOOT_COMPLETED :  Triggered when Boot is completed.
  2. android.intent.action.REBOOT : Triggered when device reboot
  3. android.intent.action.BATTERY_LOW : Triggered when battery is low
  4. android.intent.action.POWER_CONNECTED : Triggered when power is connected to device
  5. android.intent.action.POWER_DISCONNECTED : Triggered when power is disconnected from device.
In above code we have registered BroadcastReceiver for intent android.intent.action.BATTERY_LOW which is system generated.
But if you want to Register BroadcastReceiver for custom intent,
First you have to broadcast your custom intent ( You can broadcast your custom intent inside your activity class using sendBroadcast() method ) as shown below.

Now you have to registered your custom BroadcastReceiver with custom intent in Android Manifest file, this is similar as we register our android.intent.action.BATTERY_LOW.

You can contact me through contact form for any query or through twitter @iVishalMalik