Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Android Broadcast Receivers


May 21, 2021 Android


Table of contents


Android Broadcast Receivers

Broadcast receivers are used to respond to broadcast messages from other applications or systems. T hese messages are sometimes referred to as events or intents. F or example, an application can initialize a broadcast to let other applications guide that some data has been downloaded to the device and can be used for them. This allows the broadcast receiver to define appropriate actions to intercept these communications.

There are two important steps to make the broadcast intent of the system work with the broadcast receiver.

  • Create a broadcast receiver
  • Register the broadcast receiver

There is also an additional step to implement custom intents that you must create and broadcast.


Create a broadcast receiver

The broadcast receiver needs to implement a sub-class for the BroadcastReceiver class and override the onReceive() method to receive messages with the Input object as the 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 app listens to the .xml by registering a broadcast receiver in the Android Manifest program. L et's say we're going to register MyReceiver to listen for ACTION_BOOT_COMPLETED system. This event is issued when the startup process for the Android system is complete.

Android 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 an Android device is started, it will be intercepted by broadcast receiver MyReceiver, and the logic implemented in onReceive() will be executed.

There are many system-generated events defined as static constant values in the classIntent. The following table lists important system events.

The event constant Describe
android.intent.action.BATTERY_CHANGED A long-lasting broadcast that contains the battery's charging status, level, and other information.
android.intent.action.BATTERY_LOW Identify the device's low-power conditions.
android.intent.action.BATTERY_OKAY The identification battery is now ready after it is low in charge.
android.intent.action.BOOT_COMPLETED Broadcast once after the system is started.
android.intent.action.BUG_REPORT Displays activity that reports bugs.
android.intent.action.CALL The person specified to perform the call data.
android.intent.action.CALL_BUTTON The user clicks the "Call" button to open the dialer or other dial-up interface.
android.intent.action.DATE_CHANGED The date changes.
android.intent.action.REBOOT The device restarts.

Broadcast custom intent

If you want custom intents to be generated and sent in your application, you need to create and send them in the active class through SendBroadcast(). If you use the SendSticky Broadcast method, the intent is persistent, which means that the intent you send is maintained after the broadcast is complete.

public void broadcastIntent(View view)
{
   Intent intent = new Intent();
   intent.setAction("cn.uprogrammer.CUSTOM_INTENT");
   sendBroadcast(intent);
}

cn.uprogrammer.CUSTOM_INTENT of the application can be registered as before with the intent of our registration system.

<application
   android:icon="@drawable/ic_launcher"
   android:label="@string/app_name"
   android:theme="@style/AppTheme" >
   <receiver android:name="MyReceiver">

      <intent-filter>
         <action android:name="cn.uprogrammer.CUSTOM_INTENT">
         </action>
      </intent-filter>

   </receiver>
</application>

This example explains how to create a broadcast receiver to block custom intent. O nce you are familiar with custom intent, you can program your application to block the intent generated by the system. Let's follow the steps below to modify the Android app we created in the Hello World Instances section.

Steps Describe
1 Use Android Studio to create the Android app and name it broadcastreceiver, and place it under the cn.uprogrammer.broadcastreceiver package in the Hello World Instance section.
2 Modify the main active file MainActivity .java to add the broadcastIntent() method.
3 Create a new Java file called MyReceiver under the cn.uprogrammer.broadcastreceiver package.java to define the broadcast receiver.
4 Applications can handle the intent of one or more customizations or systems without any restrictions. Every intent you want to block needs to be registered in the Android Manifest .xml tag.
5 Modify the default content activity_main.xml/layout/file to include a button for broadcast intent.
6 There is no need to modify the string file, and Android Studio pays attention to the stringing .xml file.
7 Launch the Android simulator to run the app and verify the results of the changes made by the app.

Below is the contents of the modified main activity file src/cn.uprogrammer.broadcastreceiver/MainActivity .java file. T his file contains each underlying lifecycle approach. We've added the broadcastIntent() method to broadcast custom events.

package cn.uprogrammer.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;
    }

    // 广播自定义意图
    public void broadcastIntent(View view){
        Intent intent = new Intent();
        intent.setAction("cn.programmer.CUSTOM_INTENT");
        sendBroadcast(intent);
    }
}

Here's what src/cn.uprogrammer.broadcastreceiver/MyReceiver .java content:

package cn.uprogrammer.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 Android Manifest .xml file. Here we include our broadcast receivers by adding the hashtag:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="cn.uprogrammer.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 contents of the activity_main.xml/layout/image file, which contains buttons for broadcasting custom 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="广播实例"
        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.uprogrammer.cn"
        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="广播意图"
        android:onClick="broadcastIntent"
        android:layout_below="@+id/imageButton"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

Below is the contents of the res/values/strings .xml file, 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 we just modified. L et me assume that you created the AVD when you installed the environment. O pen the active file in Android Broadcast Receivers your project and click the icon in the toolbar to run the app in Android Studio. A ndroid Studio installs the app on the AVD and launches it. If all goes well, it will appear on the emulator window as follows:

Android Broadcast Receivers

Now click on the Broadcast Intent button to broadcast our custom intent. T his will broadcast our custom intent "cn.programmer.CUSTOM_INTENT" and intercept and execute the logic we implement in myReceiver, our registered broadcast receiver. T oast appears at the bottom of the simulator. As follows:

Android Broadcast Receivers

You can try to implement other broadcast receivers to intercept the system's generated intent, such as system startup, date changes, and low power.