BroadcastReceiver:
In Android, there are some events occur. All these events are managed by Android system. If our application wants to perform some operations when that events occur, we will subscribe to that events. So that, whenever that event occurs, our app will get a notification. We use BroadcastReceiver to receive that notification. Then, we write our logic to perform a specific operation.
Steps to create BroadcastReceiver:
1) Create a subclass of BroadcastReceiver
2) Override onReceive method
3) Register in AndroidManifest.xml with specific Action
Create an Android application to work with BroadcastReceiver
public class DateReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
Toast.makeText(context, “Date is changed”, Toast.LENGTH_LONG).show();
}}
Manifest:
<?xml version=”1.0″ encoding=”utf-8″?><manifest xmlns:android=”http://schemas.android.com/apk/res/android” package=”nareshit.com.broadcastreceiver”>
<application
android:allowBackup=”true”
android:icon=”@mipmap/ic_launcher”
android:label=”@string/app_name”
android:roundIcon=”@mipmap/ic_launcher_round”
android:supportsRtl=”true”
android:theme=”@style/AppTheme”>
<activity android:name=”.MainActivity”>
<intent-filter>
<action android:name=”android.intent.action.MAIN” />
<category android:name=”android.intent.category.LAUNCHER” />
</intent-filter>
</activity>
<receiver android:name=”.DateReceiver”>
<intent-filter>
<action android:name=”android.intent.action.DATE_CHANGED”/>
</intent-filter>
</receiver>
</application>
</manifest>
HomeWork:
Create an Android application to work with receiving mobile restarted event, phone call received event, message received event, time set event
Creating a custom BroadcastReceiver:
1) Create a sub class of BroadcastReceiver
2) Override onReceive method
3) Create a custom Action.
This is nothing but a String constant.
Ex: public static final String action = “nareshit.com.CUSTOM_EVENT”4) Register the reciever with custom action in AndroidManifest.xmlEx: <receiver android:name=”.receiver.CustomActionReceiver”> <intent-filter> <action android:name=”nareshit.com.broadcastreceiver.
CUSTOM_ACTION”/>
</intent-filter></receiver>
5) Send the broadcast.
For sending the broadcast, we will create an Intent object with the custom action and use the sendBroadcast method as follows.
Ex: Intent i = new Intent(“nareshit.com.broadcastreceiver.
CUSTOM_ACTION”); sendBroadcast(i);
Refer source for application:https://tinyurl.com/android7pm