“This is the 21st day of my participation in the Gwen Challenge in November. See details: The Last Gwen Challenge in 2021”

Introduction of Broadcast

Broadcast is one of the four components in Android and is a mechanism for propagating data (intents) between components. The sender and receiver of a broadcast need not know of each other’s existence beforehand. The benefit of this is that the components of the system can be loosely coupled together, making the system highly extensible and easy to integrate with other systems.

Radio features

  1. The broadcast lifecycle is very short, and onReceive is the end of the whole process.
  2. Do not perform time-consuming tasks on the broadcast receiver; otherwise, the Application No Response dialog box will be displayed. If a time-consuming task needs to be completed, send an Intent to the Service to complete the task.
  3. Each time a broadcast arrives, the BroadcastReceiver object is recreated and the onReceive() method is called, which is then destroyed. If the onReceive() method does not complete execution within 10 seconds, the program is considered unresponsive. It is not recommended to open child threads in the broadcast object, because the broadcast object will be destroyed before the thread is finished.

There are two main types of broadcasts in Android:

Standard radio

Is a broadcast that executes completely asynchronously, which is efficient but cannot be truncated.

Orderly broadcast

A synchronous square wave in which only one broadcast receiver receives a message at a time, and the message is transmitted only after the previous logic has been executed.

Radio reception

Dynamic registration

IntentFilter filter = new IntentFilter();
filter.addAction("This is an action.");
BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG, "onReceive: " + "Receive message processing"); }}; registerReceiver(mReceiver, filter);Copy the code

Dynamically registered broadcast receivers must be unregistered, typically by calling unregisterReceiver(mReceiver) in the onDestroy() method;

Static registration

<receiver android:name=".MyReceiver">
    <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>// Action must be specified</intent-filter>
</receiver>
Copy the code