Exploring Android Broadcasting: Demystifying the Magic of Android Broadcasting Mechanism

One Broadcast Mechanism

  • The broadcast (Broadcast) mechanism in Android is used for inter-process/thread communication , which uses the observer mode.
  • Observer mode is a software design mode. This mode is a message-based publish/subscribe event model. In this model, the message publisher is the broadcast sender in the broadcast mechanism, and the message subscriber is the broadcast receiver in the broadcast mechanism . The specific implementation process of the broadcast mechanism is shown in the figure below.
    insert image description here
  1. The broadcast receiver registers in AMS (Activity Manager Service) through the Binder mechanism
  2. The broadcast sender sends broadcasts to AMS through the Binder mechanism.
  3. AMS finds the broadcast receiver (BroadcastReceiver) that meets the corresponding conditions (IntentFilter/Permission), and sends the broadcast to the corresponding message loop queue.
  4. When the broadcast is obtained during the execution of the message loop, the onReceive() method in the broadcast receiver (BroadcastReceiver) will be called back and related processing will be performed in this method.
  • There are many broadcasts built into the Android system. For example, a broadcast will be sent when the phone is powered on and the battery is low. In order to monitor broadcast events from the system or applications, the Android system provides the BroadcastReceiver (broadcast receiver) component.
    insert image description here
  • The creation of the broadcast receiver is as follows: Create a class in the application package to inherit BroadcastReceiver and rewrite the onReceive() method to achieve.
public class MyReceiver extends BroadcastReceiver {
    
    
    public MyReceiver() {
    
    
    }
    //在该方法中实现广播接收者的相关操作
    @Override
     public void onReceive (Context context, Intent intent) {
    
    
          throw new UnsupportedOperationException("Not yet implemented");
     }
}

1.1 Dynamic Registration

  • After creating the broadcast receiver, you need to register the broadcast receiver before you can receive the broadcast [usually registered in MainActivity]
  • Dynamic registration broadcast, whether the dynamically registered broadcast receiver is canceled or not depends on the component that registered the broadcast. When the component is destroyed, the broadcast receiver is also canceled.
protected void onCreate(Bundle savedInstanceState) {
    
    
       super.onCreate(savedInstanceState); 
       //实例化广播接收者
       MyReceiver receiver = new MyReceiver();
       //实例化过滤器并设置要过滤的广播
       String action = "android.provider.Telephony.SMS_RECEIVED";
       IntentFilter intentFilter = new IntentFilter();
       intentFilter.addAction(action);
       registerReceiver(receiver,intentfilter);//注册广播
}
protected void onDestroy() {
    
    
       super.onDestroy();
       //当Activity销毁时,取消注册
       unregisterReceiver(receiver);
}

1.2 Static Registration

  • Static registration broadcast, on devices less than Android 8.0, as long as the device is turned on, the broadcast receiver can receive the broadcast.
<?xml version="1.0" encoding="utf-8"?>
<manifest ……….  >
     <application ……… > 
         <receiver
                 android:name=".MyReceiver"
                 android:enabled="true"
                 android:exported="true" >
         </receiver> 
    </application>
 </manifest>

1.3 Custom broadcast

  • When the broadcast provided by the system cannot meet the actual needs, you can customize the broadcast, and you need to write the corresponding broadcast receiver.
    insert image description here
  • When a custom broadcast sends a message, it will be stored in the public message area, and if there is a corresponding broadcast receiver in the public message area, the message will be received in time.

2. Types of Broadcasting

The Android system provides two broadcast types, ordered broadcast and disordered broadcast, and developers can set different broadcast types for programs according to their needs.

  1. Unordered broadcast: Unordered broadcast is executed completely asynchronously. When a broadcast is sent, all broadcast receivers listening to this broadcast will receive this message, but the order of receipt is uncertain.
    insert image description here
  2. Orderly broadcast: Receive according to the priority of the receiver. Only one broadcast receiver can receive the message. After the logic execution in this broadcast receiver is completed, the message will continue to be delivered.
    insert image description here
  3. local broadcast
  • Use the LocalBroadcastManager.sendBroadcast method to send broadcasts within the same app as the sender. If you don't need to send broadcasts between different apps, use local broadcasts. This broadcast implementation is more efficient, does not require inter-process communication, and does not need to worry about security restrictions.

Three priority

  • The larger the value, the higher the priority. If two broadcast receivers have the same priority, the broadcast receiver registered first will have higher priority.
//动态注册MyReceiver广播
MyReceiver  one = new MyReceiver ();
IntentFilter filter = new IntentFilter();
filter.setPriority(1000); 
filter.addAction("Intercept_Stitch");
registerReceiver(one,filter);

orderly broadcast

Orderly broadcast, it has two broadcast methods:

  1. The first method has the form:

    sendOrderedBroadcast(Intent, String)
    
    • The second parameter can be omitted. If it is omitted, it means that the broadcast receiver can receive it without a certain permission. If it is not omitted, the broadcast receiver must have the permission specified by the second parameter to receive the broadcast. The first parameter value intent contains the corresponding action in the intent filter of the broadcast receiver.
  2. The second method has the form:

    public abstract void sendOrderedBroadcast (Intent intent, String receiverPermission, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras)
    
    • The first two parameters of this method are the same as the previous method. The third parameter indicates the last receiver that must receive the broadcast. The fourth parameter is used to specify the thread that schedules the third receiver. If it is null, it indicates the context The main thread;
      initialCodethe initial value of the result code, usually Activity.RESULT_OK.
      initialDataThe initial value of the result data, usually null.
      initialExtrasThe initial value of the additional result, usually null.

4.1 Interrupt broadcast

  • If the broadcast receiver wants to interrupt the broadcast, it can call to mark abortBroadcast ()the received ordered broadcast no longer to be delivered. If the sendOrderedBroadcastlast receiver is specified in the broadcast, the broadcast will be delivered to the last receiver.
  • If you want to cancel the interrupt broadcast, executeclearAbortBroadcast ()

4.2 Get result status and data

By calling getResultCode (), you can get the result code passed by the previous receiver;
by calling getResultData (), you can get the result data passed by the previous receiver, usually null;
by calling getResultExtras (boolean makeMap), you can get the additional data passed by the previous receiver, parameters If it is true, it means that if there is no additional data passed, it will automatically create an empty one Map. If the parameter is false, it means that if there is no additional data passed, it will only return null and will not create a new one.Map

4.3 Setting result status and data

By calling setResult (int code, String data, Bundle extras), change the result code, result data and additional results in the ordered broadcast;
by calling to setResultCode (int code)set the result code, the parameter is usually RESULT_CANCELEDand RESULT_OK;
by calling setResultData (String data), change the broadcast result data;
by calling setResultExtras (Bundle extras), the original additional data in the broadcast will be replaced

4.4 Judging whether it is an ordered broadcast

Call isOrderedBroadcast ()to determine whether the received broadcast is a sequential broadcast

Wu restricts broadcasting through permissions

  • Permissions can be used to restrict broadcasts from being sent to certain app collections, either by restricting the sender or by restricting the receiver.

5.1 Send Add permission

  • When calling sendBroadcast(Intent, String)or sendOrderedBroadcast(Intent, String, BroadcastReceiver, Handler, int, String, Bundle), you can specify a permission parameter. Only receivers who have obtained the permission in the manifest can receive the broadcast.
  • For example:
    sendBroadcast(new Intent("com.example.NOTIFY"),Manifest.permission.SEND_SMS);
    
  • In order to receive this broadcast, the receiver must obtain permission:
    //指定一个存在的系统权限,也可以使用<permission>自定义一个权限
    <uses-permission android:name="android.permission.SEND_SMS"/>
    
  • Note: Custom permissions are registered when the app is installed into the system. Custom permissions must be used after the app is installed.

5.2 Receive Add permission

  • When registering a broadcast receiver, you specify a permission parameter, (either using registerReceiver(BroadcastReceiver, IntentFilter, String, Handler)or in manifest的<receiver>the tag), then only those broadcasters that manifestuse the permission in the broadcast receiver will send broadcast intents to the receiver.<uses-permission>
  • Suppose the broadcast receiver manifest is defined as follows:
    <receiver android:name=".MyBroadcastReceiver"
              android:permission="android.permission.SEND_SMS">
        <intent-filter>
            <action android:name="android.intent.action.AIRPLANE_MODE"/>
        </intent-filter>
    </receiver>
    
  • Or register a broadcast receiver in MainActivity:
    IntentFilter filter = new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED);
    registerReceiver(receiver, filter, Manifest.permission.SEND_SMS, null );
    
  • In order to send a broadcast to a receiver, the sending app must obtain permission as follows:
    <uses-permission android:name="android.permission.SEND_SMS"/>
    

Lu important topic

  1. Briefly describe the implementation process of the broadcast mechanism
    insert image description here
    1. The broadcast receiver registers in AMS (Activity Manager Service) through the Binder mechanism
    2. The broadcast sender sends broadcasts to AMS through the Binder mechanism.
    3. AMS finds the broadcast receiver (BroadcastReceiver) that meets the corresponding conditions (IntentFilter/Permission), and sends the broadcast to the corresponding message loop queue.
    4. When the broadcast is obtained during the execution of the message loop, the onReceive() method in the broadcast receiver (BroadcastReceiver) will be called back and related processing will be performed in this method.
  2. Briefly describe the difference between ordered broadcast and disordered broadcast
    1. Sending broadcasts uses a different method. Ordered broadcasts use sendOrderedBroadcast()send broadcasts, while unordered broadcasts use sendBroadcast()method send broadcasts.
    2. The order in which broadcast receivers execute.
      • Receivers of ordered broadcasts are executed sequentially. Ordered broadcasts are received sequentially according to the priority declared by the broadcast receiver. The broadcast will not continue to be delivered until the high-level broadcast receiver logic has been executed. When the priorities are the same, the broadcast receiver registered first will be executed first.
      • Out-of-order broadcasts are performed completely asynchronously. When an out-of-order broadcast is sent, all broadcast receivers listening to this broadcast will receive this broadcast message, but the order of reception and execution is uncertain.
    3. Intercepting broadcasts: Receivers of ordered broadcasts can intercept broadcasts. If a higher-priority broadcast receiver terminates the broadcast, the broadcast will not be passed back. Out-of-order broadcasts cannot be intercepted.
    4. Efficiency: Ordered broadcasts are less efficient than out-of-order broadcasts.

  1. abortBroadcast: This method can terminate the ordered broadcast
  2. NEW_OUTGOING_CALL is registered in the list file, and the method to get the broadcast event in the code is ( ).
    A, getAction()
    B, getActionCall()
    C, getMethod()
    D, getOutCall()
  • Parse:
    • The way to get broadcast events in code is to use broadcast receiver (BroadcastReceiver) to handle broadcast events. When a broadcast event is received, the onReceive() method of the broadcast receiver will be called, and information about the broadcast event can be obtained through the Intent parameter. When processing the NEW_OUTGOING_CALL broadcast event, the action (Action) of the broadcast event can be obtained through the getAction() method of the Intent. For example:
    //通过intent.getAction()方法获取广播事件的动作,并将其与"android.intent.action.NEW_OUTGOING_CALL"进行比较,
    //以判断是否接收到了NEW_OUTGOING_CALL广播事件
    public class MyBroadcastReceiver extends BroadcastReceiver {
          
          
        @Override
        public void onReceive(Context context, Intent intent) {
          
          
            String action = intent.getAction();
            if (action.equals("android.intent.action.NEW_OUTGOING_CALL")) {
          
          
                // 处理NEW_OUTGOING_CALL广播事件
            }
        }
    }
    
  1. The correct statement about the broadcast event of text message interception is (
    )
    .
    Same
    D. The above statements are all correct
  2. The resident broadcast means that when the application is closed, if it receives broadcasts from other applications, the program will automatically restart.
  3. In the manifest file, the node used when registering broadcast is (C).
    A, <Activity>
    B, <Broadcast>
    C, <receiver>
    D,<broadcastreceiver>
    • The node used when registering the broadcast in the manifest file is <receiver>. <receiver>Nodes are used to declare a broadcast receiver ( BroadcastReceiver) for receiving and processing broadcast events. In <receiver>the node, you can specify the broadcast receiver's class name, priority, filter and other attributes.
  4. For some special broadcast events, such as screen lock and unlock, for such broadcast events, dynamic code registration is required, and registration in the manifest file does not take effect
  5. The action corresponding to the broadcast event for registering outbound calls isandroid_intent.action.NEW_OUTGOING_CALL
  6. The following description of the Exported attribute in statically registered broadcast receivers is correct ().
    A. Whether the broadcast receiver can be instantiated by the system
    B. Whether to receive broadcasts outside the current program
    C. Create the name of the broadcast receiver
    D. None of the above statements are correct
  7. The code needs to call the ( registerReceiver() ) method to register the broadcast, and the ( unregisterReceiver() ) method to cancel the broadcast
  8. There are two ways to register broadcast, resident broadcast and ( non-resident broadcast )
    - There are two ways to register broadcast, resident broadcast and non-resident broadcast.
    1. Sticky Broadcast: Sticky broadcast means that after the broadcast is sent, even if there is no registered broadcast receiver, the broadcast receiver registered subsequently can receive the broadcast. Permanent broadcasts can sendStickyBroadcast(Intent intent)be sent via methods. This kind of broadcast is suitable for scenarios where broadcast events need to be received by subsequent registered broadcast receivers after the broadcast is sent.
    2. Non-resident broadcast (Normal Broadcast): A non-resident broadcast means that only registered broadcast receivers can receive the broadcast after it is sent. Non-resident broadcasts sendBroadcast(Intent intent)are sent via methods. This broadcast is suitable for scenarios where only registered broadcast receivers are expected to receive broadcast events.
  • It should be noted that resident broadcasts may increase the burden on the system, because even if there are no registered broadcast receivers, the system will still store broadcast events in memory until a broadcast receiver is registered. Therefore, resident broadcasts should be used with caution to avoid unnecessary impact on system performance.
  1. The broadcast event corresponding to the phone restart is ( android.intent.action.BOOT_COMPLETED )
  2. Broadcasting is a mechanism used between applications ( passing messages )
  3. The permission to be added to the broadcast event of the registration system SMS arrival is ( android.permission.RECEIVE_SMS )

Seven supplementary content

  1. Ordered broadcast and out-of-order broadcast in android
    • In Android, broadcast can be divided into ordered broadcast (Ordered Broadcast) and disorderly broadcast (Normal Broadcast), and their main difference lies in the delivery method of broadcast and the order of receivers.
    1. Normal Broadcast:
      • sent via Context.sendBroadcast(Intent)method.
      • Broadcasting is asynchronous, and does not wait for the receiver's processing result after sending the broadcast.
      • All receivers matching the broadcast will receive the broadcast at the same time.
      • The order of processing among receivers is indeterminate and can be executed in parallel.
    2. Ordered Broadcast:
      • sent via Context.sendOrderedBroadcast(Intent, String)method.
      • The broadcast is synchronous, and after sending the broadcast, it will be delivered one by one according to the priority order of the receivers.
      • Broadcast receivers can receive broadcasts in priority order and can interrupt the delivery of broadcasts.
      • After receiving the broadcast, each receiver can decide whether to interrupt the broadcast or modify the content of the broadcast.
      • The processing order among receivers is determined, and the latter receivers depend on the processing results of the previous receivers.

In an ordered broadcast, each receiver can call abortBroadcast()a method to interrupt the delivery of the broadcast, so that subsequent receivers will not receive the broadcast. In out-of-order broadcast, the receivers are independent, and the operation of one receiver will not affect other receivers.


  1. Please explain how many ways there are to register broadcasts and what are the advantages and disadvantages of these ways?
    • Non-resident broadcast: This kind of broadcast depends on the life cycle of the component that registered the broadcast. For example, register the broadcast receiver in the Activity, and the broadcast will be removed when the Activity is destroyed.
    • Permanent broadcast: When the application is closed, if it receives broadcasts from other applications, the program will automatically restart. However, if the application is installed but not opened in the system above 4.0, the application cannot receive the broadcast information when there is a broadcast.

  1. Please briefly describe which features require permission to receive system broadcasts
    • dial number:< uses-permission android:name=android.permission.CALL_PHONE/>
    • send messages:< uses-permission android:name=android.permission.SEND_SMS />
    • Device power on:< uses-permission android:name=android.permission.RECEIVE_BOOT_COMPLETED />
    • battery is low:< uses-permission android:name=android.intent.action.BATTERY_LOW/>

Guess you like

Origin blog.csdn.net/yang2330648064/article/details/131395219