Broadcast Receive life cycle

Source: Internet
Author: User

Broadcastreceiver Introduction

Broadcastreceiver Source is located at: Framework/base/core/java/android.content.broadcastreceiver.java

The broadcast recipient (Broadcastreceiver) is used to receive broadcast Intent, and the broadcast Intent is sent by calling Context.sendbroadcast (), Context.sendorderedbroadcast () To achieve. Typically a broadcast Intent can be received by multiple broadcast receivers subscribed to this Intent.

Broadcasting is a widely used mechanism for transmitting information between applications . And Broadcastreceiver is a kind of component that filters and receives and responds to the transmitted broadcast;

Some data from a common application, such as an application that notifies other applications, has already been downloaded.

The broadcastreceiver itself does not implement a graphical user interface, but when it receives a notification, Broadcastreceiver can initiate activity as a response, or Notificationmananger alert the user, or start Service and so on.

The mechanism of Broadcastreceiver

1. Mechanism

There are all kinds of broadcasts in Android, such as the use of batteries, the reception of telephones and the reception of text messages, which generate a broadcast, and application developers can listen to these broadcasts and make procedural logic.

2. Implement

Use to receive SMS examples:

The first way :

Realize

Public class Mybroadcastreceiver extends broadcastreceiver {

Action Name

String sms_received = "Android.provider.Telephony.SMS_RECEIVED";

Public void onreceive (context context, Intent Intent) {

if (Intent.getaction (). Equals (sms_received)) {

Related processing: regional transformation, insufficient electricity, incoming letter;

}

}

}

System registration: in Androidmanifest.xml Registered in

< receiver Android:name = ". Mybroadcastreceiver " >

< Intent-filter android:priority = "+" >

< action Android:name = " android.provider.Telephony.SMS_RECEIVED" />

</intent-filter >

</receiver > of course, permissions are required :

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

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

The second way:

Broadcast recipient-Broadcast reception

Private Broadcastreceiver mybroadcastreceiver = new broadcastreceiver () {

@Override

Public void onreceive (context context, Intent Intent) {

Related processing, such as receiving SMS, monitor the Power change information

}

};

Register in Code:

Intentfilter intentfilter = new intentfilter ("Android.provider.Telephony.SMS_RECEIVED");

Registerreceiver (Mbatteryinforeceiver, Intentfilter);

3. Life cycle

Describes the life cycle of the broadcast in Android, and secondly it is not as complex as Activity, and the principle of operation is simple as:

The life cycle is only about 10 seconds, if onreceive () within 10 seconds of doing things, you will get an error .

Each time the broadcast arrives, the Broadcastreceiver object is recreated, and the OnReceive () method is called, and the object is destroyed when it finishes executing. When the OnReceive () method is not completed within 10 seconds, Android will consider the program unresponsive. So in

Broadcastreceiver can not do some more time-consuming operation, the side will eject the ANR (Application No

Response) dialog box. 。 ():

How to use it well Broadcastreceiver ?

If you need to complete a more time-consuming task, you should do so by sending Intent to the service. It is not possible to use child threads here because the Broadcastreceiver life cycle is short and the child threads may not have ended

The Broadcastreceiver will be finished first. Once the broadcastreceiver is over, this broadcastreceiver

The process is easy to kill when the system needs memory because it belongs to an empty process (a process without any active components). If its host process is killed, then the working child thread will be killed. So using sub-threading to solve is unreliable.

Broadcast type and broadcast type

General Broadcast (Normal broadcasts)

Send a broadcast, so the broadcast receiver listening to the broadcast can listen to change the broadcast.

asynchronous broadcast , when the intent after processing, still exist, this time Registerreceiver (Broadcastreceiver, Intentfilter) can also receive his value, until you remove it, The processing result cannot be passed to the next recipient and the broadcast cannot be terminated.

Orderly Broadcast (Ordered broadcasts)

Receive broadcasts in the priority order of the recipients, declared in priority in Intent-filter, 1000 to

1000, the greater the value, the higher the priority. The continuation of broadcast intent can be terminated. The recipient can tamper with the content.

Radio and receiver

The component that receives the broadcast Intent,context can pass Sendbroadcast () and Sendorderedbroadcast ()

method to implement broadcast delivery.

First, place the information to be sent and the information used for filtering (such as Action, Category) into a Intent object where the message is to be sent , and then call Context.sendbroadcast (), Sendorderbroadcast (), or Sendstickybroadcast () method to send the intent object as a broadcast.

Using the Sendbroadcast () or Sendstickybroadcast () method to emit a Intent, all broadcastreceiver that meet the criteria will randomly execute their onreceive () method

Sending and receiving of ordinary broadcasts:

Sendbroadcast (Intent);

Intent Intent = new Intent ("cn.lenovo.yangguangf ");

Sendbroadcast (Intent);

Priority: This is the Intent-filter parameter in androidmanifest.xml .

< receiver Android:name = ". Mybroadcastreceiver " >

< Intent-filter android:priority = "+" >

< action Android:name = "Cn.lenovo.yangguangfu" />

</intent-filter >

</receiver >

Sendorderedbroadcast (Intent, receiverpermission);

1, he decides the level of the broadcast, the level value is between 1000 to 1000, the greater the value, the higher the priority;

2, the same level of reception is the random, low-level received the broadcast;

3, in the Android system as long as listen to the receiver of the broadcast, can receive Sendbroadcast (intent) issued by the broadcast;

3, can not truncate the continuation of the broadcast transmission,

4, experimental phenomenon, in this method sent to the broadcast, the Code registration method, received the broadcast successively and noted that the highest priority of their order is random. If neither has a priority, the code registration is received as the first.

Sending and receiving of ordered broadcasts:

Sendorderedbroadcast (Intent, receiverpermission);

Sendorderedbroadcast (Intent, receiverpermission, Resultreceiver,

Scheduler, Initialcode, Initialdata, Initialextras)

Intent, broadcast, all matching this intention to receive the receiver broadcast.

Receiverpermission This is permission, a receiver must hold to receive your broadcast. If NULL, the requirement is not approved.
Resultreceiver your own broadcastreceiver as the final broadcast receiver.
Scheduling custom handlers to schedule resultreceiver callbacks; If null, the main thread in the context is held.
Initialcode the initial value of a result code. It is usually activity.result_ok. This value is-1; for other int types can also, such as 0,1,2;
Initialdata the initial value of a result data. Normally null, is a String type;
Initialextras an additional initial value for the result. Usually empty, is Bundle;

Intent the intent to broadcast; All receivers matching this Intent would receive the broadcast.

Receiverpermission String naming a permissions a receiver must hold in order to receive your broadcast. If NULL, no permission is required.

Resultreceiver Your own broadcastreceiver to treat as the final receiver of the broadcast.

Scheduler A custom Handler with which to schedule the resultreceiver callback; If NULL it is scheduled in the Context ' s main thread.

Initialcode an initial value for the result code. Often ACTIVITY.RESULT_OK.

Initialdata an initial value for the result data. Often NULL.

Initialextras an initial value for the result extras. Often NULL.

1, the level of the broadcast level, the level value is between 1000 to 1000, the greater the value, the higher the priority;

2, the same level receive is successively random, and then to the level of low received broadcast;

3, 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. (Abortbroadcast ())

4, can cut off the continued transmission of the broadcast, high-level broadcasts received by the broadcast, can decide whether the clock broadcast is truncated.

5, experimental phenomenon, in this method sent to the broadcast, the Code registration method, received the broadcast order: marked priority, code registration, no priority; If there is no priority, the code registration is received as the first.

Send and receive for asynchronous broadcasts:

Sendstickybroadcast (Intent);

When the intent is finished, it still exists until you remove it.

Send this broadcast requires permission <uses-permission android:name="Android.permission.BROADCAST_STICKY" />

To remove is to use this method Removestickybroadcast (intent); But do not forget in the implementation of this method of application inside Androidmanifest.xml also have to add face permissions;

Sendstickyorderedbroadcast (Intent, resultreceiver, scheduler,

Initialcode, Initialdata, Initialextras)

This method has the characteristics of an orderly broadcast and an asynchronous broadcast;

Send this broadcast to: <uses-permission android:name="Android.permission.BROADCAST_STICKY" /> This permission. To use this method. If you do not have this permission, the SecurityException will be thrown.

Experimental Phenomena (Sendstickyorderedbroadcast ()), in this method sent to the broadcast, the Code registration method, received the broadcast order is: priority, code registration, no priority; If there is no priority, the code registration is received as the first.

Broadcast registration and deregistration code to register the broadcast:

Registered Broadcast method one: Registerreceiver (broadcastreceiver receiver, Intentfilter filter), the first parameter is the broadcastreceiver we want to process the broadcast (broadcast receiver, can be either system or custom); The second parameter is the intent filter.

Registered Broadcast Method II: Registerreceiver (receiver, filter, broadcastpermission, scheduler), the first parameter is Broadcastreceiver (broadcast receiver, can be system, can also be customized), the second parameter is the intent filter, the third parameter is the broadcast permission, the fourth parameter is hander;

Note: Permissions duplication, if the function manifest file registered permissions, in the method of re-registration, receiver can not receive the broadcast, if the function manifest file does not have permission to register, the method registration can not be received. When the method does not have registration permission, receiver can receive the broadcast when the function list is registered.

Summary: In Activity The Code registration broadcast recommendation is registered in: Onresume ();

Thinking Expansion: 1, if the code calls Registerreceiver (Broadcastreceiver receiver, intentfilter filter) 10 times (receiver, the parameter of the filter is the same parameter), So will it receive 10 times when the broadcast is sent?

2, write off if you have to write off 10 times in order to write off all the broadcasts?

Register the broadcast in the system: (in Androidmanifest.xml)

< receiver Android:name = ". Mybroadcastreceiver " >

< Intent-filter android:priority = "" ">

< action Android:name = "Cn.lenovo.yangguangfu" />

</intent-filter >

</receiver >

Sometimes you have to decide whether or not you want permissions based on whether you specify permissions for the Send broadcast.

Broadcast logoff

Sign out of the broadcast in code

/unregisterreceiver (Mbatteryinforeceiver);

The code logoff broadcast in Activity is recommended to be logged out in: Onpuase ();

Do not unregister this in this activity.onsaveinstancestate (), because this method is to save the Intent state.

Broadcastreceiver's Apiabortbroadcast ():

This method can intercept broadcasts sent by Sendorderedbroadcast () so that other broadcast receivers cannot receive the broadcast.

Clearabortbroadcast ()

This method is targeted at the Abortbroadcast () method above and is used to cancel interception of broadcasts. This will enable its next-level broadcast receiver to receive the broadcast.

Getabortbroadcast ()

The function of this method is to determine if Abortbroadcast () is called, and if Abortbroadcast () is called First, then Getabortbroadcast () is called, which returns true; If you are calling Abortbroadcast (), Clearabortbroadcast ()

Getabortbroadcast (), will return false;

Public Final Boolean getdebugunregister ()

SINCE:API Level 1

Return the last value of given to setDebugUnregister(boolean) .

Getresultcode ()

If the broadcast is sent using the following four methods, the return code is:-1;

Sendbroadcast (Intent);

Sendbroadcast (Intent, receiverpermission);

Sendorderedbroadcast (Intent, receiverpermission);

Sendstickybroadcast (Intent);

If you send a broadcast using the following two methods, the return code is: According to the number you set Initialcode is how much;

Sendstickyorderedbroadcast (Intent, resultreceiver, scheduler,

Initialcode, Initialdata, Initialextras)

Sendorderedbroadcast (Intent, receiverpermission, Resultreceiver,

Scheduler, Initialcode, Initialdata, Initialextras)

Getresultdata ()

Get the Initialdata data that is set when the broadcast is sent;

Getresultextras (Boolean Makemap)

If True then a new empty Map would be made for if the current Map is null; If False you should is prepared to receive a null MAP.

Get By

Sendstickyorderedbroadcast (Intent, resultreceiver, scheduler,

Initialcode, Initialdata, Initialextras);

Sendorderedbroadcast (Intent, receiverpermission, Resultreceiver,

Scheduler, Initialcode, Initialdata, Initialextras)

The parameters that are passed in Initialextras.

Experiment: I used the above two methods to send Initialextras (this one Bundle) passed in parameters, as long as not empty, then Makemap is true and false to get the data.

Isinitialstickybroadcast ()

Returns true if the receiver is currently processing the initial value of a sticky broadcast – that's, the value that WA S last broadcast and are currently held in the sticky cache, so this is not directly the result of a broadcast right now.

If the broadcast receiver is currently processing the initial value of a host's broadcast, it will return true-that is, this value is the last broadcast out of the value that is currently being held by the host cache, so this is not directly causing the current broadcast.

Experiment: Call this method in the third application, whichever way you send the broadcast, this method always gets false; it is called in the Resultreceiver broadcast receiver of the broadcast, and the result is false;

Isorderedbroadcast ()

Sendstickyorderedbroadcast (Intent, resultreceiver, scheduler,

Initialcode, Initialdata, Initialextras)

When the above method is sent, the resulting is true;

Determine whether it is an orderly broadcast;

OnReceive (context context, Intent Intent)

Public IBinder Peekservice (Context mycontext, Intent service)

Provide a binder to an already-running service. This method is synchronous and would not start the target service if it isn't present, so it's safe to call from Onreceiv E.

Parameters:

Mycontext the context, had been passed to onreceive (context, Intent)

Service the Intent indicating the service wish to use. See Context.startservice (Intent) for more information.

Setdebugunregister (Boolean Debug)

Control inclusion of debugging help for mismatched calls to {@ context#registerreceiver (broadcastreceiver, Intentfilter) C Ontext.registerreceiver ()}. If called with true, before given to Registerreceiver () and then the callstack of the following call Context.unregisterReceiver() is retained Printed if a later incorrect unregister call is made. Note that doing this requires retaining information on the broadcastreceiver for

Reprint: http://yangguangfu.iteye.com/blog/1063732

Broadcast Receive life cycle

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.