Detailed explanation of the broadcast mechanism in Android

Detailed explanation of the broadcast mechanism in Android

[[436469]]

Preface

Each application in Android can register for the broadcasts it is interested in, so that the program will only receive the broadcast content it is interested in, which may come from the system or from other applications;

Android provides a complete set of APIs that allow applications to freely send and receive broadcasts.

Today we will introduce in detail

1. Broadcast Introduction

1. Standard broadcast

  • This is a completely asynchronous broadcast. After the broadcast is sent, all broadcast receivers will receive the broadcast message almost at the same time, so there is no order between them. The receiver cannot do anything with the received broadcast, nor can it intercept the broadcast and continue to propagate;
  • This type of broadcast is sent using sendBroadcast;

2. Orderly broadcast

  • This is a synchronous broadcast. After the broadcast is sent, only one broadcast receiver can receive the broadcast message at the same time. When the logic in the broadcast receiver is executed, the broadcast will continue to be transmitted.
  • Therefore, the broadcast receivers at this time are in order. The broadcast receiver with a high priority can receive the broadcast message first, and the previous broadcast receiver can also intercept the broadcast being transmitted, so that the subsequent broadcast receiver cannot receive the broadcast message;
  • This type of broadcast is sent using sendOrderedBroadcast;

3. Sticky Broadcast

  • The characteristic of sticky broadcast is that the Intent will be retained until the broadcast event ends, and this kind of broadcast does not have the so-called 10-second limit. The 10-second limit means that if the onReceive method of a normal broadcast takes too long to execute, the system will set the broadcast as a "candidate" that can be killed when it exceeds 10 seconds. Once the system resources are insufficient, the broadcast will be killed and not executed. This broadcast is sent using sendStickyBroadcast;
  • It is no longer available in Android 5.0 & API 21, so it is not recommended to use;

2. Broadcasting Details

Android has many built-in system-level broadcasts. We can listen to these broadcasts in the application to get various system status information. For example, a broadcast will be sent when the phone is turned on, a broadcast will be sent when the battery level changes, and a broadcast will be sent when the time or time zone changes, etc.

There are generally two ways to register broadcasts:

Dynamic registration is registered in the code;

Static registration is registered in AndroidManifest.xml

1. Static registration

Generally, it is a permanent broadcast, which is set in AndroidManifest.xml through Label declaration

  1. <receiver android: name = ".MyBroadcastReceiver" android:exported= "true" >
  2. <intent-filter>
  3. < action android: name = "android.intent.action.BOOT_COMPLETED" />
  4. < action android: name = "android.intent.action.INPUT_METHOD_CHANGED" />
  5. </intent-filter>
  6. </receiver>

The intent filter specifies the action to which the receiver subscribes;

2. Dynamic Registration

Non-resident broadcasts are registered when used and destroyed immediately after use;

  1. BroadcastReceiver br = new MyBroadcastReceiver();
  2. IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
  3. filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
  4. this.registerReceiver(br, filter);

Remember to log out in time to avoid memory leaks;

  1. @Override
  2. protected void onDestroy() {
  3. super.onDestroy();
  4. unregisterReceiver(receiver);
  5. }

3. Custom broadcast

Register Broadcast

  1. <receiver
  2. android: name = ".test.MyBroadcastReceiver"  
  3. android:enabled= "true"  
  4. android:exported= "true" >
  5. <intent-filter>
  6. < action android: name = "com.test.test" />
  7. </intent-filter>
  8. </receiver>
  9. public class MyBroadcastReceiver extends BroadcastReceiver {
  10. @Override
  11. public void onReceive(Context context, Intent intent) {
  12. Toast.makeText(context, "Send standard broadcast" , Toast.LENGTH_LONG).show();
  13. }
  14. }
  15. Intent intent = new Intent( "com.test.test" );
  16. sendBroadcast(intent);
  17. //Send ordered broadcast
  18. Intent intent = new Intent( "com.test.test" );
  19. sendOrderedBroadcast(intent, null );

4. Local broadcast

All broadcasts we send and receive belong to the system global broadcast, that is, the broadcasts sent can be received by any other application, and we can also receive broadcasts from any other application;

In order to solve the broadcast security problem, Android introduced a local broadcast mechanism. The broadcasts sent using this mechanism can only be transmitted within the application, and the broadcast receiver can only receive broadcasts from this application, so all security issues do not exist;

Initialize broadcast:

  1. private LocalBroadcastManager localBroadcastManager;
  2. private void init() {
  3. //Get the instance
  4. localBroadcastManager = LocalBroadcastManager.getInstance(this);
  5. IntentFilter intentFilter = new IntentFilter();
  6. intentFilter.addAction( "om.test.LOCAL_BROADCAST" );
  7. LocalReceiver localReceiver = new LocalReceiver();
  8. localBroadcastManager.registerReceiver(localReceiver, intentFilter);
  9. }
  10. Intent intent = new Intent( "om.test.LOCAL_BROADCAST" );
  11. localBroadcastManager.sendBroadcast(intent);
  12. definition
  13. private class LocalReceiver extends BroadcastReceiver {
  14. @Override
  15. public void onReceive(Context context, Intent intent) {
  16. Toast.makeText(context, "Local broadcast....." , Toast.LENGTH_LONG).show();
  17. }
  18. }

advantage:

  • We know for sure that the broadcast we are sending will not leave our program, so we don't have to worry about leaking confidential data:
  • Other programs cannot send broadcasts to our program, so there is no need to worry about security vulnerabilities:
  • Sending a local broadcast is more efficient than sending a system-wide broadcast:

5. Standard broadcast with permissions

Send a broadcast

When calling sendBroadcast(Intent, String) or sendOrderedBroadcast(Intent, String, BroadcastReceiver, Handler, int, String, Bundle), you can specify the permission parameter;

  1. sendBroadcast(new Intent( "com.test" ),
  2. Manifest.permission.SEND_SMS);

To receive this broadcast, the receiving app must apply for this permission

  1. <uses-permission android: name = "android.permission.SEND_SMS" />

Receiving Broadcasts

If you specify a permission parameter when registering a broadcast receiver (using registerReceiver(BroadcastReceiver, IntentFilter, String, Handler) or in the manifest file ), only use it in the manifest file Only the broadcast sender who requests permission can send the Intent to the receiver;

Declare in the manifest file:

  1. <receiver android: name = ".MyBroadcastReceiver"  
  2. android:permission= "android.permission.SEND_SMS" >
  3. <intent-filter>
  4. < action android: name = "com.test" />
  5. </intent-filter>
  6. </receiver>

When registering, declare:

  1. IntentFilter filter = new IntentFilter("com.test);
  2. registerReceiver(receiver, filter, Manifest.permission.SEND_SMS, null );

To send a message to it, the app that broadcasts the message must apply for the corresponding permissions:

  1. <uses-permission android: name = "android.permission.SEND_SMS" />

Summarize

Dynamically registered broadcasts are not permanent broadcasts, which means that the broadcast follows the life cycle of the Activity. Note that before the Activity ends, remove the broadcast receiver;

Static registration is permanent, which means that when the application is closed, if there is a message broadcast, the program will be called by the system to run automatically;

When the broadcast is an ordered broadcast: the one with the highest priority is received first (regardless of static or dynamic). For broadcast receivers with the same priority, dynamic takes precedence over static;

For the same type of broadcast receivers with the same priority, static: the first scan takes precedence over the later scan; dynamic: the first registration takes precedence over the later registration;

When the broadcast is the default broadcast: regardless of the priority, dynamic broadcast receivers take precedence over static broadcast receivers. For the same type of broadcast receivers with the same priority, static ones scanned first take precedence over those scanned later, and dynamic ones registered first take precedence over those registered later;

This article is reproduced from the WeChat public account "Android Development Programming"

<<:  WeChat Pay Family Card function upgrade: Added "Other relatives" option with a maximum limit of 3,000

>>:  Profit as soon as you buy it: iPhone 13 depreciates 50% lower than iPhone 12

Recommend

How to attract new customers through live quiz contest?

Live quiz show was first started by HQTrivia in t...

Price list for renting overseas server bandwidth configuration

The price list for renting overseas server bandwi...

How to write copy that matches your brand positioning?

A few days ago, we held a small activity on the f...

Can you send iMessages on your Android phone? How does weMessage work?

iPhone to Android: But what about iMessage? Nowad...

How to effectively improve the conversion effect of information flow?

The cost remained at 180 a few days ago, why did ...

The Internet in 2016: Where has all the traffic gone?

The trouble with public accounts: disappearing re...

From 0 to 3,000 followers, 6 points you must get

At the beginning, my public account only had doze...