Android Broadcast Receiver

0
468

Broadcast Receivers is that application component which is responsible for responding to the broadcast messages sent either by the system or by other applications. These broadcast messages are also known as events or intents. For an instance, an application broadcasts a message to other applications about the availability of the downloaded data. This broadcast message will be intercepted by the broadcast receiver to initiate a proper action.

Also Read: Android Services

The broadcast receiver works in two steps, which are:
* Creation of The Broadcast Receiver
* Registration of The Broadcast Receiver

Other than these two, there is another step to be added if you are to implement the custom intents. This another step helps the application to create and broadcast the intents on its own.

Creation of The Broadcast Receiver
To create a broadcast receiver, you need to extend BroadcastReceiver base class. In this newly created MyReceiver subclass, you will be overriding the onReceive() method where the Intent object is passed as an argument.

public class MyReceiver extends BroadcastReceiver
{
      @Override
      public void onReceive(Context context, Intent intent)
     {
             Toast.makeText(context, “Intent Detected.”, Toast.LENGTH_LONG).show();
     }
}

Registration of The Broadcast Receiver
The registration of a broadcast receiver begins with mentioning it in the AndroidManifest.xml file. After the successful registration of a broadcast receiver, the Android application is now capable of listening to the particular broadcasts intents with the help of the recently registered broadcast receiver. Take a look at an example where the system has finished the booting process with the help of system generated event which is indicated by android.intent.action.BOOT_COMPLETED intent. In the following code, we will be registering the broadcast receiver for this system generated event.

<application
android:icon=”@drawable/ic_launcher”
android:label=”@string/app_name”
android:theme=”@style/AppTheme” >
  <receiver android:name=”MyReceiver”>
     <intent-filter>
           <action android:name=”android.intent.action.BOOT_COMPLETED”>
           </action>
      </intent-filter>
  </receiver>
</application>

So, according to this above code, the broadcast receiver will intercept every time whenever the system finishes the booting process. After the interception, the logic inside the onReceive() method will be implemented.

Below is a list of the system generated events that have definitions as static fields. These system generated events are defined in the Intent class.

S.No. Event Constant Description
1 android.intent.action.BATTERY_CHANGED * This is a sticky broadcast.
* It is used to indicate the battery state, charging level, and other information associated with it.
2 android.intent.action.BATTERY_LOW * It is used to indicate the low battery of the device.
3 android.intent.action.BATTERY_OKAY * It is used to indicate the improved battery level after being low.
4 android.intent.action.BOOT_COMPLETED * It is used to indicate the completion of the booting process.
* This event constant gets broadcasted once.
5 android.intent.action.BUG_REPORT * It is used to indicate the presence of a bug during an activity.
6 android.intent.action.CALL * It is used to make a specified call based on the stored data.
7 android.intent.action.CALL_BUTTON * It is used to redirect the user to a dialer containing a ‘call’ button that enables the user to place a call.
8 android.intent.action.DATE_CHANGED * It is used to represent the changed date.
9 android.intent.action.REBOOT * It is used to reboot the system.

Broadcast of Custom Intents
In case, you want your application to be decisive enough regarding the custom intents then you need to use sendBroadcast() method. This method will be defined in the activity class. In other words, this method will help your Android application to generate and send custom events on its own. And, if you want the Intent is to be sticky then use the sendStickyBroadcast(Intent) method. sendStickyBroadcast(Intent) method is used whenever you want the Intent to stick around even after the completion of the broadcast.

public void broadcastIntent(View view)
{
         Intent intent = new Intent();
         intent.setAction(“com.w3school.CUSTOM_INTENT”);
         sendBroadcast(intent);
}

You can register com.w3school.CUSTOM_INTENT intent in a similar way as the system generated intent. Well, for that, you need to follow the below provided code.

<application
android:icon=”@drawable/ic_launcher”
android:label=”@string/app_name”
android:theme=”@style/AppTheme” >
   <receiver android:name=”MyReceiver”>
      <intent-filter>
            <action android:name=”com.w3school.CUSTOM_INTENT”>
            </action>
      </intent-filter>
   </receiver>
</application>

Now, take a look at the following example to understand the concept of broadcast receivers more clearly. Here, we will be helping you to create the broadcast receiver that can intercept custom intent. So, before you start with the programming of your Android application which can intercept system generated intents, you must be aware of the custom intent. The following step-to-step guide will enlighten you with the modifications in the already created Hello World example.

Step 1: Create an application on Android Studio under the com.example.w3school.myapplication package. Save this application by the name My Application.

Step 2: Add broadcastIntent() method in the main activity file, MainActivity.java to broadcast a custom intent. This file can have all the basic life cycle callback methods.

package com.example.w3school.myapplication;
import android.app.Activity
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends Activity
{
       /** Called when the activity is first created. */
      @Override
       public void onCreate(Bundle savedInstanceState)
      {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
       }

       // broadcast a custom intent
       public void broadcastIntent(View view)
       {
            Intent intent = new Intent();
            intent.setAction(“com.w3school.CUSTOM_INTENT”);
            sendBroadcast(intent);
       }
}

Step 3: Now, create a new Java file under the com.example.w3school.myapplication package. Save this file as MyReceiver.java. In this file, we will be defining the BroadcastReceiver.

package com.example.w3school.myapplication;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class MyReceiver extends BroadcastReceiver
{
        @Override
        public void onReceive(Context context, Intent intent)
        {
              Toast.makeText(context, “Intent Detected.”, Toast.LENGTH_LONG).show();
        }
}

Step 4: An application is capable of having more than one custom and system generated intents without any specific constraints. But each and every intent that can be intercepted should be registered in the AndroidManifest.xml file. The registration process will require the <receiver…/> tag.

<?xml version=”1.0″ encoding=”utf-8″?>
<manifest xmlns:android=”http://schemas.android.com/apk/res/android”
package=”com.example.w3school.myapplication”>

<application
android:allowBackup=”true”
android:icon=”@mipmap/ic_launcher”
android:label=”@string/app_name”
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=”MyReceiver”> 
             <intent-filter>
                  <action android:name=”com.w3school.CUSTOM_INTENT”>
                  </action>
             </intent-filter>
         </receiver>
</application>
</manifest>

Step 5: There is another file which requires modification. For this, you need to add a button to the res/layout/activity_main.xml file. This button will be to initiate the broadcast intent.

<RelativeLayout
xmlns:android=”http://schemas.android.com/apk/res/android”
xmlns:tools=”http://schemas.android.com/tools”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:paddingLeft=”@dimen/activity_horizontal_margin”
android:paddingRight=”@dimen/activity_horizontal_margin”
android:paddingTop=”@dimen/activity_vertical_margin”
android:paddingBottom=”@dimen/activity_vertical_margin”
tools:context=”.MainActivity”>

<TextView
android:id=”@+id/textView1″
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Example of Broadcast”
android:layout_alignParentTop=”true”
android:layout_centerHorizontal=”true”
android:textSize=”30dp” />

<TextView
android:id=”@+id/textView2″
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Tutorials point “
android:textColor=”#ff87ff09″
android:textSize=”30dp”
android:layout_above=”@+id/imageButton”
android:layout_centerHorizontal=”true”
android:layout_marginBottom=”40dp” />

<ImageButton
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:id=”@+id/imageButton”
android:src=”@drawable/abc”
android:layout_centerVertical=”true”
android:layout_centerHorizontal=”true” />

<Button
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:id=”@+id/button2″
android:text=”Broadcast Intent”
android:onClick=”broadcastIntent”
android:layout_below=”@+id/imageButton”
android:layout_centerHorizontal=”true” />
</RelativeLayout>

Step 6: Leave the string.xml file untouched.

Step 7: At this last step, you just need to run this modified Hello World application on the Emulator window to verify the changes. For this, you need to create the AVD during the environment setup process. We are assuming that you are already done with that process. Well, now, open any of the Android Studio’s project activity files. After this, click on the Run icon to verify the changes on the Emulator window.

If the application gets through successfully then you will be displayed with the Broadcast Intent button. Click on the button to broadcast the custom intent. The com.w3school.CUSTOM_INTENT custom intent will broadcast and it is now ready to be intercepted by the MyReceiver broadcast receiver. The message ‘Intent Detected’ will indicate the successful completion of the broadcast.