Drill down into Android broadcastreceiver two ways to register (static and dynamic) detailed _android

Source: Internet
Author: User

Today we are going to discuss the next Andong Broadcastreceiver component and the two ways to register it in a detailed analysis.

Broadcastreceiver is the "broadcast receiver" meaning, as the name suggests, it is used to receive from the system and applications in the broadcast. In the Android system, broadcast in all aspects, for example, when the system is completed after a broadcast, received this broadcast will be able to achieve the function of the boot service; When the network state changes, the system will produce a broadcast, receive this broadcast can prompt and save data and so on operation When the battery power changes, the system will produce a broadcast, receive this broadcast can be in low power to tell the user in time to save progress and so on. The broadcast mechanism in Android is designed so well that a lot of things would have to be done by the developers themselves, and now it's just waiting for the broadcast to tell itself, which greatly reduces the development effort and the development cycle. And as an application developer, you need to learn to master the Android system provides a development tool, that is broadcastreceiver.

Before we analyze the two ways to create a broadcastreceiver, we'll list the outline of this analysis:

(1) The static and dynamic registration methods for the concept of the description and demonstration of the implementation steps

(2) A brief description of the types of two broadcastreceiver (preparation for the comparison of subsequent registration methods)

(3) Comparison of two registration methods under the default broadcast type setting priority and no priority

(4) Comparison of two kinds of registration methods under ordered broadcast type

(5) Comparison of the two registration methods by receiving a call broadcast, at the time the program (activity) is run and when the operation is terminated

(6) Summarize the characteristics of two ways

The first step: static and dynamic registration methods basic concepts and implementation steps

Building intent, using the Sendbroadcast method to emit a broadcast defines a broadcast receiver, which inherits Broadcastreceiver and overrides the OnReceive () method to register the broadcast receiver in response to the event. We can register in code (dynamic registration), or register (static registration) in the Androidmanifest.xml configuration file.

Dynamic registration:

The effect of the following figure:

Here does not demonstrate click on the button layout implementation, Mainactivity.java implementation code as follows:

Import Android.content.BroadcastReceiver;
Import Android.content.Context;
Import android.content.Intent;
Import Android.content.IntentFilter;
Import android.support.v7.app.AppCompatActivity;
Import Android.os.Bundle;
Import android.view.Gravity;
Import Android.view.View;

Import Android.widget.Toast;
  public class Mainactivity extends appcompatactivity {dynamicreceiver dynamicreceiver;
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (R.layout.activity_main);
    Instantiate Intentfilter Object Intentfilter filter = new Intentfilter ();
    Filter.addaction ("Panhouye");
    Dynamicreceiver = new Dynamicreceiver ();
  Registered broadcast Reception registerreceiver (Dynamicreceiver,filter);
    //button click event public void Send2 (View v) {Intent Intent = new Intent ();
    Intent.setaction ("Panhouye");
    Intent.putextra ("Sele", "Pan hou Ye");
  Sendbroadcast (Intent); /* Dynamic registration needs to remove the broadcast receiver in the acticity lifecycle OnPause through the *unregisterreceiver () method, * Optimize memory space to avoid memory overflow/@Override protected void OnPause () {super.onpause ();
  Unregisterreceiver (New Myreceiver ()); ///Build dynamic Broadcast receiver class Dynamicreceiver extends broadcastreceiver{@Override public void OnR by inheriting broadcastreceiver Eceive (context context, Intent Intent) {//Validated by Toast received broadcast Toast T = Toast.maketext (context, "Dynamic broadcast:" + INTENT.GETSTR
      Ingextra ("Sele"), Toast.length_short);
    T.setgravity (gravity.top,0,0)//Convenient recording screen, the toast set at the top of the screen t.show ();

 }
  }
}

Create the method code to do a detailed comment, there is no clear place please leave a message to discuss.

Static registration:

The effect is as follows:

Static registration to establish the first step, new Broadcastreceiver, see the following figure:

From the above steps, generate the Myreceiver.java file:

Import Android.content.BroadcastReceiver;
Import Android.content.Context;
Import android.content.Intent;
Import android.view.Gravity;
Import Android.widget.Toast;

public class Myreceiver extends Broadcastreceiver {public
  myreceiver () {
  }
  @Override public
  Void OnReceive (context, Intent Intent) {
    Toast t = toast.maketext (context, static broadcast: +intent.getstringextra ("info "), toast.length_short);
    T.setgravity (gravity.top,0,0);
    T.show ();
  }


While generating Myreceiver.java, modify the code in the Androidmainfest.xml configuration file:

<?xml version= "1.0" encoding= "Utf-8"?> <manifest xmlns:android= "http://schemas.android.com/apk/res/" Android "package=" Com.example.administrator.day19 "> <uses-permission android:name=" Android.permission.PROCESS_OUTGOING_CALLS "/> <application android:allowbackup=" true "android:icon=" @mipmap
    /ic_launcher "android:label=" @string/app_name "android:supportsrtl= true" android:theme= "@style/apptheme" > <activity android:name= ".

        Mainactivity "> <intent-filter> <action android:name=" Android.intent.action.MAIN "/>
    <category android:name= "Android.intent.category.LAUNCHER"/> </intent-filter> </activity> Generated receiver configuration file <receiver android:name= ".
        Myreceiver "android:enabled=" true "android:exported=" true "> <intent-filter>//Custom action <action android:name= "Mly"/> </intent-filter> </receiver> </aPplication> </manifest>

 

Finally, add the button click event in the Mainactivity.java file, as follows:

Import Android.content.BroadcastReceiver;
Import Android.content.Context;
Import android.content.Intent;
Import Android.content.IntentFilter;
Import android.support.v7.app.AppCompatActivity;
Import Android.os.Bundle;
Import android.view.Gravity;
Import Android.view.View;
Import Android.widget.Toast;

public class Mainactivity extends Appcompatactivity {
  dynamicreceiver dynamicreceiver;
  @Override
  protected void onCreate (Bundle savedinstancestate) {
    super.oncreate (savedinstancestate);
    Setcontentview (R.layout.activity_main);
  }
  Static broadcast click Public
  void Send (View v) {
    Intent Intent = new Intent ();
    Intent.setaction ("Mly");
    Intent.putextra ("info", "Panhouye");
    Sendbroadcast (intent);
  }


At this point, the implementation of the two types of registration code demo finished, welcome to explore.

Second step: For the convenience of subsequent analysis, here are two common types of broadcastreceiver inserted

(1) normalbroadcasts: Default broadcast

Send a default broadcast using the Context.sendbroadcast () method, normal broadcasts are completely asynchronous for multiple receivers, and usually each receiver can receive a broadcast without waiting, and the receiver will not have an impact on each other. For this broadcast, the receiver cannot terminate the broadcast, that is, it cannot prevent other receivers from receiving the action.

(2) Orderedbroadcasts: Ordered broadcast

Send an ordered broadcast using the Context.sendorderedbroadcast () method, the ordered broadcast is special, it is sent to the higher priority receiver at a time, and then the priority receiver is then propagated to the lower priority receiver, who has the ability to terminate the broadcast.

Send ordered broadcast: Sendorderedbroadcast ()

Use the Android:priority property in <intent-filter> in the Register broadcast. This property ranges from 1000 to 1000, and the larger the number, the higher the priority. Use the Setresultextras method in a broadcast sink to set a bundle object as a result set object and pass it to the next recipient, so that the lower-priority receiver can obtain the latest collection of processed information with Getresuttextras. When an ordered broadcast is sent using the Sendorderedbroadcast method, a permission parameter is required, and if NULL indicates that the recipient is not required to declare the specified permission, or if it is not NULL, to declare the specified permission to receive the broadcast. This is done from a security perspective, such as the system of the text message is ordered broadcast form, an application may have to intercept the spam message function, when the message arrives it can first receive the SMS broadcast, if necessary, terminate the broadcast transmission, such software must declare the permission to receive the message.

Step three: Comparison of two ways of registering under the default broadcast

(1) The two registration methods are not set priority

Here the dynamic and static two registered broadcast triggers are focused on a single button, showing the effect as follows (without setting the priority, dynamic after static):

The button layout file is also not shown here, and static registration involves Androidmainfest.xml and Myreceiver.java files. Direct display of Mainacticity.java implementation code:

Import Android.content.BroadcastReceiver;
Import Android.content.Context;
Import android.content.Intent;
Import Android.content.IntentFilter;
Import android.support.v7.app.AppCompatActivity;
Import Android.os.Bundle;
Import android.view.Gravity;
Import Android.view.View;

Import Android.widget.Toast;
  public class Mainactivity extends appcompatactivity {dynamicreceiver dynamicreceiver;
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (R.layout.activity_main);
    Intentfilter filter = new Intentfilter ();
    Filter.addaction ("Panhouye");
    Dynamicreceiver = new Dynamicreceiver ();
  Registerreceiver (Dynamicreceiver,filter);
    }//static broadcast click public void Send (View v) {Intent Intent = new Intent ();
    Set the same action as the dynamic, which is convenient to trigger both static and dynamic intent.setaction ("Panhouye");
    Intent.putextra ("info", "Pan hou Ye");
    Sendbroadcast (intent);//default broadcast} @Override protected void OnPause () {super.onpause (); UnreGisterreceiver (New Myreceiver ()); Class Dynamicreceiver extends broadcastreceiver{@Override public void onreceive (context context, Intent Inten
      T) {Toast t = Toast.maketext (context, "Dynamic broadcast:" + Intent.getstringextra ("info"), toast.length_short);
      T.setgravity (gravity.top,0,0);
    T.show ();

 }
  }
}

(2) Set the dynamic priority to the lowest-1000, the static priority is set to the highest 1000

The display effect is as follows (the dynamic is still received before the static):

The dynamic priority setting in Mainactivity is as follows:

protected void OnCreate (Bundle savedinstancestate) {
    super.oncreate (savedinstancestate);
    Setcontentview (r.layout.activity_main);
    Intentfilter filter = new Intentfilter ();
    Filter.addaction ("Panhouye");
    Filter.setpriority (-1000);//Set dynamic priority
    Dynamicreceiver = new Dynamicreceiver ();
    Registerreceiver (Dynamicreceiver,filter);
  }

The static priority setting in Androidmainfest.xml is as follows:

<receiver
  android:name= ". Myreceiver "
  android:enabled=" true "
  android:exported=" true ">
  //Set static priority
  <intent-filter android:priority= "1000" >
     <action android:name= "Panhouye"/>
  </intent-filter>
</ Receiver>

Fourth step: Comparison of two kinds of registration methods in ordered broadcasting

Static broadcast 1 (priority 200), static broadcast 2 (priority 300), static broadcast 3 (priority 400), static broadcast priority (-100), dynamic broadcast priority is 0. The display effect is as follows:

The order of occurrence is determined by priority, from high to low, respectively, static 3-Static 2-static 1-dynamic-static. (Refer to the previous code here)

Step Fifth: Accept the call broadcast, compare the two ways of registering when the program is running and ending running

This comparison is done by comparing the two registration methods in Mainactivity.java, where the activity lifecycle is inserted to detect log analysis.

The Androidmainfest.xml configuration file code is as follows:

<manifest xmlns:android= "http://schemas.android.com/apk/res/android" package= " com.example.administrator.test19 ">//Add call permission <uses-permission android:name=" Android.permission.PROCESS_ Outgoing_calls "/> <application android:allowbackup=" true "android:icon=" @mipmap/ic_launcher "android:l Abel= "@string/app_name" android:supportsrtl= "true" android:theme= "@style/apptheme" > <activity android:na Me= ".

        Mainactivity "> <intent-filter> <action android:name=" Android.intent.action.MAIN "/>
    <category android:name= "Android.intent.category.LAUNCHER"/> </intent-filter> </activity> <receiver android:name= ". Staticreceiver "android:enabled=" true "android:exported=" true "> <intent-filter>/Set Call
    Corresponding action <action android:name= "Android.intent.action.NEW_OUTGOING_CALL"/> </intent-filter> </receiver> </applicaTion> </manifest>

 

Implementing code in Mainactivity.java:

Import Android.content.BroadcastReceiver;
Import Android.content.Context;
Import android.content.Intent;
Import Android.content.IntentFilter;
Import android.support.v7.app.AppCompatActivity;
Import Android.os.Bundle;

Import Android.util.Log; public class Mainactivity extends Appcompatactivity {dynamicreceiver dynamicreceiver;//declares dynamic enrollment broadcast receive @Override protect
    Ed void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (R.layout.activity_main);
    Intentfilter filter = new Intentfilter ();
    Filter.addaction ("Android.intent.action.NEW_OUTGOING_CALL");
    Dynamicreceiver = new Dynamicreceiver ();
    Registerreceiver (Dynamicreceiver,filter);
  LOG.I ("Tag", "activity-oncreate");
    } @Override protected void OnStart () {Super.onstart ();
  LOG.I ("Tag", "Activity-onstart");
    } @Override protected void Onresume () {super.onresume ();
  LOG.I ("Tag", "Activity-onresume"); } @Override protected void OnPause () {super.OnPause ();
  LOG.I ("Tag", "Activity-onpause");
    } @Override protected void OnStop () {super.onpause ();
  LOG.I ("Tag", "activity-onstop");
    } @Override protected void OnDestroy () {Super.ondestroy ();
    LOG.I ("Tag", "Activity-ondestroy");
  Unregisterreceiver (Dynamicreceiver); Class Dynamicreceiver extends broadcastreceiver{@Override public void onreceive (context context, Intent Inten
    T) {log.i ("Tag", "Dynamic registration broadcast received you are calling" +getresultdata ());

 }
  }
}

Implementation code in Staticreceiver.java:

Import Android.content.BroadcastReceiver;
Import Android.content.Context;
Import android.content.Intent;
Import Android.util.Log;
public class Staticreceiver extends Broadcastreceiver {public
  staticreceiver () {
  }
  @Override
  public void OnReceive (Context context, Intent Intent) {
    log.i ("Tag", "Static registration broadcast receives the call you are dialing" +getresultdata ());
  }

(1) When the activity is not withdrawn, call the log as follows:

The log is aware that in the case of an activity that has not exited, both methods can be accepted for broadcast.

(2) When exiting the activity, make a call, log as follows:

When exiting a program (activity), only static registration can be accepted to the broadcast.

Sixth step: Summarize the characteristics of two kinds of registration methods

There are two forms of broadcast receiver registration: Static registration and dynamic registration.

The difference between the two and their received broadcasts:

(1) Dynamic registration broadcasts are not resident-type broadcasts, that is, broadcasts follow the life cycle of activity. Notice that the broadcast receiver is removed before the activity ends.

Static registration is a resident type, meaning that when an application shuts down, the program is automatically run by the system call if there is information broadcast.

(2) When broadcast for ordered broadcast: Priority high first receive (no static and dynamic). Same priority broadcast receiver, Dynamic takes precedence over static

(3) The same priority of the same broadcast receiver, static: First scan priority after the scan, dynamic: First registered priority after the registration.

(4) When broadcasting is the default broadcast: The priority is ignored, and the dynamic broadcast receiver takes precedence over the static broadcast receiver. The same priority of the same broadcast receiver, static: First scan priority after the scan, dynamic: First registered priority in the back of the book.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.