Android Interview Collection record 2 broadcast receiver detailed

Source: Internet
Author: User


1.Broadcast Receiver Broadcast receiver brief introduction

1.1. Definition

    • Broadcast receiver (broadcast receiver), one of the four components of Android
    • In Android development, broadcast receiver has a lot of application scenarios. Broadcast, is a global listener, belongs to Android four components.

Android broadcasts are divided into two roles: broadcast sender, broadcast receiver.

1.2. Role

    • Used to listen to and respond to broadcast messages sent by the app.
    • Application Scenarios

A. Communication between different components (including in-app/different applications)

B. Communication with the Android system under certain circumstances (e.g. when the phone is on, when the network is available)

C. Multi-threaded communication

1.3. Principle of implementation

The broadcast in Android uses the Observer pattern in design mode: The message-based publish/subscribe event model.

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

There are 3 characters in the model:

I. Message subscribers (broadcast recipients)

Ii. Message Publishers (broadcast publishers)

Iii. Message Center (AMS, Activity Manager Service)

  

Principle Description:

I. The broadcast recipient is registered with the AMS through the binder mechanism

II. Broadcast sender sends a broadcast to AMS via binder mechanism

Iii. AMS is looking for the right broadcast recipient on the registered list, as required by the broadcast sender.

Finding the basis: Intentfilter/permission

iv. AMS sends the broadcast to the appropriate broadcast receiver in the appropriate message loop queue

V. The broadcast receiver receives this broadcast through a message loop and callbacks Onreceiver ()

  

Special attention:

The execution of the broadcast sender and the broadcast receiver is asynchronous, and the outgoing broadcast does not care whether the receiver receives it or not, and it is not sure when the receiver will receive it;

  


How to use 2.Broadcast Receiver

The specific use process is as follows:

The following step-by-step description of the Developer Manual completion section:

  

4.1. Custom Broadcast Recipient Broadcastreceiver

    • Inherit from Broadcastreceiver base class
    • Must replicate abstract method OnReceive () method

I. After the broadcast receiver receives the corresponding broadcast, the OnReceive () method is automatically recalled.

II. In general, the OnReceive method involves interaction with other components, such as sending notification, starting the service, etc.

III. By default, the broadcast sink runs on the UI thread, so the OnReceive method cannot perform time-consuming operations, otherwise it will result in ANR.

    • code example Mbroadcastreceiver.java

   

 Public class extends broadcastreceiver {  // The method is automatically called after receiving a broadcast   @Override  public  void  onreceive (context context, Intent Intent) {    // write operation after receiving broadcast     }}

4.2. Broadcast Receiver Registration

There are two ways to register: Static registration, dynamic registration

  

  Static registration:

Androidmanifest.xml through <receive> label declaration

Property Description:

<receiver Android:enabled=["true" | "False"]  //whether this broadcastreceiver can receive broadcasts from other apps//The default value is determined by whether or not Intent-filter is in receiver: if there is intent-filter, the default value is True, otherwise falseAndroid:exported=["true" | "False"] Android:icon= "Drawable resource"Android:label= "String Resource"//inheriting the class name of the Broadcastreceiver subclassAndroid:name= ". Mbroadcastreceiver"//A broadcast sent by a broadcast sender with corresponding rights will be received by this broadcastreceiver;Android:permission= "string"//Broadcastreceiver The process where the operation is run//default to the app's process, you can specify a separate process//Note: The four basic components of Android can be used to specify their own independent processes through this propertyAndroid:process= "string" >//used to specify the type of broadcast that this broadcast sink will receive//This example shows a broadcast that is used to receive a change in the network state.<intent-filter> <action android:name= "Android.net.conn.CONNECTIVITY_CHANGE"/> </intent-filter> </receiver>

Registration Example:

<receiver  // This broadcast receiver class is mbroadcastreceiver  android:name= ". Mbroadcastreceiver ">  // broadcast <intent-filter> <action android:name= for receiving network status changes      " Android.net.conn.CONNECTIVITY_CHANGE "/>  </intent-filter></receiver>

When the app is first launched, the Mbroadcastreceiver class is automatically instantiated and registered to the system.

  Dynamic registration:

Dynamically register Broadcastreceiver in code by invoking the *registerreceiver () * Method of the context, with the following code:

  

@Overrideprotected voidOnresume () {Super. Onresume (); //Instantiate Broadcastreceiver subclasses & IntentfilterMbroadcastreceiver Mbroadcastreceiver =NewMbroadcastreceiver (); Intentfilter Intentfilter=NewIntentfilter (); //set the type of receive broadcastintentfilter.addaction (Android.net.conn.CONNECTIVITY_CHANGE); //Invoke Context's Registerreceiver () method for dynamic registrationregisterreceiver (Mbroadcastreceiver, intentfilter);}//after registering the broadcast, remember to destroy the broadcast in the appropriate location//that is, in OnPause () unregisterreceiver (mbroadcastreceiver)//When this activity is instantiated, Mybroadcastreceiver is dynamically registered to the system//When this activity is destroyed, the dynamically registered Mybroadcastreceiver will no longer receive the corresponding broadcast. @Overrideprotected voidOnPause () {Super. OnPause (); //destruction of broadcasts in the Onresume () methodUnregisterreceiver (mbroadcastreceiver);}

Special attention:

Dynamic broadcasts are best registered in the activity's Onresume (), OnPause () logoff.

Reason:

For dynamic broadcasts, there is a need to sign out of registration, otherwise it will cause a memory leak. Duplicate registration, repeat logout is not allowed.

The difference between the two ways of registering:

  

4.3. Broadcast senders send broadcasts to AMS

  Sending of broadcasts:

    • Broadcasts are identified with "intent (Intent)"
    • Defining the nature of broadcasting: Defining the "intent (Intent)" of broadcasting
    • Broadcast send: The broadcast sender sends the "intent" of this broadcast through the Sendbroadcast () method

  Type of broadcast:

 The types of broadcasts are mainly divided into 5 categories:

    • General broadcast (normal broadcast)
    • Systems Broadcast (System broadcast)
    • Orderly broadcast (Ordered broadcast)
    • Sticky Broadcast (Sticky broadcast)
    • App in app broadcast (Local broadcast)

Specify the following:

  

①. Normal broadcast (normal broadcast)

That is, the developer itself defines intent broadcasts (most commonly used). Send a broadcast using the following:

    

New Intent (); // corresponds to Intentfilter action in Broadcastreceiver intent.setaction (broadcast_action); // Send broadcast sendbroadcast (intent);

If the Intentfilter action matches the above in the registered broadcast recipient, the broadcast will be received (that is, Callback OnReceive ()).

The following mbroadcastreceiver will receive the above broadcast

  

<receiver     // This broadcast receiver class is mbroadcastreceiver    android:name= ". Mbroadcastreceiver ">    // broadcast <intent-filter> <action android:name= for receiving network status changes        " broadcast _action "/>    </intent-filter></receiver>

  

If the broadcast has the appropriate permissions, then the broadcast recipient also needs the appropriate permissions

  

②. Systems broadcast (System broadcast)

  

    • Multiple system broadcasts are built into Android: the corresponding broadcasts are issued as long as the basic operation of the phone is involved (such as power-on, network status changes, taking photos, etc.)
    • Each broadcast has a specific intent-filter (including a specific action), and the Android system broadcasts the action as follows:

 

System Operation Action
Monitor network changes Android.net.conn.CONNECTIVITY_CHANGE
Turn off or turn on airplane mode Intent.action_airplane_mode_changed
Charge or power change Intent.action_battery_changed
Low battery power Intent.action_battery_low
The battery is fully charged (that is, it emits a broadcast when it changes from low to full Intent.action_battery_okay
After system boot is complete (broadcast only once) intent.action_boot_completed
When you press the camera button (the hardware key) 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
Plug in the ear machine Intent.action_headset_plug
The SD card was not removed correctly but was removed (correct removal method: Set--SD card and device memory--Uninstall SD card) Intent.action_media_bad_removal
Inserting an external storage device (e.g. SD card) Intent.action_media_checking
Install APK successfully intent.action_package_added
Successfully deleted APK Intent.action_package_removed
Restarting the device Intent.action_reboot
Screen is turned off Intent.action_screen_off
Screen is open intent.action_screen_on
When the system is shut down Intent.action_shutdown
Restarting the device Intent.action_reboot

 

Attention:

When using system broadcasts, you only need to define the relevant action when registering the broadcast receiver.

There is no need to send broadcasts manually, and the system broadcasts automatically when the system has related actions.

③. Orderly broadcast (Ordered broadcast)

The defined broadcasts are received in sequence by the broadcast recipient and are ordered for the broadcast recipient.

Sequence rules for broadcast receivers receiving broadcasts (both static and dynamically registered broadcast receivers)

I. Sort by priority attribute value from large to small;

Ii. The priority attribute is the same, the broadcast with dynamic registration is preferred;

Characteristics:

I. Receiving broadcasts sequentially

II. The broadcast receiver can truncate the broadcast, that is, the broadcast receiver will no longer receive the broadcast;

III. The broadcast receiver can modify the broadcast before receiving the broadcast receiver, then receive the modified broadcast

Specific use:

The use of ordered broadcasts is very similar to ordinary broadcasts, where the difference is only in the way the broadcast is sent:

    

Sendorderedbroadcast (Intent);

④. App in App broadcast (Local broadcast)

Background:

Broadcasts in Android can communicate directly across apps (exported the default value is true for intent-filter cases)

Conflict:

Problems that may occur

Other apps targeted broadcasts that match the current app Intent-filter, resulting in the ongoing app receiving broadcasts and processing;

Other apps register Intent-filter with the current app to receive broadcasts, get broadcast specific information, and security & efficiency issues arise.

Solution:

Use the app in app broadcast (Local broadcast)

App-in-app broadcasts can be understood as a partial broadcast where the sender and receiver of the broadcast belong to an app.

In contrast to global broadcast (general broadcast), app broadcast benefits are: High security & Efficiency

Use 1-Set the global broadcast as a local broadcast

When registering a broadcast, set the exported property to falseso that the broadcast not issued inside the app is not received;

When the broadcast is sent and received, the corresponding permission permission is added for authorization authentication;

When you send a broadcast, you specify the package name of the broadcast receiver, and this broadcast will only be sent to a valid broadcast receiver in the app that matches within the package.

Registration via Intent.setpackage (PackageName)

  

Use 2-Use the encapsulated Localbroadcastmanager class in a way that is almost identical to a global broadcast,

Just register/unregister the broadcast receiver and send the broadcast when the context of the parameter becomes a single instance of Localbroadcastmanager

Attention:

In-app broadcasts sent in Localbroadcastmanager mode can only be registered dynamically via Localbroadcastmanager and cannot be registered statically

    

//registering an in-app broadcast receiver//Step 1: Instantiate the Broadcastreceiver subclass & Intentfilter MbroadcastreceiverMbroadcastreceiver =NewMbroadcastreceiver (); Intentfilter Intentfilter=NewIntentfilter ();//Step 2: Instantiate an instance of LocalbroadcastmanagerLocalbroadcastmanager = Localbroadcastmanager.getinstance ( This);//Step 3: Set the type of the receive broadcastintentfilter.addaction (Android.net.conn.CONNECTIVITY_CHANGE);//Step 4: Invoke Localbroadcastmanager Single Instance Registerreceiver () method for dynamic registrationlocalbroadcastmanager.registerreceiver (Mbroadcastreceiver, intentfilter);//unregister an in-app broadcast receiverLocalbroadcastmanager.unregisterreceiver (mbroadcastreceiver);//send in-app broadcastsIntent Intent =NewIntent (); intent.setaction (broadcast_action); Localbroadcastmanager.sendbroadcast (Intent) ;

  

⑤. Sticky Broadcast (Sticky broadcast)

Since it has been invalidated in Android5.0 & API 21, it is not recommended and is not summarized here.

  


3. Reference Articles

3.1. All the above is from the following website

Https://github.com/LRH1993/android_interview/blob/master/android/basis/broadcastreceiver.md


Android Interview Collection record 2 broadcast receiver detailed

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.