Hi, you finally come ~ wait for you for a long time ~ like friends welcome to pay attention to, I will regularly share Android knowledge and analysis, and will constantly update the BATJ interview topic, welcome to come to discuss and exchange, if there is a good article also welcome to contribute.

preface

Before, some friends sent me a message asking me to talk about the four major components of Android. I was busy with my work these days, so I put it on hold. Today, the project has finally come to an end, so I decided to talk about the in-depth knowledge of the four components respectively from this article

As we all know, BroadcastReceiver is one of the four components of Android. There are a lot of application scenarios of BroadcastReceiver in Android development, so today’s first article, I’m going to cover everything there is to know about BroadcastReceiver.

directory

Definition 1.

Broadcast, a global listener, is one of the four components of Android

Android broadcast is divided into two roles: broadcast sender and broadcast receiver

2. The role

Listen to/receive broadcast messages sent by the App and respond to them

3. Application scenarios

  • AndroidCommunication between different components (including intra-application/inter-application)
  • Multithreaded communication
  • withAndroidThe communication of a system under certain circumstances

For example, when a call is made or the network is available

4. Implementation principle

4.1 Model adopted

  • AndroidThe broadcast used in design modeObserver model: message-based publish/subscribe event model

As a result, Android decouples the sender and receiver of a broadcast, making the system easier to integrate and expand

4.2 Model Explanation

  • There are three roles in the model:

    1. Message subscriber (broadcast receiver)
    2. Message Publisher (Broadcast publisher)
    3. Message center (AMS, i.e.,Activity Manager Service)
  • Schematic diagram & principle as follows

Schematic diagram

5. Use a process

  • The usage process is as follows:

Schematic diagram

  • Next, I will introduce how to use it step by stepBroadcastReceiver

This is what the developer did manually, as shown above

5.1 Customizing Broadcast Receivers BroadcastReceiver

  • inheritanceBroadcastReceivreThe base class
  • An abstract method must be overriddenonReceive()methods
  1. When the broadcast receiver receives the corresponding broadcast, it automatically calls backonReceive()methods
  2. In general,onReceiveMethods involve interactions with other components, such as sendingNotification, start,ServiceEtc.
  3. By default, the broadcast receiver runs onUIThreads, therefore,onReceive()Method cannot perform time-consuming operations that would otherwise causeANR
  • Code example

    mBroadcastReceiver.java
// Extends the BroadcastReceivre base class
public class mBroadcastReceiver extends BroadcastReceiver {

  // Copy the onReceive() method
  // When a broadcast is received, the method is automatically called
  @Override
  public void onReceive(Context context, Intent intent) {
   // Write the operation after receiving the broadcast}}Copy the code

5.2 Broadcast receiver registration

There are two ways of registration: static registration and dynamic registration

5.2.1 Static Registration

  • Registration: declared in androidmanifest.xml with the

    tag
  • Attribute Description:
<receiver 
    android:enabled=["true" | "false"]
// Whether the broadcastReceiver can receive broadcasts from other apps
// The default value is determined by the presence or absence of intent-filter in the receiver: true if there is an intent-filter, false otherwise
    android:exported=["true" | "false"]
    android:icon="drawable resource"
    android:label="string resource"
// Extends the name of the BroadcastReceiver subclass
    android:name=".mBroadcastReceiver"
// Only broadcasts sent by BroadcastReceiver with corresponding permissions can be received by the BroadcastReceiver;
    android:permission="string"
//BroadcastReceiver Specifies the process in which the BroadcastReceiver runs
// The default is app process, can specify a separate process
// Note: Each of Android's four basic components can specify their own independent processes via this property
    android:process="string" >

// Used to specify the type of broadcast this broadcast receiver will receive
// In this example, the broadcast is used to receive when the network state changes
 <intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
    </intent-filter>
</receiver>
Copy the code
  • Register the sample
<receiver 
    // This broadcast receiver class is mBroadcastReceiver
    android:name=".mBroadcastReceiver" >
    // Used to receive broadcasts when the network status changes
    <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
    </intent-filter>
</receiver>
Copy the code

When the App is started for the first time, the system automatically instantiates the mBroadcastReceiver class and registers it with the system.

5.2.2 Dynamic Registration

  • Register: Call the context.registerReceiver () method in your code

  • The specific code is as follows:

// Select register in onResume() in the Activity lifecycle method
@Override
  protected void onResume(a){
      super.onResume();

    // 1. Instantiate BroadcastReceiver subclass & IntentFilter
     mBroadcastReceiver mBroadcastReceiver = new mBroadcastReceiver();
     IntentFilter intentFilter = new IntentFilter();

    // 2. Set the type of the broadcast to be received
    intentFilter.addAction(android.net.conn.CONNECTIVITY_CHANGE);

    // 3. Dynamic registration: call the Context registerReceiver () method
     registerReceiver(mBroadcastReceiver, intentFilter);
 }


// After registering a broadcast, remember to destroy the broadcast at the appropriate location
// 即在onPause() 中unregisterReceiver(mBroadcastReceiver)
// When this Activity is instantiated, MyBroadcastReceiver is dynamically registered with the system
// Dynamically registered MyBroadcastReceiver will no longer receive broadcasts when this Activity is destroyed.
 @Override
 protected void onPause(a) {
     super.onPause();
      // Destroy the broadcast in onResume()unregisterReceiver(mBroadcastReceiver); }}Copy the code

Pay special attention to

  • Dynamic broadcasting is best inActivityonResume()Registration,onPause()Cancellation.
  • The reason:
    1. In the case of dynamic broadcast, registration is necessary to have logout, otherwise it will lead to memory leaks

Repeated registration and cancellation are not allowed

  1. ActivityThe life cycle is as follows:

Activity Lifecycle

Methods for the Activity lifecycle come in pairs:

  • onCreate() & onDestory()
  • onStart() & onStop()
  • onResume() & onPause()

Register onResume() and unregister onPause() because onPause() must be executed before the App dies, ensuring that broadcasts are unregistered before the App dies and preventing memory leaks.

  1. Do not register onCreate() & onDestory() or onStart() & onStop() because: When the system attempts to reclaim resources from an Activity because it is running out of memory (memory is required for higher-priority applications, see the red box above), the Activity is destroyed after executing onPause(), and some lifecycle methods onStop() and onDestory() are not executed. When you return to the Activity, you start with the onCreate method.
  2. If we place the broadcast logout in the onStop(), onDestory() methods, it is possible that the onStop(), onDestory() methods are not executed after the Activity is destroyed, resulting in a memory leak.
  3. However, onPause() must be executed to ensure that the broadcast is unregistered before the App dies, preventing memory leaks.

5.2.3 Differences between the two registration methods

Schematic diagram

5.3 Broadcast senders send broadcasts to AMS

5.3.1 Broadcast transmission
  • Broadcast is used with “intent (Intent) mark”
  • Defining the nature of broadcasting = defining the “intent” of broadcasting (Intent)”
  • Broadcast transmission = the “intent” of the broadcast (Intent)”SendBroadcast () methodSend out
5.3.2 Types of broadcasts

There are five main types of broadcasting:

  • General broadcast (Normal Broadcast)
  • System broadcast (System Broadcast)
  • Orderly broadcast (Ordered Broadcast)
  • Viscous broadcast (Sticky Broadcast)
  • In-app broadcasting (Local Broadcast)

The details are as follows: 1. Normal Broadcast is an intent Broadcast defined by the developer (the most common). Use the following to send a broadcast:

Intent intent = new Intent();
// The action corresponding to intentFilter in BroadcastReceiver
intent.setAction(BROADCAST_ACTION);
// Send a broadcast
sendBroadcast(intent);
Copy the code
  • If a registered broadcast receiver is registeredintentFiltertheactionMatches the above, this broadcast is received (that is, a callbackonReceive()). The followingmBroadcastReceiverWill receive the above broadcast
<receiver 
    // This broadcast receiver class is mBroadcastReceiver
    android:name=".mBroadcastReceiver" >
    // Used to receive broadcasts when the network status changes
    <intent-filter>
        <action android:name="BROADCAST_ACTION" />
    </intent-filter>
</receiver>
Copy the code
  • If you have the right to send a broadcast, then the receiver of the broadcast also needs the right

2. System Broadcast

  • Multiple system announcements are built into Android: announcements are made whenever the phone’s basic actions (such as starting up, changing network status, taking photos, etc.) are involved
  • Each broadcast has a specific intent-filter (including specific actions). Android broadcasts actions as follows:
System operation action
Monitoring network changes android.net.conn.CONNECTIVITY_CHANGE
Turn off or on airplane mode Intent.ACTION_AIRPLANE_MODE_CHANGED
Change in charge or charge Intent.ACTION_BATTERY_CHANGED
Low battery Intent.ACTION_BATTERY_LOW
When the battery is fully charged (i.e., when it changes from low to full, it broadcasts Intent.ACTION_BATTERY_OKAY
After the system is started (broadcast only once) Intent.ACTION_BOOT_COMPLETED
Press the take picture button (hardware button) when taking a picture Intent.ACTION_CAMERA_BUTTON
Screen lock screen Intent.ACTION_CLOSE_SYSTEM_DIALOGS
When the device’s current Settings are changed (interface language, device orientation, etc.) Intent.ACTION_CONFIGURATION_CHANGED
When you plug in your headphones Intent.ACTION_HEADSET_PLUG
The SD card is not removed correctly but is removed (Correct removal method: Setup –SD card and device memory — unmount SD card) Intent.ACTION_MEDIA_BAD_REMOVAL
Insert an external storage device (e.g. SD card) Intent.ACTION_MEDIA_CHECKING
The APK is successfully installed Intent.ACTION_PACKAGE_ADDED
The APK was successfully deleted. Procedure Intent.ACTION_PACKAGE_REMOVED
Restart the device Intent.ACTION_REBOOT
Screen turned off Intent.ACTION_SCREEN_OFF
The screen is opened Intent.ACTION_SCREEN_ON
When shutting down the system Intent.ACTION_SHUTDOWN
Restart the device Intent.ACTION_REBOOT

Note: When using the system broadcast, you only need to define the relevant action when registering the broadcast receiver, and do not need to send the broadcast manually. When the system has related operations, the system will automatically broadcast

3. Ordered Broadcast

  • Defines the order in which outgoing broadcasts are received by broadcast receivers

Order is for broadcast receivers

  • Order rules for broadcast receivers to receive broadcasts (for both static and dynamically registered broadcast receivers)

    1. Sort by Priority attribute value from highest to lowest;
    2. If the Priority attribute is the same, dynamically registered broadcasts take precedence.
  • The characteristics of

    1. Receive Broadcasts are received in sequence
    2. The first receiving receiver can truncate the broadcast, that is, the later receiving receiver can no longer receive the broadcast;
    3. The first receiver can modify the broadcast, and the later receiver will receive the modified broadcast
  • The process of using ordered broadcast is very similar to that of ordinary broadcast, except for the way in which the broadcast is sent:

sendOrderedBroadcast(intent);
Copy the code

4. Local Broadcast in App

  • Background Broadcasts in Android can communicate directly across apps (default: true if the intent filter is available).

  • Possible problems arising from conflict:

    • Other apps send broadcasts that match the current App intent-filter. As a result, the current App continues to receive and process broadcasts.
    • Other apps register the same intent-filter as the current App to receive broadcasts and obtain specific broadcast information. There will be safety and efficiency issues.
  • The solution uses Local Broadcast in App

  1. In-app broadcast can be understood as a kind of local broadcast, in which both sender and receiver belong to the same App.
  2. Compared with global broadcast (ordinary broadcast), in-app broadcast has the following advantages: high security & high efficiency
  • Use 1 – to set global broadcast to local broadcast

    1. Set the exported property to
      false

      , so that the broadcast that is not issued within the App cannot be received;

    2. When sending and receiving broadcast, add corresponding permission for permission verification;
    3. When sending a broadcast, specify the packet name of the broadcast receiver. This broadcast will only be sent to the valid broadcast receiver that matches it in the App in this packet.

    Specify sign-up with intent.setPackage(packageName)

  • The LocalBroadcastManager class is used in much the same way as the global BroadcastManager class, except that when registering/unregistering broadcast receivers and sending broadcasts, the context parameter becomes a single instance of LocalBroadcastManager

Note: Intra-application broadcasts sent through LocalBroadcastManager can only be dynamically registered, not statically registered

// Register the in-application broadcast receiver
// Step 1: instantiate IntentFilter mBroadcastReceiver
mBroadcastReceiver = new mBroadcastReceiver(); 
IntentFilter intentFilter = new IntentFilter(); 

// Step 2: Instantiate the LocalBroadcastManager instance
localBroadcastManager = LocalBroadcastManager.getInstance(this);

// Step 3: Set the type of broadcast to be received
intentFilter.addAction(android.net.conn.CONNECTIVITY_CHANGE);

// Step 4: Call the LocalBroadcastManager single instance registerReceiver () method for dynamic registration
localBroadcastManager.registerReceiver(mBroadcastReceiver, intentFilter);

// Unregister the in-application broadcast receiver
localBroadcastManager.unregisterReceiver(mBroadcastReceiver);

// Send in-app broadcasts
Intent intent = new Intent();
intent.setAction(BROADCAST_ACTION);
localBroadcastManager.sendBroadcast(intent);

Copy the code

5. Sticky Broadcast is not recommended and will not be summarized here because it is disabled in Android5.0 & API 21.

6. Pay special attention

OnReceive (Context Context, Intent Intent) returns different values:

  • For static registration (global + application in radio), the callback onReceive (context in the context, intent) the return value is: ReceiverRestrictedContext;
  • For dynamic registration of global broadcasts, the context in onReceive(context, intent) callback returns the following value: Activity context;
  • For LocalBroadcastManager, onReceive(Context, intent) returns the value of Application Context.
  • For applications that are not LocalBroadcastManager, onReceive(Context, intent) returns the following value: Activity context;

7. To summarize

  • This paper mainly introduces theAndroidOf the four major componentsBroadcastReceiverAll knowledge, feel good articles like a small partner canFocus and ShareAnd you are welcome to come and discuss.