In-depth analysis of Android BroadcastReceiver (8)

Article Directory

    • In-depth Analysis of Android Broadcast Receiver (8)
    • 1. System and Custom Implementation
      • 1.1 System broadcast mechanism
        • 1.1.1 Implementation principle of system broadcasting
        • 1.1.2 Source code analysis of system broadcasting
      • 1.2 Custom broadcast mechanism
        • 1.2.1 Implementation steps of custom broadcast
        • 1.2.2 Source Code Analysis of Custom Broadcast
    • 2. The original intention and advantages of broadcast mechanism design
      • 2.1 Design intent
      • 2.2 Advantages
    • 3. Sum up

In-depth Analysis of Android Broadcast Receiver (8)

1. System and Custom Implementation

In order to understand the broadcast mechanism of Android more comprehensively, it is very important to deeply analyze its underlying implementation principle and design logic. This section will explore the system implementation of the broadcast mechanism and the internal working mechanism of the custom broadcast.

1.1 System broadcast mechanism

System broadcast is an important mechanism in the Android operating system for notifying applications of system events. System broadcasts are typically used to notify system level events such as network changes, low battery, screen unlock, etc.

1.1.1 Implementation principle of system broadcasting

The implementation of system broadcasting mainly involves BroadcastReceiver key components such as, Intent, Context and ActivityManagerService (AMS). The following is the process of system broadcast sending and receiving:

  1. Broadcast transmission

An application or system send a broadcast through a Context.sendBroadcast() method.

Intent intent = new Intent("com.example.SOME_ACTION");
context.sendBroadcast(intent); 
  1. Broadcast registration

The application registers the broadcast receiver through the Context.registerReceiver() method.

IntentFilter filter = new IntentFilter("com.example.SOME_ACTION");
context.registerReceiver(new MyReceiver(), filter); 
  1. AMS handles the broadcast

After the broadcast is sent, ActivityManagerService the (AMS) is responsible for the distribution of the broadcast. AMS finds all receivers registered for the broadcast and distributes the broadcast message to those receivers.

  1. Receive broadcast

A registered broadcast receiver receives and processes a broadcast by a onReceive() method.

public class MyReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // Handle received broadcasts
    }
} 
1.1.2 Source code analysis of system broadcasting

Take Intent.ACTION_BATTERY_LOW this as an example to analyze the source code of system broadcasting:

  1. Broadcast transmission

When the system detects a low battery, it broadcasts by BatteryService sending a low battery:

Intent intent = new Intent(Intent.ACTION_BATTERY_LOW);
mContext.sendBroadcast(intent); 
  1. AMS Distribution Broadcast

After ActivityManagerService receiving the broadcast request, distribute it through the BroadcastQueue internal:

void processNextBroadcastLocked(boolean fromMsg) {
    ...
    // Get the next broadcast
    BroadcastRecord r = mBroadcastQueue.dequeueBroadcastLocked(fromMsg);
    ...
    // Distribute broadcast
    deliverToRegisteredReceiverLocked(receiver, info, r);
} 
  1. Receive broadcast

The broadcast is received by the receiver registered by the application and processed by the onReceive() method:

@Override
public void onReceive(Context context, Intent intent) {
    if (Intent.ACTION_BATTERY_LOW.equals(intent.getAction())) {
        // Handling low battery broadcasts
    }
} 

1.2 Custom broadcast mechanism

Custom broadcast is an important means of communication between components in an application, which is usually used for data transfer or event notification between modules.

1.2.1 Implementation steps of custom broadcast
  1. Define the broadcast intent

To define the intent of a custom broadcast:

Intent intent = new Intent("com.example.CUSTOM_ACTION");
intent.putExtra("data", "Sample data");
context.sendBroadcast(intent); 
  1. Register the broadcast receiver

Register a receiver in the application to receive custom broadcasts:

IntentFilter filter = new IntentFilter("com.example.CUSTOM_ACTION");
context.registerReceiver(new CustomReceiver(), filter); 
  1. Receive and process broadcast

Customize the receiver implementation onReceive() method to handle the broadcast:

public class CustomReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if ("com.example.CUSTOM_ACTION".equals(intent.getAction())) {
            String data = intent.getStringExtra("data");
            // Process received broadcast data
        }
    }
} 
1.2.2 Source Code Analysis of Custom Broadcast

The processing mechanism of custom broadcast is similar to that of system broadcast. The main difference is that the definition and registration process of broadcast is controlled by the developer.

  1. Send a broadcast

Send through Context.sendBroadcast() method for custom broadcast:

Intent intent = new Intent("com.example.CUSTOM_ACTION");
context.sendBroadcast(intent); 
  1. AMS handles the broadcast

Custom broadcasts are also distributed through AMS, and the distribution mechanism is consistent with the system broadcast. The broadcast message AMS is distributed to the corresponding receivers according to the list of registered receivers.

  1. Receive broadcast

The registered receiver receives and processes the broadcast:

@Override
public void onReceive(Context context, Intent intent) {
    if ("com.example.CUSTOM_ACTION".equals(intent.getAction())) {
        String data = intent.getStringExtra("data");
        // Handle broadcast data
    }
} 

2. The original intention and advantages of broadcasting mechanism design

2.1 Design intent

  1. Decoupling components

One of the original purposes of the broadcast mechanism is to decouple the various components in the application, making the communication between components more flexible and loosely coupled. Through broadcasting, components do not need to refer to each other directly, but communicate through broadcasting messages, thus reducing the dependency between components.

  1. Asynchronous communication

The broadcast mechanism provides a way of asynchronous communication, so that messages can be sent and received in different threads without blocking the main thread, thus improving the response speed of the application and the user experience.

  1. System event notification

The broadcast mechanism allows the system to notify the application of various system events (such as network changes, battery status, etc.), so that the application can respond to changes in the system state, thereby improving the intelligence of the application and the user experience.

2.2 Advantages

  1. Loose coupling

The broadcast mechanism communicates between components in an event-driven way, which realizes loose coupling, reduces the dependency between components, and improves the maintainability and extensibility of the code.

  1. Flexibility

The broadcast mechanism supports both dynamic and static registration, providing great flexibility. Applications can register broadcast receivers dynamically at runtime as needed, or they can register receivers statically through Manifest files.

  1. Global Communication

The broadcast mechanism supports global communication. The system broadcast can be received by any application, and the custom broadcast can perform global communication within the application, which is suitable for scenarios requiring global notification.

3. Sum up

Broadcast mechanism is an important asynchronous communication method in Android. Through system broadcast and custom broadcast, the loose coupling and flexible communication inside and outside the application are realized. In the actual development, developers should choose the appropriate broadcast mechanism according to the specific requirements, and follow the best practices to improve the performance and security of the application.

  • System broadcast: Used to notify applications of system-level events, broadcast distribution via AMS.
  • Customize the broadcast: Used for communication between components within the application, broadcast sending and receiving via custom intents.
  • Security and performance optimization: Improve application security and performance by setting permissions, using LocalBroadcast Manager, and managing the lifecycle of broadcast receivers.

Through in-depth understanding of the implementation principle and design logic of the broadcast mechanism, developers can more efficiently use the broadcast mechanism to develop applications and build high-quality Android applications.