Runoob Tutorial ArchiveEnglish

Android Broadcast Receivers

Android Broadcast Receivers

Broadcast receivers are used to respond to broadcast messages from other applications or the system. These messages are sometimes called events or intents. For example, an application can initialize a broadcast to let other applications know that some data has been downloaded to the device and is available for them to use. The broadcast receiver can then define appropriate actions to intercept this communication.

There are two important steps to make the system's broadcast intents work with broadcast receivers.

There is an additional step; to implement custom intents, you must create and broadcast these intents.


Create a broadcast receiver

The broadcast receiver needs to be implemented as a subclass of the BroadcastReceiver class and override the onReceive() method to receive messages with an Intent object as a parameter.

public class MyReceiver extends BroadcastReceiver {

   @Override

   public void onReceive(Context context, Intent intent) {

      Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();

   }

}


Register the broadcast receiver

The application listens for a defined broadcast intent by registering the broadcast receiver in AndroidManifest.xml. Assume we are registering MyReceiver to listen for the system-generated ACTION_BOOT_COMPLETED event. This event is emitted when the Android system's boot process is complete.

Broadcast Receivers

<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>

Now, whenever the Android device is started, it will be intercepted by the broadcast receiver MyReceiver, and the logic implemented in onReceive() will be executed.

Many system-generated events are defined as static constant values in the Intent class. The table below lists important system events.

Event Constant Description
android.intent.action.BATTERY_CHANGED Persistent broadcast containing battery charge status, level, and other information.
android.intent.action.BATTERY_LOW Identifies the low battery condition of the device.
android.intent.action.BATTERY_OKAY Identifies that the battery is now okay after being low.
android.intent.action.BOOT_COMPLETED Broadcasts once after the system has finished booting.
android.intent.action.BUG_REPORT Display the report bug activity.
android.intent.action.CALL Execute a call to the specified person.
android.intent.action.CALL_BUTTON The user clicks the "Call" button to open the dialer or another appropriate dialing interface.
android.intent.action.DATE_CHANGED The date has changed.
android.intent.action.REBOOT Restart the device.

Broadcast custom intents

If you want to generate and send custom intents in your application, you need to create and send these intents in the activity class using sendBroadcast(). If you use the sendStickyBroadcast(Intent) method, the intent is sticky, meaning the intent you send remains even after the broadcast is finished.

public void broadcastIntent(View view)

{

   Intent intent = new Intent();

   intent.setAction("com.runoob.CUSTOM_INTENT");

   sendBroadcast(intent);

}

Intents with com.runoob.CUSTOM_INTENT can be registered just like the system-generated intents we registered before.

<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.runoob.CUSTOM_INTENT">

         </action>

      </intent-filter>



   </receiver>

</application>


Instance

This instance will explain how to create a broadcast receiver to intercept custom intents. Once you are familiar with custom intents, you can program your application to intercept system-generated intents. Let's modify the Android application we created in the Hello World instance chapter by following the steps below.

Steps Description
1 Use Android Studio to create an Android application named broadcastreceiver, and place it under the com.runoob.broadcastreceiver package in the Hello World instance chapter.
2 Modify the main activity file MainActivity.java to add the broadcastIntent() method.
3 Create a new Java file named MyReceiver.java in the com.runoob.broadcastreceiver package to define the broadcast receiver.
4 The application can handle one or more custom or system intents without any restrictions. Every intent you want to intercept must be registered in AndroidManifest.xml using the <receiver.../> tag.
5 Modify the default content in res/layout/activity_main.xml to include a button for a broadcast intent.
6 No need to modify the string file; Android Studio will notice string.xml.
7 Start the Android emulator to run the application and verify the results of the changes made to the application.

Below is the content of the main activity file src/com.runoob.broadcastreceiver/MainActivity.java. This file contains every basic lifecycle method. We added the broadcastIntent() method to broadcast custom events.

Original prompt (Chinese, left untranslated)

package com.runoob.broadcastreceiver;



import android.os.Bundle;

import android.app.Activity;

import android.view.Menu;

import android.content.Intent;

import android.view.View;



public class MainActivity extends Activity {



    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

    }



    @Override

    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.menu_main, menu);

        return true;

    }



    // Broadcast custom intent

    public void broadcastIntent(View view){

        Intent intent = new Intent();

        intent.setAction("cn.programmer.CUSTOM_INTENT");

        sendBroadcast(intent);

    }

}

Below is the content of src/com.runoob.broadcastreceiver/MyReceiver.java:

Original prompt (Chinese, left untranslated)

package com.runoob.broadcastreceiver;



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, "检测到意图。", Toast.LENGTH_LONG).show();

    }

}

Next, modify the AndroidManifest.xml file. Here, we include our broadcast receiver by adding the <receiver.../> tag:

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.runoob.broadcastreceiver"

    android:versionCode="1"

    android:versionName="1.0" >



    <uses-sdk

        android:minSdkVersion="8"

        android:targetSdkVersion="22" />



    <application

        android:icon="@drawable/ic_launcher"

        android:label="@string/app_name"

        android:theme="@style/AppTheme" >



        <activity

            android:name=".MainActivity"

            android:label="@string/title_activity_main" >



            <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="cn.programmer.CUSTOM_INTENT">

                </action>

            </intent-filter>



        </receiver>



    </application>



</manifest>

Below is the content of res/layout/activity_main.xml, which includes a button for the broadcast custom intent.

Original prompt (Chinese, left untranslated)

<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="Broadcast instance"

        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="www.runoob.com"

        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/ic_launcher"

        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>

Below is the content of res/values/strings.xml, which defines two new constants.

<?xml version="1.0" encoding="utf-8"?>

<resources>



    <string name="app_name">Android Broadcast Receiver</string>

    <string name="action_settings">Settings</string>

    <string name="menu_settings">Settings</string>

    <string name="title_activity_main">Main Activity</string>



</resources>

Let's run the Hello World! application that was just modified. I assume you have created an AVD during the installation environment setup. Open the activity file in your project and click the icon in the toolbarImageto run the application in Android Studio. Android Studio installs and launches the application on the AVD. If everything goes well, it will display as follows on the emulator window:

Image

Now click the "Broadcast Intent" button to broadcast our custom intent. This will broadcast our custom intent "cn.programmer.CUSTOM_INTENT", which will be intercepted by our registered broadcast receiver MyReceiver and execute the logic we implemented. A toast will appear at the bottom of the emulator, like this:

Image

You can try implementing other broadcast receivers to intercept system-generated intents, such as system boot, date change, and low battery, etc.