Broadcasting of the four major components of Android

1. Introduction

In Android application development, the broadcast component is a key technology and is widely used in various tasks and scenarios. Whether sending system-level broadcasts or implementing communication between components within an application, understanding and mastering the working principles and usage of broadcast components is crucial for every Android developer. This article aims to help you gain an in-depth understanding of Android broadcast components and give some practical tips and suggestions.

Study with questions

What is broadcasting?
What features does broadcast include?
How are broadcasts sent and received?
How to register for broadcasting and what are the registration methods?
What system broadcasts are there?
What is the difference between static registration and dynamic registration?
How to quickly create a broadcast receiver in Android?
How to send a custom broadcast?
What types of broadcasts are there?
What safety and compliance issues do I need to pay attention to when using broadcasts?

2. What is broadcast?

Broadcast is a mechanism in the Android operating system used for communication between or within applications. It allows one application to send messages (broadcast events), and other applications can receive and respond to these messages.

3. Broadcast transmission

1. System broadcast

System broadcasts are broadcasts emitted by the Android operating system itself to notify applications about changes in device status and system events.

Common system broadcasts

broadcast action describe illustrate
android.net.conn.CONNECTIVITY_CHANGE Network status changes Broadcast sent when the device's network connection status changes. You can detect changes in network connectivity by listening to this broadcast and adjust your application's behavior accordingly.
android.intent.action.BATTERY_CHANGED Changes in device power Broadcast sent when the device's battery level changes. Applications can obtain current battery power information by listening to this broadcast, and take appropriate operations based on changes in power.
android.intent.action.SCREEN_ON screen on Broadcast sent when the device's screen is turned on. Applications can listen to this broadcast to perform specific operations, such as launching screen-related functions.
android.intent.action.SCREEN_OFF screen off Broadcast sent when the device's screen is turned off. Applications can listen to this broadcast to perform corresponding operations, such as turning off screen-related functions.
android.intent.action.BOOT_COMPLETED Device startup completed Broadcast sent when device startup is complete. The application can perform some initialization operations or start specific services by listening to this broadcast to ensure that the application runs normally after the device starts.
android.intent.action.TIMEZONE_CHANGED time zone change Broadcast sent when the device's time zone changes. Applications can adjust time-related functions based on time zone changes.
android.intent.action.AIRPLANE_MODE Flight mode changes Broadcast sent when the device's airplane mode is on or off. Applications can listen to this broadcast and take appropriate actions.
android.intent.action.MEDIA_MOUNTED Storage media is mounted Broadcast sent when storage media (such as SD card) is mounted on the device. Applications can respond to storage media mount events by listening to this broadcast.
android.intent.action.MEDIA_REMOVED Storage media removed Broadcast sent when storage media (such as SD card) is removed from the device. Applications can listen to this broadcast and handle it accordingly.
android.intent.action.PACKAGE_ADDED Application installation completed Broadcast sent when the application is installed. Applications can listen to this broadcast to perform appropriate operations.
android.intent.action.PACKAGE_REMOVED Application uninstall completed Broadcast sent when the application is uninstalled. Applications can listen to this broadcast to perform appropriate operations.
android.intent.action.HEADSET_PLUG Headphone plug and unplug event Broadcast sent when headphones are plugged into or unplugged from the device. Applications can listen to this broadcast and handle it accordingly.
android.intent.action.WALLPAPER_CHANGED Wallpaper changes Broadcast sent when the device's wallpaper changes. Applications can listen to this broadcast and handle it accordingly.

2. Custom broadcast

In Android, the sending type of custom broadcast is similar to the system broadcast. You can use standard broadcast, ordered broadcast and sticky broadcast.

1. Normal Broadcast

Normal Broadcast is a common broadcast type in Android. It is an asynchronous broadcast, which means that after sending the broadcast, the sender does not wait for the receiver's processing results, but returns immediately. All recipients matching the broadcast receive the broadcast message simultaneously.

Features
  1. The sender of the broadcast will not know which receivers have received the broadcast message, nor can it affect the execution order of the receivers.
  2. The recipient cannot interrupt or cancel the delivery of the broadcast.
  3. The sending and receiving of broadcasts is completely asynchronous, and there is no direct interaction between the sender and the receiver.
When standard broadcasting applies
  • Broadcast messages do not require ordered processing, i.e. the order of execution among receivers is not important.
  • The sender of a broadcast message does not care about the processing results of the receiver.
  • The broadcast needs to be sent to all matching recipients without specific filtering of the broadcast.
Code implementation example
// 创建Intent对象
Intent intent = new Intent();

// 设置广播的动作
intent.setAction("com.example.MY_CUSTOM_ACTION");

// 发送有序广播
sendBroadcast(intent, null);

2. Ordered Broadcast

Ordered Broadcast is another common broadcast type in Android. Unlike standard broadcasts, ordered broadcasts are sent to matching receivers in order of priority, and each receiver can choose to terminate the broadcast or pass the broadcast to the next receiver after processing the broadcast.

Features
  • Ordered broadcast allows receivers to process broadcast messages in priority order. Receivers can control their execution order in the broadcast chain by setting priorities.
  • Each receiver can interrupt the delivery of a broadcast to prevent other receivers from continuing to receive broadcast messages.
  • The sender of an ordered broadcast can obtain the results of the receiver processing the broadcast because each receiver can return a result code.
When orderly broadcast applies
  • Broadcast messages need to be processed in a specific order to ensure that recipients execute them in the expected order.
  • It is necessary to control the delivery of broadcasts and allow the receiver to interrupt the delivery of broadcasts.
  • Requires communication and collaboration between receivers to return results to the broadcast sender by setting result codes.
Code implementation example
// 创建Intent对象
Intent intent = new Intent();

// 设置广播的动作
intent.setAction("com.example.MY_CUSTOM_ACTION");

// 发送有序广播
sendOrderedBroadcast(intent, null);

3. Sticky Broadcast

Sticky Broadcast is a special type of broadcast in Android. Unlike standard broadcasts and ordered broadcasts, sticky broadcasts remain in the system even if there are no matching recipients. When new receivers register, they receive the latest sticky broadcast immediately.

Features
  • Sticky broadcasts remain in the system until new recipients are registered. Even if the broadcast has been sent for some time, the recipient can still receive the latest broadcast message.
  • The receiver will receive the latest sticky broadcast message immediately after registration without waiting for the next broadcast to be sent.
  • Sticky broadcasts can be used to pass application state information to components that are not running, or to restore a previous state after the application is restarted.
When sticky broadcast applies
  • The broadcast needs to be sent before the receiver is registered to ensure that the receiver can get the latest broadcast message immediately.
  • Broadcast messages need to be delivered to non-running components so that they can handle them as soon as they receive the broadcast.
  • It is necessary to restore the previous state after the application is restarted by receiving the sticky broadcast message sent before.
Code implementation example
// 创建Intent对象
Intent intent = new Intent();

// 设置广播的动作
intent.setAction("com.example.MY_CUSTOM_ACTION");

// 发送粘性广播
sendStickyBroadcast(intent);

3. Local broadcast

Local Broadcast is an application-specific broadcast mechanism used to communicate between internal components of the application. Unlike global broadcasts, local broadcasts only propagate within the boundaries of the application and do not leave the application context.

Features

  • Local broadcasts are only propagated within the application and will not be leaked to other applications, providing higher security.
  • The propagation range of local broadcasts is limited to the boundaries of the application and will not affect other applications.
  • The sending and receiving of local broadcasts are synchronous, that is, the sender will wait for the processing result of the receiver.

Where local broadcasting applies

  • Communicate between components within an application without wanting to pass broadcasts to other applications.
  • You need to ensure that broadcast messages are only valid within the application to avoid unintended effects on other applications.
  • It is necessary to wait synchronously for the result of the receiver processing the broadcast message.

code example

// 创建Intent对象
Intent intent = new Intent();

// 设置广播的动作
intent.setAction("com.example.MY_LOCAL_ACTION");

// 发送本地广播
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);

4. Reception of broadcasts

In Android, to receive broadcasts, you need to create a broadcast receiver (BroadcastReceiver). A broadcast receiver is a component that receives and processes broadcast messages sent to an application.

1. Create a broadcast receiver class

Create a class that inherits from BroadcastReceiver and implement the onReceive(Context, Intent) method. Write the processing logic after receiving the broadcast in the onReceive method.

public class MyBroadcastReceiver extends BroadcastReceiver {
    
    
    @Override
    public void onReceive(Context context, Intent intent) {
    
    
        // 在这里编写接收到广播后的处理逻辑
        // 根据广播的动作或其他信息进行相应的操作
    }
}

2. Register broadcast receiver

1. Static Registration

  • Static registration is registered in the application's manifest file (AndroidManifest.xml) by declaring the class name and related configuration of the broadcast receiver in the tag.
  • Staticly registered broadcast receivers will be known to the system when the application is installed, and can receive broadcast messages regardless of whether the application is running.
  • Example:
<receiver
    android:name=".MyBroadcastReceiver"
    android:exported="true">
    <intent-filter>
        <action android:name="com.example.MY_CUSTOM_ACTION" />
    </intent-filter>
</receiver>

2. Dynamic Registration

  • Dynamic registration is to use the registerReceiver() method to dynamically register a broadcast receiver in the application code.
  • A dynamically registered broadcast receiver can only receive broadcast messages after calling the registerReceiver() method, and needs to call the unregisterReceiver() method to unregister at the appropriate time to avoid memory leaks.
  • Example:
// 创建广播接收器实例
MyBroadcastReceiver receiver = new MyBroadcastReceiver();

// 创建IntentFilter对象,并添加接收的广播动作
IntentFilter filter = new IntentFilter();
filter.addAction("com.example.MY_CUSTOM_ACTION");

// 注册广播接收器
context.registerReceiver(receiver, filter);

3. Process the received broadcast

After receiving the broadcast, you need to write processing logic in the onReceive(Context, Intent) method of the broadcast receiver (BroadcastReceiver)

1. Implement the onReceive method in the broadcast receiver class

public class MyBroadcastReceiver extends BroadcastReceiver {
    
    
    @Override
    public void onReceive(Context context, Intent intent) {
    
    
        // 在这里编写接收到广播后的处理逻辑
    }
}

2. Obtain broadcast-related information through the Intent object

  • Action: Use the getAction() method to obtain the broadcast action, and perform corresponding operations according to the action type.
  • Data: Use the getData() method to obtain broadcast data, if the broadcast carries data.
  • Extra information (Extras): Use the getExtras() method to obtain additional information broadcast. You can obtain specific information in the form of key-value pairs.
  • Example:
public class MyBroadcastReceiver extends BroadcastReceiver {
    
    
    @Override
    public void onReceive(Context context, Intent intent) {
    
    
        String action = intent.getAction();
        Uri data = intent.getData();
        Bundle extras = intent.getExtras();
        
        // 根据广播的动作、数据或额外信息进行相应的处理
    }
}

3. Perform the appropriate operations

  • Based on the broadcast action or other information, perform appropriate operations, such as updating UI, starting services, sending notifications, etc.
  • You can use the Context object to perform specific operations, such as starting an Activity, obtaining system services, etc.
  • Example
public class MyBroadcastReceiver extends BroadcastReceiver {
    
    
    @Override
    public void onReceive(Context context, Intent intent) {
    
    
        String action = intent.getAction();
        
        if ("com.example.MY_CUSTOM_ACTION".equals(action)) {
    
    
            // 执行相应的操作
            // ...
        }
    }
}

5. Expand reading and resources

Broadcast overview

Guess you like

Origin blog.csdn.net/qq_42886163/article/details/131547431