[Android] Broadcastreceiver Summary

Source: Internet
Author: User

Definition of Broadcastreceiver

Broadcast is a widely used mechanism for transmitting information between applications, which is mainly used to listen to the broadcast information sent by the system or application, then according to the broadcast information as the corresponding logical processing, but also can be used to transmit a small amount of low frequency data.

The application is processed by the broadcast of the receiving system when the boot-up service and network status changes, power changes, text messages and calls are made.

Broadcastreceiver itself does not implement a graphical user interface, but when it receives a notification, Broadcastreceiver can alert the user by starting the Service, initiating Activity, or Notificationmananger.

Broadcastreceiver Use note

When the system or application broadcasts, it will scan all the broadcast receivers in the system, send the broadcast to the appropriate recipient through action matching, and the receiver will generate an instance of the broadcast receiver after receiving the broadcast, and execute the Onreceiver () method It is particularly important to note that the lifetime of this instance is only 10 seconds, and if the end Onreceiver () is not executed within 10 seconds, the system will error.
  
After Onreceiver () is executed, the instance will be destroyed, so do not take the time-consuming action in onreceiver (), or create a sub-threading service inside (because it is possible that the sub-threads are not processed and the receiver is recycled, then the child threads are then recycled) The right approach is to invoke activity or service processing through in.

Broadcastreceiver's Registration

There are only two ways to register Broadcastreceiver, one is static registration (recommended), the other is dynamic registration, and the broadcast receiver starts listening to the broadcast message sent between the system or application after registering.

Receive SMS Broadcast example :

Define your own Broadcastreceiver class

publicclass MyBroadcastReceiver extends BroadcastReceiver {// action 名称"android.provider.Telephony.SMS_RECEIVED" ;    publicvoidonReceive(Context context, Intent intent) {       if (intent.getAction().equals( SMS_RECEIVED )) {           // 一个receiver可以接收多个action的,即可以有多个intent-filter,需要在onReceive里面对intent.getAction(action name)进行判断。       }    }}
static mode

Define receiver in Androidmanifest.xml's application and set the action to receive.

< receiver android:name = ".MyBroadcastReceiver" >  < intent-filter android:priority = "777" >             <action android:name = "android.provider.Telephony.SMS_RECEIVED" /></ intent-filter ></ receiver >

The priority value here is 1000 to 1000, the higher the value the higher the precedence, and the attention plus the system to receive SMS restrictions.

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

A statically registered broadcast receiver is a global listener that resides in the system, and when you configure a static broadcastreceiver in the application, the broadcast recipient is already resident in the system, regardless of whether the app is running or not. At the same time all receiver in the application is in the manifest file, easy to view.
  
To destroy a broadcast receiver that is statically registered, you can disable receiver by calling Packagemanager.

Dynamic mode

Declare the Broadcastreceiver extension object in activity, register it in Onresume, and unload it in OnPause.
   

 Public  class mainactivity extends Activity {Mybroadcastreceiver receiver;@Override     protected void Onresume() {//Dynamic registration of broadcasts (the code executes so that it starts listening for broadcast messages and handles broadcast messages as appropriate)Receiver =NewMybroadcastreceiver (); Intentfilter Intentfilter =NewIntentfilter ("Android.provider.Telephony.SMS_RECEIVED"); Registerreceiver (receiver, intentfilter);Super. Onresume (); }@Override    protected void OnPause() {//Revoke registration (the broadcast recipient will no longer listen to the system's broadcast messages after deregistration)Unregisterreceiver (receiver);Super. OnPause (); }}
The difference between static registration and dynamic registration

1, static registration of the broadcast receiver once installed in the system, do not need to restart the wake-up recipient;
Dynamically registered broadcast receivers with the application's life cycle, the registerreceiver starts to listen, the listener is withdrawn by the Unregisterreceiver, if the application exits, no revocation of the registered recipient app will be an error.

2. When the broadcast receiver initiates an activity or service through intent, if the corresponding component cannot be matched in intent.
Dynamically registered broadcast receivers will result in an application error
The static registered broadcast receiver will not have any error, because since the application installation is complete, the broadcast receiver and the application has been out of relation.

Send Broadcastreceiver

There are two main types of sending broadcasts:

General broadcast

Applications that need to be notified to individual broadcast receivers, such as boot-up

How to use: Sendbroadcast ()

new Intent("android.provider.Telephony.SMS_RECEIVED"//通过intent传递少量数据intent.putExtra("data""finch"// 发送普通广播

The normal broadcast is completely asynchronous and can be received by all receivers at the same time (logically), and all broadcastreceiver that satisfy the condition will randomly execute its onreceive () method.
The reception at the same level is successively random, and the low level receives the broadcast;
Message delivery is more efficient and cannot interrupt broadcast propagation.

Orderly broadcast

Applications are used in scenarios where specific interception is required, such as blacklist text messages and phone interception.

How to use:

Sendorderedbroadcast (Intent, receiverpermission);

Receiverpermission: A receiver must hold to receive your broadcast. If NULL, the requirement is not permitted (generally null).

//发送有序广播null);

In an ordered broadcast, we can send the processed data to the subsequent broadcast receivers in the previous broadcast receiver, or call Abortbroadcast () to end the broadcast propagation.

publicvoidonReceive(Context arg0, Intent intent) {  //获取上一个广播的bundle数据  Bundle bundle = getResultExtras(true);//true:前一个广播没有结果时创建新的Bundle;false:不创建Bundle  bundle.putString("key""777");  //将bundle数据放入广播中传给下一个广播接收者  setResultExtras(bundle);     //终止广播传给下一个广播接收者  abortBroadcast();}

When the broadcast is received by a high-level broadcast, it is possible to decide whether to truncate the broadcast.
The same level of reception is random, if the first received the broadcast truncated, the same level of exception recipients are unable to receive the broadcast.
  

Asynchronous broadcast

How to use: Sendstickybroadcast ():

The issued Intent can be re-accepted to its Intent when the receiving activity (dynamic registration) is re-onresume. (The Intent will is held to being re-broadcast to future Receivers). This means that the last intent issued by Sendstickybroadcast will be retained and will be accepted the next time the activity is active.

You need permission to send this broadcast:

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

To uninstall the broadcast:

removeStickyBroadcast(intent);

The intent will be retained before the uninstallation, and the receiver will be available in the receiving State.

Asynchronous ordered broadcast

How to use: Sendstickyorderedbroadcast (Intent, resultreceiver, scheduler,
Initialcode, Initialdata, Initialextras):

This method has the characteristics of an orderly broadcast and an asynchronous broadcast;
Also requires restriction:

<uses-permission android:name="android.permission.BROADCAST_STICKY" />
Summarize
    • The processor that is received by the static broadcast is owned by Packagemanagerservice, and when the phone is launched or a new app is installed, Packagemanagerservice scans all installed apps in the phone, The information about registered broadcasts in Androidmanifest.xml is parsed and stored in a global static variable.

    • The processor that is received by the dynamic broadcast is owned by Activitymanagerservice, and when the app's service or process is up, it executes the code logic of the registered broadcast receipt, which is loaded and stored in an additional global static variable. It is important to note that:

      1, this is not immutable, when the program is killed, the registered dynamic broadcast receiver will also be moved out of the global variables, until the next time the program starts, and then the dynamic broadcast registration, of course, the order has been changed once.

      2, there is not a complete sequence of broadcasting, only record the order of registration, there is no combination of priority processing.

    • When the broadcast is issued, the broadcast receiver receives the following order:

      1. When a broadcast is a normal broadcast , it has the following order of reception:

      Ignore priority
      Dynamic takes precedence over static
      A dynamic broadcast receiver with priority, which is registered more than
      Static broadcast receivers of the same priority, first scanned for larger than 

      2. If the broadcast is an ordered broadcast , then the dynamic broadcast processor and the static broadcast processor are combined to process the broadcast message, which ultimately determines the order in which the broadcast is received:
        
      First receive with high priority
      Static and dynamic broadcast receivers with priority
      A dynamic broadcast receiver with priority, which is registered more than
      Static broadcast receivers of the same priority, first scanned for larger than 

Some popular systems broadcast action and permission
    • Boot up

<action android:name="android.intent.action.BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />  
    • Network status
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>  
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

How the network is available:

 public  static  boolean  isnetworkavailable  (Context context) {Connect Ivitymanager 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 ; } 
    • Power change
<action android:name="android.intent.action.BATTERY_CHANGED"/>  

Broadcastreceiver Method of OnReceive:

publicvoidonReceive(Context context, Intent intent) {          int0);  //当前电量           int1);    //总电量          int100 / total;          "battery: ""%");      }  

[Android] Broadcastreceiver Summary

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.