Broadcastreceiver detailed analysis of Android four components

Source: Internet
Author: User
Tags stub

What is Broadcastreceiver? as one of the four components of Android, Broadcastreceiver also plays an important role in the development of the Android program, broadcasting is very similar to the radio in our real life. The radio station sends its content on a channel, so that anyone who listens to the channel will receive it. In Android, the broadcast is also divided into two roles: broadcast sender , broadcast receiver .


Broadcastreceiver's application scenario1. In an application, our activity and service communication needs to use the broadcast as an intermediary, such as service in the background to download tasks, when the download is successful, need to notify the activity, this time can be used to broadcast.
2. In Android, sometimes two apps need to communicate, such as when you click on a button in another app to notify the launch of another app, this time you need to click on the button to send a broadcast, and the other app is the broadcast receiver.
3. Another scenario is a broadcast by the system, your app acts as a broadcast receiver, for example, you need to make a prompt in your app when your phone is disconnected, and let your app receive a broadcast from the system when the phone starts: "The phone is up!" "And then your app will do it right away, such as booting from the boot, and so on.


Broadcast the biggest feature is: the sender and the receiver is decoupled, that is, although the sender sent a broadcast, but it does not matter whether the receiver received it or not, or the receiving party to do after the broadcast, and the receiver only need to register the broadcast, it will receive the same type of broadcast message when the corresponding. And the broadcast can be a sender, multiple receivers.




How do I use the broadcast? As mentioned earlier, broadcast is required to register, that is, the need to register a broadcast receiver, in Android, broadcast registration is divided into two ways:
1. Statically registered broadcast "register Broadcastreceiver in Androidmanifest.xml"
2. Dynamic registration Broadcast "Register Broadcastreceiver by Code"


To register a custom broadcast in a static manner

1. Send a broadcast, where the activity is the example of sending a broadcast in the activity's OnCreate

public class Mainactivity extends Activity {@Overrideprotected void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); Intent Intent = new Intent ();//The Sign of the broadcast intent.setaction ("Broadcast_test");//Carry Data Intent.putextra ("MSG", "This is a custom static broadcast message");//Send Broadcast sendbroadcast (intent);}}

The key is SendbroadcastThis method, which sends the broadcast intent, can carry the data through intent
Attention: setactionRepresents the intent setting of the previous Action, which is equivalent to a flag of this broadcast, only the broadcast recipient that matches this flag will receive the message.


2. Create a broadcast receiver, a new class inherits from Broadcastreceiver, implementing the OnReceive method in it

public class Myreceiver extends broadcastreceiver{@Overridepublic void onreceive (context context, Intent Intent) {//TODO Auto-generated method stub//Gets the data in the broadcast string msg = Intent.getstringextra ("msg");//Analog Response Toast.maketext (context, MSG, 1000 ). Show ();}}

In the OnReceive method, a variety of response operations are made after receiving a broadcast, and the OnReceive method has two parameters: the context represents the place where the broadcast was sent, and the intent that was carried by the broadcast. This is the intent that was sent in the sendbroadcast in the previous step. So it's natural to get the data from it.


3. Register our defined broadcasts in the Androidmanifest.xml


Note: The name of the action tag must match the action set by intent in the first step to receive the broadcast



Run




dynamically registering custom broadcasts1. Send a broadcast, where the activity is the example of sending a broadcast in the activity's OnCreate

public class Mainactivity extends Activity {@Overrideprotected void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main);//Intent Filters and Actionintentfilter filter for dynamic Register receiver = New Intentfilter (); Filter.addaction ("broadcast_test"); Registerreceiver (new Myreceiver (), filter); Intent Intent = new Intent ();//The Intent.setaction ("Broadcast_test") of this broadcast;//Carry Data Intent.putextra ("MSG", "This is a custom dynamic broadcast message");// Send broadcast sendbroadcast (intent);}}


As you can see, the difference between this and the static is that there is more intentfileter generation and receiver Registration, which is equivalent to registering receiver in XML into code for registration .




2. A broadcast receiver is also required, and a new class inherits from the Broadcastreceiver to implement the OnReceive method

public class Myreceiver extends broadcastreceiver{@Overridepublic void onreceive (context context, Intent Intent) {//TODO Auto-generated method stub//Gets the data in the broadcast string msg = Intent.getstringextra ("msg");//Analog Response Toast.maketext (context, MSG, 1000 ). Show ();}}



Run




The above demonstrates how to send a custom broadcast statically and dynamically, following the Mobile flight mode switch to demonstrate how to receive static and dynamic broadcasts from the system

static receive system broadcast 1. Create a new broadcast receiver to receive a specific system broadcast

public class Myreceiver extends broadcastreceiver{//is used as a flag to determine whether to turn on or off private static int count = 0;//If the flight mode state changes the broadcast, Just perform operation @overridepublic void OnReceive (context context, Intent Intent) {//TODO auto-generated method stub//Each change in flight status, Count is +1count++;switch (count%2) {//If the remainder is 1, indicating that count is odd, that is, Operation---> Open flight mode Case 1:toast.maketext (context, "Turn on airplane mode", (). Show (); break;//if the remainder is 0, the count is an even number, that is, the operation---> Close airplane mode case 0:toast.maketext (context, "Off airplane Mode", "+"). Show (); Break;}}}




2. Register the broadcast recipient in the Androidmanifest

<receiver android:name= ". Myreceiver "><intent-filter>                <action android:name=" Android.intent.action.AIRPLANE_MODE "/>        </intent-filter></receiver>


Note that the action here is Android.intent.action.AIRPLANE_MODE, which is provided by the system when the mobile phone flight status changes when the broadcast, This broadcast is only received in OnReceive because the Myreceiver is registered to receive the specified system broadcast here.



dynamic receive system broadcast 1. Create a new broadcast receiver that is basically consistent with the static

public class Myreceiver extends broadcastreceiver{//is used as a flag to determine whether to turn on or off private static int count = 0;//If the flight mode state changes the broadcast, Just perform operation @overridepublic void OnReceive (context context, Intent Intent) {//TODO auto-generated method stub//Each change in flight status, Count is +1count++;switch (count%2) {//If the remainder is 1, indicating that count is odd, that is, Operation---> Open flight mode Case 1:toast.maketext (context, "Turn on airplane mode", (). Show (); break;//if the remainder is 0, the count is an even number, that is, the operation---> Close airplane mode case 0:toast.maketext (context, "Off airplane Mode", "+"). Show (); Break;}}}




2. Register it in the activity

public class Mainactivity extends Activity {@Overrideprotected void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); Intentfilter filter = new Intentfilter ();// This adds the ACTION of the flight mode change to the filter filter.addaction (intent.action_airplane_mode_changed); Registerreceiver (new Myreceiver (), filter);}}



Run




How do I unregister a broadcast?

In the above example of dynamically registering a custom broadcast , if you try to kill the current application, you will find that Logcat reported the following error:



As can be seen from the error message, it is because we are dynamically registered custom broadcasts, so when the activity is destroyed, the broadcast recipient will no longer receive the corresponding broadcast, the system requires that the broadcast must be unregistered
The workaround is simple, just call unregisterreceiver (myreceiver) in the OnDestroy method of the activity; You can unregister the broadcast when activity exits:

@Overrideprotected void OnDestroy () {//TODO auto-generated method Stubsuper.ondestroy (); Unregisterreceiver ( Myreceiver);}



Orderly BroadcastThe broadcast shown above is sent out through Sendbroadcast, is a disorderly broadcast, and sometimes there are multiple broadcast receivers, if we need to set them a certain priority, we need to pass sendorderedbroadcast () To send an ordered broadcast


The following shows how to use ordered broadcasts by customizing three broadcast receivers and a broadcast sender:
1. Creation of three broadcast receivers

Orderly broadcast
The broadcast shown above is sent out through Sendbroadcast, is a disorderly broadcast, and sometimes there are multiple broadcast receivers, if we need to set them a certain priority, we need to send an orderly broadcast via Sendorderedbroadcast ()


The following shows how to use ordered broadcasts by customizing three broadcast receivers and a broadcast sender:
1. Creation of three broadcast receivers

Myfirstreceiver.java:

public class Myfirstreceiver extends broadcastreceiver{@Overridepublic void onreceive (context context, Intent Intent) {/ /TODO auto-generated method stubstring msg = Intent.getstringextra ("msg"); LOG.D ("Myfirstreceiver", msg);//transmits the data to the next broadcast receiver Setresultdata ("This is the Second msg from Myfirstreceiver");}}



Mysecondreceiver.java:

public class Mysecondreceiver extends broadcastreceiver{@Overridepublic void onreceive (context context, Intent Intent) { TODO auto-generated method stub//Gets the data transmitted by the last broadcast receiver string msg = Getresultdata (); LOG.D ("Mysecondreceiver", msg);//transmits the data to the next broadcast receiver Setresultdata ("This is the third msg from Mysecondreceiver");}}



Mythirdreceiver.java:

public class Mythirdreceiver extends broadcastreceiver{@Overridepublic void onreceive (context context, Intent Intent) {/ /TODO auto-generated method stub//Gets the data transmitted by the last broadcast receiver string msg = Getresultdata (); LOG.D ("Mythirdreceiver", msg);}}


2. Register three broadcast receivers in the Androidmanifest.xml:

<receiver            android:name= ". Myfirstreceiver ">           <intent-filter android:priority=" >                <action android:name= " Orderbroadcast "/>           </intent-filter></receiver>        <receiver            android:name=". Mysecondreceiver ">           <intent-filter android:priority=" >                <action android:name= " Orderbroadcast "/>           </intent-filter></receiver>        <receiver            android:name=". Mythirdreceiver ">           <intent-filter android:priority=" >                <action android:name= " Orderbroadcast "/>           </intent-filter></receiver>


Notice that each recipient adds a property: priority, whichrepresents the precedence in an ordered broadcast, the higher the value, the higher the priority, and the highest priority will be the first to receive the broadcast and intercept it when the broadcast is issued. Then it will continue to pass down to the lower priority level.


3. Send an ordered broadcast

public class Mainactivity extends Activity {@Overrideprotected void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); Intent Intent = new Intent ("Orderbroadcast"); Intent.putextra ("msg", "This was the first msg from Activity"); Sendorderedbroadcast (intent, NULL);}}



Run to view Logcat print results:




Local broadcast the above ordered and unordered broadcasts are all global broadcasts, that is, when the broadcast is issued, the entire system has the opportunity to receive the broadcast, but sometimes for security reasons, Android also provides partial broadcasts, which are only The broadcast receiver within the same app will receive it, and other apps won't receive it.


use of partial broadcasts:

public class Mainactivity extends Activity {private Myreceiver receiver = new Myreceiver (); @Overrideprotected void Oncreat E (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Localbroadcastmanager Manager = Localbroadcastmanager.getinstance (this); Intentfilter filter = new Intentfilter (); Filter.addaction ("Broadcasttest");//register local broadcast Manager.registerreceiver (receiver, filter); Intent Intent = new Intent (); Intent.setaction ("Broadcasttest");//Send Broadcast manager.sendbroadcast (intent);}}



the life cycle of BroadcastreceiverThe "trilogy" calls the broadcast---> Executes onreceive ()---The >onreceive method return and ends the broadcast






the point of attention Android Specifies that Broadcastreceiver cannot handle complex long-running logical operations, and if the OnReceive method cannot be completed within 10s, the system will treat it as unresponsive and may report a ANR error. These time-consuming operations can be put into service to open up sub-threads to execute.


At this point, for broadcastreceiver in the use of Android has a basic understanding, I will be in the future blog post with the actual demo to demonstrate the application of radio in development! Collation is not easy, if you think this article is helpful to you, please point a praise, if there are deficiencies, also hope to point out, joint discussion.


Broadcastreceiver detailed analysis of Android four components

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.