Android Broadcast Overview

Android application use broadcast to communicate with each other. Broadcasts can be sent by either android system or other applications. Each android application can register it’s interested broadcast, then it will only receive the interested broadcasts that has been registered.

1. Android Broadcast Principle.

android broadcast principle

The broadcast in Android uses the observer pattern, based on the message’s publish / subscribe event model.

This greatly decouples the sender and receiver of the broadcast, making the system easy to integrate and expand.

1.1 Android Broadcast Process Steps.

  1. Broadcast receiver register interested broadcast event to activity manager service.
  2. Broadcast sender send broadcast message to activity manager service.
  3. Activity manager service search matched broadcast receiver by registered intent-filter and permission.
  4. If find then send the broadcast to the receiver’s activity message loop queue.
  5. When message loop executes and find this broadcast, then it will execute the BroadcastReceiver’s onReceive() method.

From above process steps we can get below conclusions.

  1. The broadcast sender and the broadcast receiver belong to the message publication and subscription end of the observer pattern.
  2. Activity manager service is the center of the process, it’s task is to receive broadcast message and dispatch the message to registered receiver.
  3. The send and receive broadcast action is asynchronous. Broadcast sender do not care about whether the broadcast message can be received or not as well as when the broadcast message can be received.

2. Android Broadcast Receiver.

2.1 How To Create Android Broadcast Receiver.

To create and use a broadcast receiver, you should follow below steps.

  1. Create a class extends android.content.BroadcastReceiver.
  2. Override it’s onReceive(Context context, Intent intent) method.
  3. When activity manager service receive matched broadcast message, it will execute the BroadcastReceiver’s onReceive() method.
  4. Do not write time consumed code in this method.
  5. We will commonly interact with other components in this method, such as send notification, startup another service etc.

2.2 BroadcastReceiver Register Type.

2.2.1 Static Registered Broadcast Receiver.

Register broadcast receiver in AndroidManifest.xml file.

<application...
   <receiver android:name="string"
          android:label="string resource"
          android:enabled=["true" | "false"] 
          android:icon="drawable resource"
          android:exported=["true" | "false"]  
          android:permission="string" 
          android:process="string" > . . . 
   </receiver>
</application>

android:name – broadcast receiver class name, do not forget add package  name.

android:exported – whether this broadcast receiver can receive other App sent broadcast message or not. Value is true means can receive, false means can not receive. The default value is true.

READ :   Android Create User Input Popup Dialog By Custom AlertDialog Example

android:permission – If set, can only receive broadcast which require receiver has this permission.

android:process – broadcast receiver execute process. Default is app execute process.

2.2.1.1 Static Registered Broadcast Receiver Example.

Below broadcast receiver will process low storage and low battery system events.

When the receiver belongs app startup, it will register this receiver to android OS and waiting for the event to occur.

<application...
  <receiver android:name="com.example.CustomBroadcastReceiver" > 
    <intent-filter> 
         <action android:name="android.intent.action.DEVICE_STORAGE_LOW" /> 
    </intent-filter> 
    <intent-filter> 
         <action android:name="android.intent.action.BATTERY_LOW" /> 
    </intent-filter> 
  </receiver>
</application>
2.2.2 Dynamic Registered Broadcast Receiver.

You can also register broadcast receiver in java code when your android app execute.

IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");

networkChangeReceiver = new NetworkChangeReceiver();
registerReceiver(networkChangeReceiver, intentFilter);

But you also need to unregister it when the app destroy.

@Override
protected void onDestroy() {
    super.onDestroy();

    if(this.networkChangeReceiver!=null) {
        unregisterReceiver(this.networkChangeReceiver);
    }
}

3. Android Broadcast Classification.

3.1 System Broadcast.
android system broadcast

There are multiple system broadcasts built into the Android system, and all the basic phone operations will be broadcast by the system. Such as : OS start up, network status change, take photos, screen close and open, light up and down etc.

Each system broadcast has a specific intent-filter, which includes specific system pre-defined actions. For example.

  1. android.intent.action.BATTERY_LOW
  2. android.intent.action.BATTERY_CHANGED
  3. android.net.conn.CONNECTIVITY_CHANGE
  4. android.intent.action.BOOT_COMPLETED
  5. android.intent.action.DATA_SMS_RECEIVED

You can find all the system broadcast action list in broadcast_actions.txt file which is save in your android sdk folder like \ Android \ sdk \ platforms \ android-26 \ data \. 

Download “broadcast_actions.zip” broadcast_actions.zip – Downloaded 132 times – 2 KB

3.2 Normal Broadcast.
android normal broadcast

A fully asynchronous broadcast. All broadcast receivers receive the broadcast message almost at the same time after the broadcast is sent, so there’s no receive order priority between receivers.

Developers will define their own intent and action, then use sendBroadcast(Intent intent) method to send it.

The receiver should have enough permission to receive the broadcast as the sender require. This kind of broadcast is efficient but cannot be intercepted.

3.3 Ordered Broadcast.

android ordered broadcast

Simultaneous broadcast, after the broadcast is sent, the receivers will receive the broadcast message one by one in order by it’s priority, and the broadcast will continue to be transmitted when the logic of the previous broadcast receiver is completed.

Therefore, the broadcast receiver is in order, and the high priority receiver can receive the broadcast message first, it can even intercept the broadcast, this will make the low priority broadcast receiver not receive the broadcast message any more.

READ :   Android Actionbar Example

To send an ordered broadcast, you need to first create an intent with custom action value, then use sendOrderedBroadcast(intent, receiverPermission, …) method to send it.

The receive order is decided by all the registered broadcast receiver(dynamic registered or static registered )’s priority value. The bigger the value, the higher the priority.

For dynamic registered and static registered broadcast receiver with the same priority value, dynamic registered receiver will receive the broadcast message first.

3.3.1 Set Broadcast Receiver Priority Example.

In java source code.

IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
intentFilter.setPriority(100);

In AndroidManifest.xml file.

<application ...
   <receiver ...
       <intent-filter android:priority="99">
          <action .../>
       </intent-filter>
   </receiver>
</application>

3.4 Local Broadcast.

In-app broadcast (Broadcast only send and receive inside App application process).

The broadcast in Android can be cross-processes and even cross-app. There may be security concerns as following.

  1. Other App will send broadcast messages which current App registered, this will make current App receive and process the broadcast repeatedly.
  2. Other App can register same broadcast intent-filter as current App to steal broadcast message.

To resolve above broadcast security issue, we can use following methods.

  1. For sending and receiving broadcast within the same App, the exported attribute should be set to false, so that current App will not receive income broadcast messages sent from other App.
  2. When send or receive broadcast message, add corresponding permission for permission verification.
  3. Use Intent.setPackage(packageName) to specify the broadcast receiver class package name when send broadcast. So that the broadcast will only be sent to the matched broadcast receiver in current App.

In-App broadcast can be understood as a form of local broadcast, where both the sender and the receiver belong to the same App.

Instead of using a global broadcast,  local broadcast is more efficient and more secure.

Android v4 compatible package provide a LocalBroadcastManager class for you to process In-App broadcasts. The usage is similar with normal broadcasts.

// Create a broadcast receiver instance.
BroadcastReceiver broadcastReceiver = new BroadcastReceiver();

// Get LocalBroadcastManager instance.
LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
// Register In-App broadcast receiver.
localBroadcastManager.registerReceiver(broadcastReceiver, intentFilter);

// Unregister In-App broadcast receiver.
localBroadcastManager.unregisterReceiver(broadcastReceiver);

// Create intent.
Intent intent = new Intent();

// Set intent action.
intent.setAction(BROADCAST_ACTION);

// Send In-App broadcast.
localBroadcastManager.sendBroadcast(intent);

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.