Android four components of the Broadcastreceiver

Source: Internet
Author: User


Broadcastreceiver: Broadcast receiver, is a component that focuses on receiving broadcast notification information and making corresponding processing

1. The application can have any number of broadcast receivers to respond to all of the notification information that it is interested in. All receivers inherit from the Broadcastreceiver base class

2, the broadcast receiver does not have a user interface. However, they can initiate an activity to respond to the information they receive, or use Notificationmanager to notify the user. Notifications can be used in a variety of ways to attract users ' attention-flashing back lights, shaking, playing sounds, and more. In general, a persistent icon is placed on the status bar, and the user can open it and get the message

3. There are two types of broadcast events in Android:

1) System broadcast events, such as: action_boot_completed (triggered after system boot is complete), action_time_changed (triggered when system time changes), Action_battery_ Low (when the battery is down) and so on 2) our custom broadcast event.

4, the broadcast time flow:

1) Registration of broadcast events: There are two ways to register,

One is the static registration, is defined in the Androidmanifest.xml file, the registered broadcast receiver must inherit the Broadcastreceiver; statically registered broadcasts, at the end of the program, will still listen to the matching action

The other is dynamic registration, which is registered in the program using Context.registerreceiver, and the registered broadcast receiver is equivalent to an anonymous class. Both of these methods require intentfilter.

2) Send broadcast event: Send by Context.sendbroadcast, by intent to pass the action that is used when registering.

3) Receive broadcast event: When the broadcast being sent is heard by the receiver, its onreceive () method is called, and the intent object containing the message is passed to it.

Note: The code in OnReceive does not take more than 5s to execute, otherwise Android will eject the timeout dialog.


5. Broadcast Life cycle

A Broadcastreceiver object is only valid if it is called OnReceive (Context, Intent).

When returned from this function, the object is invalid, ending the life cycle


The following code to achieve the broadcast registration and send, receive broadcast

First define a broadcast receiver, create a class (Myreceiver) to inherit Broadcastreceiver, implement its onreceive () method

Package com. Broadcastreceive.archer;import Android.content.broadcastreceiver;import Android.content.context;import Android.content.intent;import Android.widget.toast;public class Myreceiver extends Broadcastreceiver {@ overridepublic void OnReceive (context context, Intent Intent) {String action = intent.getaction (); if (Action.equals (" Com.action.text ")) {String msg = Intent.getstringextra (" msg "); Toast.maketext (Context, MSG, toast.length_short). Show ();}}

A broadcast receiver can receive messages from all directions, so you can do different things in onreceive by judging the action received by intent.getaction, the action of the system or our custom action


Then you need to register for the broadcast, there are two ways to register

Static Registration :

 <application        android:allowbackup= "true"          android:icon= "@drawable/ic_launcher"          android:label= "@string/app_name"         android:theme= "@ Style/apptheme " >        <activity             android:name= ". Mainactivity "            android:label=" @string/ App_name " >            <intent-filter >                <action  android:name= "Android.intent.action.MAIN"  />                 <category android: Name= "Android.intent.category.LAUNCHER"  />             </intent-filter>        </activity>         <!--  static registered broadcast  -->         <receiver android:name= ". Myreceiver " >            <intent-filter >                <action  android:name= "Com.action.text"  /> //a custom action for a string              </intent-filter>        < /receiver>    </application>


Dynamic registration:

Private Myreceiver receiver = new Myreceiver (); Instantiate a broadcast sink
Dynamic registration Broadcast Intentfilter filter = new Intentfilter ();    Filter.addaction ("Com.action.text"); Registerreceiver (receiver, filter);

A broadcastreceiver (dynamic registration) is registered in the activity or service.

When the activity or service is destroyed, the system will report an exception if it is not de-registered.

We can cancel the registration in OnStop () or OnDestroy ()

@Override protected void OnDestroy () {Super.ondestroy ();  Unregisterreceiver (receiver); }


Send broadcast

Intent Intent = new Intent () intent.setaction ("Com.action.text");//Set Actionintent.putextra for broadcast time ("MSG", "Receive broadcast success"); Sendbroadcast (Intent);

If we need to transmit the data while sending the broadcast, we can pass it through the intent.


Shuffle broadcast:

When a broadcast is issued, all broadcast receivers that have registered the action receive the broadcast event, and do so in an order that has no effect on each other; no registration will be received


Orderly broadcast

When there is more than one broadcast receiver registering this action, and we need to give them the order of reception, this is the time to use an orderly broadcast.

Ordered broadcast is special, it is sent to the higher priority receiver at a time, and then by the high priority receiver and then propagated to the lower priority receiver, high priority recipients have the ability to terminate the broadcast.

Define two broadcast receivers first, firstreceiver to higher priority receivers

public class firstreceiver extends broadcastreceiver  {@Overridepublic  void onreceive (context context, intent intent)  {String  action = intent.getaction ();if  (action.equals ("Action"))  {string msg =  intent.getstringextra ("msg"); Toast.maketext (Context, msg, toast.length_short). Show (); Bundle bundle = new bundle (); Bundle.putstring ("MSG",  "messages from the first broadcast receiver"); Setresultextras (bundle);  //sets a bundle object to the result set object, passing to the next recipient there}}} 
public class Secondreceiver extends Broadcastreceiver {@Overridepublic void OnReceive (context context, Intent Intent) {St Ring action = Intent.getaction (), if (Action.equals ("action")) {String msg = Getresultextras (True). GetString ("msg"); Use Getresultextras to obtain processed information Toast.maketext (context, MSG, toast.length_short). Show ();}}

When registering a broadcast, you need to set the priority android:priority

        <receiver              android:name= ". Firstreceiver ">            <intent-filter                  android: Priority= ">  //" The range of this attribute is 1000 to 1000, the greater the value, the higher the priority                  <action android:name= "Com.action.text"/>             </intent-filter>         </receiver> 
        <receiver              android:name= ". Firstreceiver ">            <intent-filter                  android: Priority= ">  //" The range of this attribute is 1000 to 1000, the greater the value, the higher the priority                  <action android:name= "Com.action.text"/>             </intent-filter>         </receiver> 
<receiver android:name= ". Secondreceiver "> <intent-filter android:priority=" 999 "> <action Android Oid:name= "Com.action.text"/> </intent-filter> </receiver>

Send an ordered broadcast

Intent Intent = new Intent ();    Intent.setaction ("Com.action.text");      Intent.putextra ("msg", "Message from activity"); Sendorderedbroadcast (Intent, "Scott.permission.MYBROADCAST");
When you use Send ordered broadcasts, the second parameter is a custom permission, NULL indicates that you do not need to declare the specified permission, and is not empty, which means that you need to declare the specified permission and declare the following permissions <permission android:protectionlevel= "Normal" Android:name= "Scott.permission.MYBROADCAST"/> <uses-permission android:name= "Scott.permission.MYBROADCAS T "/>

When a broadcast is issued, the receiver with the highest priority receives the broadcast, which is then passed to the lower-priority receiver in turn

If we need to terminate the broadcast in one of the receivers, we can call the following code in Onreceiver ()

Abortbroadcast ();


Broadcastreceiver of Android four components

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.