Broadcast Receiver
Broadcast in itself means transmitting some content/message or say events. When taken in android terms, notifications or system events are fired on android operating system via broadcast senders and in order to receive these broadcast receivers comes into the picture i.e broadcast receiver is a component that responds to the system wide broadcast announcements. Broadcast receivers are android components used to listen to the events/notifications occurring on android operating system.Why do we need a broadcast receiver?
We usually encounter lot of events occurring on an Android operating system such as battery low, incoming calls, incoming sms, WiFi availability, charger connected, charger disconnected Bluetooth device connected. Probably you would land in such scenario where you have to respond to such occurring events for e.g say you want to stop polling of messages in the background when the battery is low to stop your battery getting drained further due to heavy running task in the background. For such scenarios you basically need a mechanism which could listen to these events occurring in your system, for this you would need a listener which can listen to the events only when the listener is registered to listen. In other words the events here are the intents, listener is the broadcast receiver that can listen to the events and in order to listen it is to be registered either in manifest file or through code. These intents include some action, category and sometimes data in it. These intents are triggered on android system at timely manner, in order to listen to these and match a particular intent at your application end you would need intent filter. Hence Broadcast receiver is also called as intent receiver as it receives intents triggered on android system.
Here are some uses of broadcast :
- If you want to trigger some action if your phone switches off and wakes up back, you can know when the phone got restarted by event REBOOT_COMPLETED.
- It can be used for pending intent for e.g say while using alarm manager at night you need to book a ticket then broadcast can be used.
- To know when the wifi got connected/disconnected and start or stop the service running background that requires internet.
- To know whether the airplane mode is on or off.
- To send the received FCM notification.
- Many more events such as battery low, locale of your phone changed, incoming call, incoming sms etc...
Implementation of Broadcast receiver :
In Android Studio at left most top corner you can find File, click on it and the first option that appears under it in dropdown is New, place your cursor on it and you find number of
options appearing beside new from which you have to place your cursor on the other option present at the bottom and you can find Broadcast Receiver, click on it. Now a popup appears
with the class name as MyReceiver with exported and enabled option selected, click on finish appearing at the bottom of the popup and your component gets created.
File ---> New ----> Other ---> Broadcast Receiver
Lets see what is exported and enabled option available in the popup :
Exported : Denotes whether the broadcast receiver can or not receive the messages from the sources outside the application.
Enabled : Denotes whether the broadcast receiver can or not be instantiated by the system.
Once the component is created you can see as follows :
- a class MyReceiver a subclass of BroadcastReceiver .
- a method onReceive() which is abstract with the parameters context and the intent, intent here is the events triggered from android system. Operating system provides this intent and hence BroadcastReceiver is also called as intent receiver as it receives intent as shown below.
public class MyReceiver extends BroadcastReceiver {
public MyReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
// This method is called when this BroadcastReceiver receives an intent/event fired from operating system.
Toast.makeText(context, "Action: " + intent.getAction(), Toast.LENGTH_SHORT).show();
}
}
Registering Broadcast Receiver :
Inorder to listen to the events, broadcast receiver is to be registered and it can be done in two ways :
- Statically via manifest file
- Dynamically via Code
Dynamically via Code Example :
public class MainActivity extends AppCompatActivity{private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//do something based on the intent's action
Log.i("BroadcastReceiver : ","Airplane mode changed");
if(intent.getBooleanExtra("Airlane State", false)){
//enabled
}else {
//disabled
}
}
};
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// your oncreate code should be
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
filter.addAction("SOME_OTHER_ACTION");
//pass the object of broadcast receiver in this method
// first parameter is the broadcast receiver
//second would be the intent filter that includes the action added that you need
registerReceiver(receiver, filter);
}
This is local broadcast receiver and runs only when your application is running, what if i want it to work throughout the app life i.e from the period of install till its uninstalled, lets see how it is to be done statically as shown below.
Statically via manifest file :
Go to manifest file and add this
<receiver android:name="MyReceiver">
<intent-filter>
<action android:name="android.intent.action.AIRPLANE_MODE">
</action>
</intent-filter>
</receiver>
Thus registering broadcast receiver via manifest runs it throughout no matter whether the app is running or not and adding dynamically via code runs only when the app is running.
Custom broadcast :
You can send your own broadcast from your app, lets get into how do we do this :
Enter the following in your module-level build.gradle file:
android {
...
defaultConfig {
...
jackOptions {
enabled true
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
This will enable java 8 features and jack in your project.
Take a button and in onClick of it write the following code :
sendBroadcast(new Intent("com.myapp.action.APP_RECEIVER));
In manifest file add the following :
<receiver android:name="MyReceiver">
<intent-filter>
<action android:name="com.myapp.action.APP_RECEIVER">
</action
</intent-filter>
</receiver>
Thus Broadcast Receiver plays a major role when it comes to listening the events, automatic starting a service on any particular event whether it is to be throughout app life or only when the app is running.
Please do share your thoughts and any queries on this post in the comments below and please do like my post by giving +1 and by sharing it.
1 Comments
Glad that it was helpful. Thanks for liking it :)
ReplyDelete