BroadcastReceiver 的生命周期

来源:互联网 发布:人工智能课程设计实例 编辑:程序博客网 时间:2024/05/17 17:17

Receiver Life-cycle


A BroadcastReceiver object is only valid for the duration of the call to onReceive(Context, Intent). Once your code returns from this function, the system considers the object to be finished and no longer active. 


This has important repercussions to what you can do in an onReceive(Context, Intent) implementation: anything that requires asynchronous operation is not available, because you will need to return from the function to handle the asynchronous operation, but at that point the BroadcastReceiver is no longer active and thus the system is free to kill its process before the asynchronous operation completes. 

In particular, you may not show a dialog or bind to a service from within a BroadcastReceiver. For the former, you should instead use the NotificationManager API. For the latter, you can use Context.startService() to send a command to the service. 

startActivity can only be one component (activity, service) to receive, Context.sendBroadcast (), can be subscribed to this intended recipient to receive all broadcast 

Radio receiver (BroadcastReceiver) for asynchronous receive broadcast Intent, Intent to send broadcast by calling Context.sendBroadcast (), Context.sendOrderedBroadcast () or Context.sendStickyBroadcast () to achieve. Intent is usually a broadcast can be subscribed to this Intent received a number of radio receivers, radio receivers and JMS Topic in the message receiver is very similar. To achieve a radio receiver as follows: 

The first step: Inheritance BroadcastReceiver, and rewrite onReceive () method. 

public class IncomingSMSReceiver extends BroadcastReceiver {   @ Override public void onReceive (Context context, Intent intent) {   } } 

Step Two: Subscribe to be interested in broadcasting Intent, subscribers in two ways: 
  • The first: to subscribe using code 
 
  IntentFilter filter = new IntentFilter ("android.provider.Telephony.SMS_RECEIVED");   IncomingSMSReceiver receiver = new IncomingSMSReceiver ();   registerReceiver (receiver, filter); 

  • The second: In AndroidManifest.xml file nodes in <application> subscribe: 
public class SmsListener extends BroadcastReceiver {   @ Override   public void onReceive (Context context, Intent intent) {     Bundle bundle = intent.getExtras ();     if (bundle! = null) {       Object [] pdus = (Object []) bundle.get ("pdus");       SmsMessage [] messages = new SmsMessage [pdus.length];       for (int i = 0; i <pdus.length; i + +) {         messages [i] = SmsMessage.createFromPdu ((byte []) pdus [i]);       }       SmsManager manager = SmsManager.getDefault ();       for (SmsMessage msg: messages) {         String content = msg.getMessageBody ();         String sender = msg.getOriginatingAddress ();         Date date = new Date (msg.getTimestampMillis ());         SimpleDateFormat format = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss");         String time = format.format (date);         String text = time + ":" + sender + ":" + content;         // Forwarded to your phone         manager.sendTextMessage ("1xxxx435", null, text, null, null);       }     }   } } 

<? Xml version = "1.0" encoding = "utf-8"?> <Manifest xmlns: Android = " http://schemas.android.com/apk/res/android "   package = "yt.hy.sms"   android: versionCode = "1"   android: versionName = "1.0">   <uses-sdk android:minSdkVersion="8" />   <application android:icon="@drawable/icon" android:label="@string/app_name">     <Receiver android: name = ". SmsListener" android: label = "Sms listener">       <intent-filter>         <action android:name="android.provider.Telephony.SMS_RECEIVED"/>       </ Intent-filter>     </ Receiver>   </ Application>   <uses-permission android:name="android.permission.RECEIVE_SMS"/> <! - permission to receive text messages ->   <uses-permission android:name="android.permission.SEND_SMS"/> <! - permission to send text messages -> </ Manifest> 

Has been issued to the 10086 is a mistake, 

manager.sendTextMessage ("1xxxx", null, text, null, null); 


Sentence will be free pointer error. 

Later discovered that this is a BUG, ​​when the figures for multi-point occurs when the null pointer error when fewer words will not, no wonder google did not promote the use of SmsManager this class ,,,,, 


There is no way such a long time to waste, 


Added: 


In addition to the arrival of broadcast messages Intent, Android and many radio Intent, such as: boot, battery change, the time has changed and so broadcast Intent. 

Changes in radio receiver battery Intent, AndroidManifest.xml file in the node where <application> Subscribe to this Intent: 

<receiver android:name=".IncomingSMSReceiver">   <intent-filter>     <action android:name="android.intent.action.BATTERY_CHANGED"/>   </ Intent-filter> </ Receiver> 

Boot received broadcast Intent, AndroidManifest.xml file in the node where <application> Subscribe to this Intent: 


<receiver android:name=".IncomingSMSReceiver">   <intent-filter>     <action android:name="android.intent.action.BOOT_COMPLETED"/>   </ Intent-filter> </ Receiver> 


And to the declaration of competence: 
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/> 

Usually the life cycle of a BroadcastReceiver object no more than 5 seconds, so there can not be done in the BroadcastReceiver some of the more time-consuming operation, a relatively time-consuming if you need to complete the work, you can send the Intent to Activity or Service, to the Activity or Service completed. 

public class IncomingSMSReceiver extends BroadcastReceiver {   @ Override  public void onReceive (Context context, Intent intent) {     // Send the Intent to start the service, from service to perform time-consuming operation     Intent service = new Intent (context, XxxService.class);     context.startService (service);     // Send start Intent Activity, Activity to be completed by the time-consuming operation     Intent newIntent = new Intent (context, XxxActivity.class);     context.startActivity (newIntent);   } } 

New threads can also be used by: 

new Thread (new Runnable () {   public void run () {     // xxxxxxxx   } }). Start (); 

Summary: 
In Android, if you want to send a broadcast to be sent to the system using sendBroadCast its interest in radio receiver.
Radio must have an intent to use the object moves the object will set its action
Using the radio must be explicit in the configuration file specified in the broadcast object
Will be re-generated each time a radio receiver to receive the broadcast object
As far as possible in the BroadCast not deal with too many logical problems, the proposed complex logic to the Activity or Service to deal with.
原创粉丝点击