Android-broadcastreceiver Specific explanations

Source: Internet
Author: User

What is broadcast

Broadcast that is broadcast, on Android broadcast is a very important feature. For example, we want to do something after the system boot, monitor the phone's power, monitor the phone's network status and so on. All of these functions need to be broadcast. Of course we are also able to define our own broadcasts.

Define your own broadcasts

Typically implementing a simple self-defined broadcast can be accomplished through, for example, the following several steps:

    • Create a class to inherit android.content.BroadcastReceiver and implement the OnReceive method
    • Register the broadcast in the Androidmanifest.xml
    • Through the context of the registerreceiver and other methods to register the broadcast
    • Call the Sendbroadcast method of the context to send the broadcast, process the broadcast in the OnReceive method
    • Call the context Unregisterreceiver and so on to unregister the broadcast

Let's explain the above steps by code:

1. Create a class to inherit android.content.BroadcastReceiver. and implement the OnReceive method

 PackageCom.mark.broadcastreciver;ImportAndroid.content.BroadcastReceiver;ImportAndroid.content.Context;ImportAndroid.content.Intent;ImportAndroid.util.Log;/** * Creating a self-defined broadcast receiver requires inheriting android.content.BroadcastReceiver, * and implementing the OnReceive method. */ Public  class myreceiver extends broadcastreceiver {    Private Final StaticString TAG = MyReceiver.class.getSimpleName (); Public Myreceiver() {    }/** * This method is called when a broadcast is received * @param Context Context Object * @param Intent call Sendbroadcast (intent) incoming in Tent instances, including action, and other accompanying information * /    @Override     Public void OnReceive(context context, Intent Intent) {//Get msg corresponding dataString msg = Intent.getstringextra ("MSG");//Print MSG dataLOG.I (TAG,"msg ="+ msg);//Print action stringLOG.I (TAG,"action ="+ intent.getaction ()); }}

2. Register the broadcast in the Androidmanifest.xml

<application>    <receiver android:name=".MyReceiver">    </receiver></application>

3. Through the registerreceiver of the context and other methods to register the broadcast
4. Call the Sendbroadcast and other methods of the context to send the broadcast. Handling broadcasts in the OnReceive method
5. Call the context Unregisterreceiver and so on to unregister the broadcast

 PackageCom.mark.broadcastreciver;ImportAndroid.content.BroadcastReceiver;ImportAndroid.content.Intent;ImportAndroid.content.IntentFilter;ImportAndroid.os.Bundle;Importandroid.support.v7.app.AppCompatActivity;ImportAndroid.view.View; Public  class mainactivity extends appcompatactivity {Broadcastreceiver Registerreceiver; Intentfilter Intentfilter;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main);//Create Broadcastreceiver instancesRegisterreceiver =NewMyreceiver ();//Create Intentfilter. Specifies that the action is com.mark.broadcast.receiver, which can be defined by itselfIntentfilter =NewIntentfilter ("Com.mark.broadcast.receiver");//Register broadcast will associate Registerreceiver with Intentfilter,        //Registerreceiver be able to receive a broadcast with action Com.mark.broadcast.receiverRegisterreceiver (Registerreceiver, Intentfilter); Findviewbyid (R.id.btnregister). Setonclicklistener (NewView.onclicklistener () {@Override             Public void OnClick(View v) {//Send broadcast                //Create intent. Specifies that its action is com.mark.broadcast.receiver, and that the action associated with Registerreceiver is consistentIntent Intent =NewIntent ("Com.mark.broadcast.receiver");//Specify the information to be sentIntent.putextra ("MSG","Hello, a new message.");            Sendbroadcast (Intent);    }        }); }@Override    protected void OnDestroy() {Super. OnDestroy ();    Unregisterreceiver (Registerreceiver); }}

Through the above steps we have implemented a self-defined broadcast when we click on the button in the console to see such information as the following:

Geneva- -  -: A:28.591 16882-16882/com. Mark. BroadcastreciverI/myreceiver:msg = Hello, a new message.Geneva- -  -: A:28.591 16882-16882/com. Mark. BroadcastreciverI/myreceiver:action =com. Mark. Broadcast. Receiver
Register broadcast

There are two ways to register a broadcast: static and dynamic.

Static Brochure

The way to do this is to configure the Androidmanifest.xml configuration file to register the broadcast in such a way that it is a resident broadcast, that is to say the application is closed. There is a corresponding event trigger. The program will be executed by the system on its own initiative.

Like what:

<!--in the configuration file Broadcastreceiver can match intent--<receiver android:name=". Myreceiver ">    <intent-filter>        </Action>        <action android:name="Com.mark.broadcast.reveiver"/>        <category android:name="Android.intent.category.DEFAULT"></category>    </intent-filter></receiver>
Dynamic Brochure

The way to do this is through the code. In the Java file. In this way the broadcast of the Register is a very resident broadcast, that is, it will follow the life cycle of the activity, so we need to call the Unregisterreceiver (receiver) method to remove it before the activity ends. Like what:

// 创建BroadcastReceiver实例registerReceiver = new MyReceiver(); // 创建IntentFilter,指定其action为com.mark.broadcast.receiver。这个能够自己定义 intentFilter = new IntentFilter("com.mark.broadcast.receiver"); // 注冊广播将registerReceiver与intentFilter关联。 // registerReceiver能够接收到action为com.mark.broadcast.receiver的广播registerReceiver(registerReceiver, intentFilter);

Note: Suppose we register the activity with the broadcastreceiver, and when the activity is destroyed, we have to voluntarily revoke the register otherwise there will be an exception. Methods such as the following:

@Override    protectedvoidonDestroy() {        super.onDestroy();        unregisterReceiver(registerReceiver);    }
Type of broadcast

There are two types of broadcast: Normal broadcast and ordered broadcast.

Normal broadcasts (normal broadcast)

The Normal broadcasts is completely asynchronous and can be received by all recipients at the same time. Message delivery efficiency is relatively high. However, the disadvantage is that the recipient cannot tell the receiving message that the processing information is passed to the next recipient and cannot stop the message from being propagated. Multiple ordinary broadcasts are set up with the same intentfilter, then the first register receives the broadcast first.

Ordered broadcasts (orderly broadcast)

The recipient of the Ordered broadcasts receives the message according to a certain priority.

For example, the priority of A,b,c is reduced in descending order. Then the message is first passed to a, passed to B, and finally to C.

The precedence level is declared in, and a value of [ -1000,1000] increases the higher the priority. The priority can also be set by Filter.setpriority (10).

In addition, the recipient of the ordered broadcasts can cancel the broadcast propagation by Abortbroadcast (), and can also deposit the processed results into Setresultextras through the Setresultdata and broadcast methods. Passed to the next recipient.

The next recipient then receives the data deposited by the high-priority recipient via Getresultdata () and Getresultextras (true).

Like what:

<receiverandroid:name=". Firstreceiver ">        <intent-filterandroid:priority="999">                <action android:name="Com.mark.broadcast.receiver" />        <category android:name="Android.intent.category.DEFAULT" />    </intent-filter></receiver><receiver android:name=". Myreceiver " >    <intent-filterandroid:priority="+">                <action android:name="Com.mark.broadcast.receiver" />        <category android:name="Android.intent.category.DEFAULT" />    </intent-filter></receiver>

As above two receiver we set the priority to 999, and 1000 respectively. Timely Myreceiver is a post-registration, but its priority is higher than firstreceiver, then Myreceiver will deal with the broadcast first.

Sendorderedbroadcast Sending ordered broadcasts

The Sendorderedbroadcast (Intent, Receiverpermission) method receives two of the parameters. More than the normal broadcast of the way to send a receiverpermission number of parameters. This is a string-type parameter that represents the receiver talent processing that has this permission to receive this broadcast. Assuming null indicates that the recipient is not required to declare the specified permission. Let's take a look at the detailed operation.

First we have to define a permission for ourselves. Like what:

<permission    android:name="com.permissions.MY_BROADCAST_RECEIVER"    android:protectionLevel="normal" />

Then we have this permission if the current program: for example:

<uses-permission android:name="com.permissions.MY_BROADCAST_RECEIVER" />

This allows the current program to have this permission.

We are sending an ordered broadcast that specifies its permission to Com.permissions.MY_BROADCAST_RECEIVER. Note that spelling is not an error, it is better to copy it over.

Send broadcasts such as the following:

// 创建Intent,指定其action为com.mark.broadcast.receiver,与registerReceiver关联的action一致Intent intent = new Intent("com.mark.broadcast.receiver");// 指定要发送的信息intent.putExtra("msg""Hello, a new message.");"com.permissions.MY_BROADCAST_RECEIVER");

This way we send a broadcast and specify its permissions as Com.permissions.MY_BROADCAST_RECEIVER, because the current program already uses this permission. So receiver in the current program is able to receive and process this broadcast. Otherwise, you cannot receive this broadcast. The permissions here reflect the importance that Android attaches to security.

Sendstickybroadcast Sticky Broadcast

The biggest difference between a sticky broadcast and other modes of broadcasting is "async", which means that when a sticky broadcast is sent out, it can be processed without receiver. But this broadcast will still exist, if after a period of time after the receiver register the broadcast, then this receiver can still handle the broadcast. But careful friends can see that Sendstickybroadcast's range of overloaded methods does not have the Receiverpermission parameters mentioned above, which will also lead to a security problem with sticky broadcasts.

So the Sendstickybroadcast method on API level 21 is marked as deprecated. That is, we do not recommend that we use sticky broadcasts. There are many flaws in the security and other aspects of sticky broadcasting. Here we are not in the main discussion.

Summarize

Here we have a brief summary of the broadcast and broadcast receivers and some considerations when using them.

1. The method of sending the broadcast is the method in Contextwrapper. Activity and service are contextwrapper subclasses, so they can send and register broadcasts.
The 2.onReceive method does not take a time-consuming action, or it can cause the ANR
3. According to the actual development needs. Add permissions to a broadcast whenever possible
4. Avoid using sticky broadcasts whenever possible
5. The priority of ordered broadcast is "1000 ~ 1000", the larger the value. The higher the priority level

The above descriptive narrative and some viewpoints may not be positive solutions, only for reference, welcome to correct, criticize.

Android-broadcastreceiver Specific explanations

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.