Use of Android development--broadcastreceiver broadcast

Source: Internet
Author: User

to understand the definition of the broadcast and related principles can be seen in this article the most comprehensive analysis in the history of Broadcastreceiver

Simply classify the broadcast, broadcast has two characters, one is the broadcast sender, the other is the broadcast receiver .

Broadcasting is divided into two types, one is global broadcasting, the other is local broadcast

A global broadcast means that a broadcast can be received by any other application, or it can receive broadcasts from any other application.

Local broadcasts are broadcasts that can be delivered only within the application, and broadcast receivers can only receive internal broadcasts and cannot accept broadcasts from other applications

In accordance with the broadcasting mechanism can also be divided into two kinds, standard broadcast and orderly broadcasting

Shuffle broadcasts: All receivers receive events, cannot be intercepted, and cannot be modified.
Orderly broadcast: By priority, a level down pass, the receiver can modify the broadcast data, or can terminate the broadcast event.

Both the receive and send broadcasts are for global broadcasts, and then we'll show you how to use local broadcast

Using a broadcast receiver to receive broadcasts 1. Define a broadcast class

Before we start using the broadcast (that is, receiving the broadcast), we need to define a class that inherits the Broadcastreceiver, and the Onrecevie method of the Onreceieve method is the one we want to process after the broadcast receiver receives the broadcast.

 Public class extends broadcastreceiver {    @Override    publicvoid  onreceive (context context, Intent Intent) {        // write the relevant processing code here, in general, do not add too much logic or take any time-consuming action         //  Because the broadcast receiver is not allowed to open multi-threaded, too long operation will appear error         // so the broadcast receiver is more of an open program other components of the role, such as creating a status bar notification, or start a service     }}

2. Registering the broadcast

There are two ways of registering, one is dynamic registration (using Java code) and the other is static registration (defined in the Androidmainfest file)

Steps to register dynamically:

    1. In the related activity file, new A broadcast class that we just defined
    2. New a Intentfilter class that calls its Setaction method, the action that passes in the relevant value in the argument
    3. Call the Context.registerreceiver method to register, the first parameter of the method is the broadcast class, the second is the Intentfilter class

PrivateMyreceiver Recevier;
PrivateIntentfilter Intentfilter;
@Override
protected voidOnCreate (Bundle savedinstancestate) {
Super.OnCreate (savedinstancestate);
setcontentview (r.layout.activity_main);
recevier = new Myreceiver ();
intentfilter = new Intentfilter ();
intentfilter. Addaction ( "Android.net.conn.CONNECTIVITY_CHANGE");
//when the network changes, the system broadcasts a broadcast that has a value of Android.net.conn.CONNECTIVITY_CHANGE
registerreceiver (recevier, intentfilter);
} /span>

Here we declare the broadcast class and the Intentfilter class as global variables to facilitate subsequent registration and logoff

It is important to note that dynamically registered broadcast receivers must log off and call Unregisterreceiver (recevier) in the OnDestroy method;

Steps for static registration:

    1. Add the receiver's sub-label under the application tag in androidmainfest
    2. registers a broadcast class with the Name property, which is the broadcast class we just defined , and the enabled and exported properties, which enables the broadcast receiver to be enabled. The exported property indicates whether this broadcast receiver is allowed to accept broadcasts other than this program (these two steps can be done automatically via Android studio)
    3. Then add the intent-filter tag under the Receiver tab to set its action
<receiverAndroid:name= ". Myreceiver"android:exported= "true"android:enabled= "true">            <Intent-filter>                <ActionAndroid:name= "Android.intent.action.BOOT_COMPLETED" >
          //A broadcast with a value of Android.intent.action.BOOT_COMPLETED issued by the system broadcast after the boot is complete </Intent-filter></receiver>

PS: Use Android Studio to quickly implement the second step, as follows

Right-click, open New, select Other, and then select Broadcastreceiver

classname is to fill in the previous broadcast class, the default exported and enabled two properties are true, do not tick is false

This function is to generate a broadcast class, and to implement static registration, of course, is to create a broadcast class and static registration of the first two steps, we also need to complete the third step, fill in the Intent-filter tag action value

3. Permissions in the Androidmainfest statement

After registering, we also need to declare the relevant permission in the Androidmainfest, this does not need to say, here put a picture

At the end of the map add a little bit about the difference between dynamic registration and static registration

send a custom broadcast using a broadcast sender

Here is the reception broadcast, which describes how to send a custom broadcast

New Intent ();                Intent.setaction ("Com.example.mymessage");                 // Intent Intent = new Intent ("Com,example.mymessage");                 // It can also be written                like a note. Sendbroadcast (Intent); // send a standard broadcast                Sendorderedbroadcast (Intent,null); // Send an ordered broadcast
          It means sending a broadcast with a value of com.example.mymessage.

After that, we changed the action in Intentfilter to the above com.example.mymessage, but when we tested it we found that we could not show the definition of an ordered broadcast, we needed to set the priority for the broadcast receiver.

If you are using dynamic registration, call Intentfilter directly. SetPriority ();

If it is a static registration, it is the priority attribute in the set Intent-fliter

The priority size setting range is -1000~1000

To truncate the broadcast, simply call Aborybroadcast () in the OnReceive () method, and the broadcast will no longer be passed down

Use local broadcast

Previously referred to as a global broadcast, there is a problem of data security, the use of local broadcast, can only be sent and received in local applications broadcast, can play a role in protecting data security.

Recall that before the dynamic registration of the broadcast is through the Registerreceiver (Receiver,intentfilter) This method to register, in fact, the use of local broadcast is very similar to the previous steps are the same, that is, the method of registering calls in the back is different, Registration is called the Localbroadcastmanager Registerreceiver method, which is called the context of the Registerreceiver method, both parameters are the same

Similarly, we also need to use the Localbrocastmanager.unregisterreceiver () method in the Ondestory method, noting that I didn't define localbroadcastmanager as a global variable in the picture.

Sending broadcasts is also a class

there is a need to say that the use of local broadcast and there is no static registration method, because the static registration is mainly to allow the program to receive the broadcast without starting, and when the local broadcast, our program is started, so, naturally there is no static registration this method

Common action




Use of Android development--broadcastreceiver broadcast

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.