Detailed Android Broadcastreceiver Components _android

Source: Internet
Author: User

Broadcastreceiver means "broadcast receiver", which is used to receive broadcasts from the system and applications.

In Android, broadcast is a widely used mechanism for transmitting information between applications. And Broadcastreceiver is a kind of component that filters the sent broadcast to accept and respond.

The following is a detailed description of how to send broadcast and use Broadcastreceiver to filter the received process:

(1) First, in the place where the information needs to be sent, load the information to be sent and the information used for filtering (such as action, Category) into a intent object, and then by calling Sendorderbroadcast () or Sendstickybroadcast () method, the intent object is sent out on a broadcast basis.

(2) When intent is sent, all registered broadcastreceiver check whether the intentfilter of the registration match the intent sent, and if the match is invoked Broadcastreceiver OnReceive ( Method So when we define a broadcastreceiver, we need to implement the OnReceive () method.

There are two ways of registering broadcastreceiver

Static registration: Register with the label life in Androidmanifest.xml and set the filter in the label.

<receiver android:name= "Myrecevice" >  //Inheritance Broadcastreceiver, overriding Onreceiver method
<intent-filter>  
<action android:name= "com.lc.test"/>//Use filter to receive specified action broadcast  </intent-filter>
</receiver>    

Dynamic registration: use Intentfilter to dynamically register a broadcast in code

Intentfilter intentfilter = new Intentfilter ();
 Specifies the action for the Broadcastreceiver to receive a broadcast
intentfilter.addaction (String) with the action,  
Registerreceiver ( Broadcastreceiver,intentfilter);

Also noteworthy is that when we use dynamic registration, when this activity or service is destroyed if not to unregister, the system will report an exception, prompted us whether we forgot to cancel the registration, so we need to OnDestroy () method to cancel registration, General: Register in OnStart, OnStop cancel Unregisterreceiver:

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

Specifies the broadcast target action:intent Intent = new Intent (actionstring);

and can carry the message via intent: Intent.putextra ("msg", "Hi, I sent the message by Radio");

Send Broadcast message: Context.sendbroadcast (Intent)

In dynamic registration, you can encapsulate the Broadcastreceiver inheriting classes, add constructors and Broadcastreceiver registrations

Broadcastreceiver's case Demo

First we create a class mybroadcastreceiver to inherit Broadcastreceiver:
One way to rewrite this is to accept the intention of the broadcast and match it:

Defined as: public static final String//action_register_success_finish= "Register.success.finish";
Constants.ACTION_REGISTER_SUCCESS_FINISH.equals (Intent.getaction ())

Here is the constant: the definition is as follows:

The public class Mybroadcastreceiver extends Broadcastreceiver {

    @Override
    the public void onreceive Intent Intent) {
      if Intent!= null && Constants.ACTION_REGISTER_SUCCESS_FINISH.equals (Intent.getaction () ) {
        finish ();}}}
  

(1) Then we will use the "dynamic registration" approach:

 Private Mybroadcastreceiver receiver = new Mybroadcastreceiver ();
    Intentfilter filter = new Intentfilter ();
    Filter.addaction (Bmobconstants.action_register_success_finish); Add Action
    registerreceiver (receiver, filter);//Sign Up

(2) Statically registered words are now added in the manifest file:

<receiver android:name= ". Mybroadcastreceiver "> 
      <intent-filter> 
        <action android:name=" Register.success.finish "/> 
        <category android:name= "Android.intent.category.DEFAULT"/> 
      </intent-filter> 
    </ Receiver> 

(2-1) We can use the code:

Intent Intent = new Intent ("Register.success.finish"); 
Intent.putextra ("msg", "Hello receiver."); 
Sendbroadcast (Intent); Send broadcast

General broadcast (normal broadcast)

Ordinary broadcasts are completely asynchronous for multiple receivers, and usually each receiver receives the broadcast without waiting, and the receiver does not affect each other. For this broadcast, the receiver cannot terminate the broadcast, that is, it cannot prevent other receivers from receiving the action. To verify the above argument, we create three new broadcastreceiver to demonstrate this process, firstreceiver, Secondreceiver, and Thirdreceiver code are as follows:

Import Android.content.BroadcastReceiver; 
Import Android.content.Context; 
Import android.content.Intent; 
Import Android.util.Log; 

public class Firstreceiver extends Broadcastreceiver { 

  private static final String TAG = "Normalbroadcast"; 

  @Override public 
  void OnReceive (context context, Intent Intent) { 
    String msg = Intent.getstringextra ("msg"); 
    LOG.I (TAG, "Firstreceiver:" + msg); 
  } 
 

public class Secondreceiver extends Broadcastreceiver { 

  private static final String TAG = "Normalbroadcast"; 

  @Override public 
  void OnReceive (context context, Intent Intent) { 
    String msg = Intent.getstringextra ("msg"); 
    LOG.I (TAG, "Secondreceiver:" + msg); 
  } 
 

public class Thirdreceiver extends Broadcastreceiver { 

  private static final String TAG = "Normalbroadcast"; 

  @Override public 
  void OnReceive (context context, Intent Intent) { 
    String msg = Intent.getstringextra ("msg"); C14/>LOG.I (TAG, "Thirdreceiver:" + msg); 
  } 
 

Then click the Send button again, send a broadcast, and the console prints as follows:

It seems that all three receivers have received this broadcast, and we modify the three recipients slightly, adding the following code on the last line of the OnReceive method to attempt to terminate the broadcast:

 
 

Clicking the Send button again, we will find that three receivers in the console still print their own logs, indicating that the receiver cannot terminate the broadcast.

Ordered broadcasts (Ordered broadcast)

An ordered broadcast is special, it is sent only to the higher priority receiver, and then the priority receiver is then propagated to the lower-priority recipient, who has the ability to terminate the broadcast.
To demonstrate the flow of ordered broadcasts, we modify the code for the above three recipients, as follows:

Import Android.content.BroadcastReceiver; 
Import Android.content.Context; 
Import android.content.Intent; 
Import Android.os.Bundle; 
Import Android.util.Log; 

public class Firstreceiver extends Broadcastreceiver { 

  private static final String TAG = "Orderedbroadcast"; 

  @Override public 
  void OnReceive (context context, Intent Intent) { 
    String msg = Intent.getstringextra ("msg"); C11/>LOG.I (TAG, "Firstreceiver:" + msg); 

    Bundle Bundle = new Bundle (); 
    Bundle.putstring ("msg", MSG + "@FirstReceiver"); 
    Setresultextras (bundle); 
  } 
 

public class Secondreceiver extends Broadcastreceiver { 

  private static final String TAG = "Orderedbroadcast"; 

  @Override public 
  void OnReceive (context context, Intent Intent) { 
    String msg = Getresultextras (True). GetString ( "MSG"); 
    LOG.I (TAG, "Secondreceiver:" + msg); 

    Bundle Bundle = new Bundle (); 
    Bundle.putstring ("msg", MSG + "@SecondReceiver"); 
    Setresultextras (bundle); 
  } 

public class Thirdreceiver extends Broadcastreceiver { 

  private static final String TAG = "Orderedbroadcast"; 

  @Override public 
  void OnReceive (context context, Intent Intent) { 
    String msg = Getresultextras (true). GetString ("msg"); 
    LOG.I (TAG, "Thirdreceiver:" + msg); 
  } 
 

We note that in both Firstreceiver and Secondreceiver, the Setresultextras method is used to set a bundle object as a result set object, passed to the next receiver, so that, since then, Lower-priority recipients can use Getresultextras to obtain the latest collection of processed information.
After the code has been changed, we need to register the broadcast address for three recipients, and we'll modify the Androidmainfest.xml file:

 <receiver android:name=". Firstreceiver "> <intent-filter android:priority=" 1000 "> <action android:name=" Android.intent.action.MY _broadcast "/> <category android:name= android.intent.category.DEFAULT"/> </intent-filter> </re Ceiver> <receiver android:name= ". Secondreceiver "> <intent-filter android:priority=" 999 "> <action android:name=" Android.intent.action.MY _broadcast "/> <category android:name= android.intent.category.DEFAULT"/> </intent-filter> </re Ceiver> <receiver android:name= ". Thirdreceiver "> <intent-filter android:priority=" 998 "> <action android:name=" android.intent.action.MY_ Broadcast "/> <category android:name= android.intent.category.DEFAULT"/> </intent-filter> </rec Eiver> 

We see that now these three receivers have an extra android:priority attribute, and then decrease it in turn. This property ranges from 1000 to 1000, and the larger the number, the higher the priority.
Now, we need to revise the code to send the broadcast as follows:

public void Send (view view) { 
  Intent Intent = new Intent ("Android.intent.action.MY_BROADCAST"); 
  Intent.putextra ("msg", "Hello receiver."); 
  Sendorderedbroadcast (Intent, "Scott.permission.MY_BROADCAST_PERMISSION"); 
} 

Note that when an ordered broadcast is sent using the Sendorderedbroadcast method, a permission argument 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.
So we define a permission in Androidmainfest.xml:

<permission android:protectionlevel= "normal" 
      android:name= "Scott.permission.MY_BROADCAST_PERMISSION"/ > 

Then the declaration uses this permission:

<uses-permission android:name= "Scott.permission.MY_BROADCAST_PERMISSION"/> 

If you don't understand this part, you can refer to an article I've written before: Android declaration and permission to use
Then we click the Send button to send a broadcast, and the console prints the following:

We see that the reception is in order, the first and second all add their own tags in the result set, and pass on the lower priority recipients.
Since it's a sequential delivery, try to terminate this pass and see how it works, we modify the Firstreceiver code and add the following code on the last line of OnReceive:

Abortbroadcast (); 

Then run the program again, and the console prints as follows:

This time, only the first recipient was executed, and the other two failed to perform because the broadcast was terminated by the first receiver.
Above is the introduction of Broadcastreceiver, I will give a few common examples to deepen your understanding and application of broadcasting:

1. Boot Service

We often have such applications, such as message push service, the need to implement the boot function. To do this, we can subscribe to the "launch complete" broadcast of the system, and we can start our own service after receiving this broadcast. Let's take a look at the concrete implementation of Bootcompletereceiver and Msgpushservice:

 import Android.content.BroadcastReceiver; 
Import Android.content.Context; 
Import android.content.Intent; 

Import Android.util.Log; public class Bootcompletereceiver extends Broadcastreceiver {private static final String TAG = "Bootcompletereceiver" 

  ; @Override public void OnReceive (context, Intent Intent) {Intent service = new Intent (context, Msgpushserv 
    Ice.class); 
    Context.startservice (service); LOG.I (TAG, "Boot Complete.") 
  Starting msgpushservice ... "); } 

} 

Import Android.app.Service; 
Import android.content.Intent; 
Import Android.os.IBinder; 
Import Android.util.Log; 

public class Msgpushservice extends Service { 

  private static final String TAG = "Msgpushservice"; 

  @Override public 
  void OnCreate () { 
    super.oncreate (); 
    LOG.I (TAG, "onCreate called."); 
  } 

  @Override public 
  int Onstartcommand (Intent Intent, int flags, int startid) { 
    log.i (TAG, "Onstartcommand called ."); 
    Return Super.onstartcommand (Intent, flags, Startid); 
  } 

  @Override public 
  IBinder onbind (Intent arg0) {return 
    null; 
  } 
} 

Then we need to configure the relevant information in the Androidmanifest.xml:

<!--the--> <receiver android:name= of the boot broadcast recipient 
. Bootcompletereceiver "> 
  <intent-filter> 
    <!--registered Boot broadcast address--> 
    <action android:name=" Android.intent.action.BOOT_COMPLETED "/> 
    <category android:name=" Android.intent.category.DEFAULT "/>" 
  </intent-filter> 
</receiver> 
<!--message Push service--> 
<service android:name= ". Msgpushservice "/> 

We see Bootcompletereceiver registered "Android.intent.action.BOOT_COMPLETED" This boot broadcast address, from the security point of view, the system requirements must declare the right to receive the boot up broadcast, We then declare that the following permissions are used:
After a few steps above, we have completed the startup function, the application will be run on the emulator, and then restart the simulator, the console print as follows:

If we look at the services that are already running, Msgpushservice is already running.

2. Network state changes

In some cases, such as when users browse the network information, the network suddenly disconnected, we should promptly remind the user network has been disconnected. To achieve this function, we can receive a network state change such a broadcast, when the connection state into a disconnected state, the system will send a broadcast, we receive, and then through the state of the network to make the appropriate operation. Here's how to do this:

Import Android.content.BroadcastReceiver; 
Import Android.content.Context; 
Import android.content.Intent; 
Import Android.net.ConnectivityManager; 
Import Android.net.NetworkInfo; 
Import Android.util.Log; 

Import Android.widget.Toast; public class Networkstatereceiver extends Broadcastreceiver {private static final String TAG = "Networkstatereceiver" 

  ; 
    @Override public void OnReceive (context context, Intent Intent) {log.i (TAG, "network state changed."); 
    if (!isnetworkavailable) {Toast.maketext (context, "network disconnected!", 0). Show ();  }/** * Network is available */public static Boolean isnetworkavailable (context context) {Connectivitymanager 
    MGR = (Connectivitymanager) context.getsystemservice (Context.connectivity_service); 
    Networkinfo[] info = Mgr.getallnetworkinfo (); if (info!= null) {for (int i = 0; i < info.length i++) {if (info[i].getstate () = = Networkinfo.state . 
       CONNECTED) {   return true; 
  }} return false; 

 } 
}

Register this recipient's message again:

<receiver android:name= ". Networkstatereceiver "> 
  <intent-filter> 
    <action android:name=" android.net.conn.CONNECTIVITY_ Change "/> 
    <category android:name=" Android.intent.category.DEFAULT "/> 
  </intent-filter> 
</receiver> 

Because we use the network state-related APIs in the Isnetworkavailable method, we need to declare the relevant permissions, and here is the corresponding permission declaration:

<uses-permission android:name= "Android.permission.ACCESS_NETWORK_STATE"/> 

We can test, for example, to turn off WiFi and see what the effect is.

3. Electricity change

If we read the software, it may be full screen reading, and users will not be able to see the remaining power, we can provide them with information on the power. To do this, we need to receive a broadcast of the electricity change, and then get the percent information, which sounds pretty simple, and we'll do the following:

Import Android.content.BroadcastReceiver; 
Import Android.content.Context; 
Import android.content.Intent; 
Import Android.os.BatteryManager; 
Import Android.util.Log; 

public class Batterychangedreceiver extends Broadcastreceiver { 

  private static final String TAG = "Batterychangedrece Iver "; 

  @Override public 
  void OnReceive (context context, Intent Intent) { 
    int currlevel = Intent.getintextra ( Batterymanager.extra_level, 0); Current charge 
    int total = Intent.getintextra (Batterymanager.extra_scale, 1);   Total charge 
    int percent = Currlevel * 100/total; 
    LOG.I (TAG, "battery:" + percent + "%"); 
  } 

 

Then sign up for the broadcast address information:

<receiver android:name= ". Batterychangedreceiver "> 
  <intent-filter> 
    <action android:name=" Android.intent.action.BATTERY_CHANGED "/> 
    <category android:name=" Android.intent.category.DEFAULT " > 
  </intent-filter> 
</receiver> 

Of course, there are times when we want to get the power immediately, not the broadcast of a change in electricity, for example, when the reading software is turned on to show the battery power immediately. We can get it in the following ways:

Intent batteryintent = Getapplicationcontext (). Registerreceiver (NULL, 
    new Intentfilter (Intent.action_battery_ CHANGED)); 
int currlevel = Batteryintent.getintextra (batterymanager.extra_level, 0); 
int total = Batteryintent.getintextra (Batterymanager.extra_scale, 1); 
int percent = Currlevel * 100/total; 
LOG.I ("Battery", "battery:" + percent + "%"); 

The above is the entire content of this article, I hope to help you learn.

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.