Android BroadcastReceiver 的生命周期及实际应用

来源:互联网 发布:linux json 格式化 编辑:程序博客网 时间:2024/05/12 13:35

BroadcastReceiver 有一个回调方法:void onReceive(Context curContext, Intent broadcastMsg)。当一个广播消息到达接收者时,Android 调用它的 onReceive() 方法并传递给它包含消息的 Intent 对象。BroadcastReceiver 被认为仅当它执行这个方法时是活跃的。当 onReceive() 返回后,它是不活跃的。

活跃的 BroadcastReceiver 的进程是受保护的,不会被杀死。但是系统可以在任何时候杀死有不活跃组件的进程。

这带来一个问题,当一个广播消息的响应时费时的,因此应该在独立的线程中做这些事,远离用户界面或者其它组件运行的主线程。如果 onReceive() 衍生线程然后返回,整个进程,包括新的线程,被判定为不活跃的(除非进程中的其它应用程序组件是活跃的),否则将使它处于被杀的危机。解决这个问题的方法是 onReceive() 启动一个 Service,让 Service 做这个工作,因此系统知道进程中有活跃的工作在做。

BroadcastReceiver 和事件处理机制类似,只不过事件的处理机制是应用程序级别的,而广播处理机制是系统级别的。

BroadcastReceiver 用于接收并处理广播通知(broadcast announcements)。多数的广播是系统发起的,如地域变换、电量不足、来电来信等,当然,应用程序自己也可以广播一个广播。BroadcastReceiver 可以通过多种方式通知用户:启动activity、使用NotificationManager、开启背景灯、振动设备、播放声音等,最典型的是在状态栏显示一个图标,这样用户就可以点它打开看通知内容。

通常某个应用或系统本身在某些事件(电池电量不足、来电来短信)来临时会广播一个 Intent 出去,通过注册一个 BroadcastReceiver 来监听到这些 Intent,并获取其中广播的数据。

Android BroadcastReceiver 实际应用

不同进程之间通过 BroadcastReceiver 传递信息,可以通过以下两种方式来实现:

第一种方式:在 AndroidManifest.xml 中注册 BroadcastReceiver,这里推荐使用这种方法,因为它不需要手动注销广播(如果广播未注销,程序退出时可能会出错)。

[html] view plaincopyprint?
  1. <receiver android:name=".mEvtReceiver">  
  2.     <intent -filter>  
  3.     <action android:name="android.intent.action.BOOT_COMPLETED" />  
  4.     </intent>  
  5.     </receiver>  

上面两个 android:name 分别是广播名和广播的动作(这里的动作是表示系统启动完成),如果要自己发送一个广播,在代码中为:

[java] view plaincopyprint?
  1. Intent i = new Intent("android.intent.action.BOOT_COMPLETED");  
  2.     sendBroadcast(i);  

这样,广播就发出去了,然后是接收。接收可以新建一个类,继承 BroadcastReceiver,也可以实例化一个 BroadcastReceiver 对象,代码如下:

[java] view plaincopyprint?
  1. protected BroadcastReceiver mEvtReceiver = new BroadcastReceiver() {  
  2.  @Override  
  3.  public void onReceive(Context context, Intent intent) {  
  4.   String action = intent.getAction();  
  5.   if (action.equals("android.intent.action.BOOT_COMPLETED")) {  
  6.     //Do something  
  7.   }  
  8.  }  
  9. };  

完整实例:

[html] view plaincopyprint?
  1. < ?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.       package="android.basic.lesson21"  
  4.       android:versionCode="1"  
  5.       android:versionName="1.0">  
  6.     <uses -sdk android:minSdkVersion="8" />  
  7.    
  8.     <application android:icon="@drawable/icon" android:label="@string/app_name">  
  9.         <activity android:name=".MainBroadcastReceiver"  
  10.                   android:label="@string/app_name">  
  11.             <intent -filter>  
  12.                 <action android:name="android.intent.action.MAIN" />  
  13.                 <category android:name="android.intent.category.LAUNCHER" />  
  14.             </intent>  
  15.         </activity>  
  16.          <receiver android:name=".HelloBroadReciever">  
  17.              <intent -filter>  
  18.                  <action android:name="android.basic.lesson21.Hello88" />  
  19.             </intent>  
  20.     </receiver>   
  21.    
  22.     </application>  
  23. </manifest>  
[html] view plaincopyprint?
  1.   
[java] view plaincopyprint?
  1. package android.basic.lesson21;  
  2.    
  3. import android.app.Activity;  
  4. import android.content.Intent;  
  5. import android.os.Bundle;  
  6. import android.view.View;  
  7. import android.widget.Button;  
  8.    
  9. public class MainBroadcastReceiver extends Activity {  
  10. /** Called when the activity is first created. */  
  11. @Override  
  12. public void onCreate(Bundle savedInstanceState) {  
  13.   super.onCreate(savedInstanceState);  
  14.   setContentView(R.layout.main);  
  15.    
  16.   Button b1 = (Button) findViewById(R.id.Button01);  
  17.    
  18.   b1.setOnClickListener(new View.OnClickListener() {  
  19.    
  20.    @Override  
  21.    public void onClick(View v) {  
  22.     // 定义一个intent  
  23.     Intent intent = new Intent().setAction("android.basic.lesson21.Hello88")  
  24.       .putExtra("yaoyao","yaoyao is 189 days old ,27 weeks -- 2010-08-10");  
  25.     System.out.println("sendBroadcast");  
  26.     // 广播出去  
  27.     sendBroadcast(intent);  
  28.    }  
  29.   });  
  30.    
  31.  }  
  32. }  

[java] view plaincopyprint?
  1. package android.basic.lesson21;  
  2.    
  3. import android.content.BroadcastReceiver;  
  4. import android.content.Context;  
  5. import android.content.Intent;  
  6. import android.util.Log;  
  7.    
  8. public class HelloBroadReciever extends BroadcastReceiver {  
  9.   public HelloBroadReciever() {  
  10.     System.out.println("HelloBroadReciever");  
  11.   }  
  12.    
  13.   // 如果接收的事件发生  
  14.   @Override  
  15.   public void onReceive(Context context, Intent intent) {  
  16.    
  17.     // 对比Action决定输出什么信息  
  18.     if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {  
  19.       Log.i("HelloBroadReciever","BOOT_COMPLETED !!!!!!!!!!!!!!!!!!!!!!!!!");  
  20.     }  
  21.    
  22.     if (intent.getAction().equals("android.basic.lesson21.Hello88")) {  
  23.       Log.i("HelloBroadReciever","Say Hello to Yaoyao !!!!!!!!!!!!!!!!!!!!!!!!!");  
  24.       Log.i("HelloBroadReciever", intent.getStringExtra("yaoyao"));  
  25.     }  
  26.     Log.i("HelloBroadReciever","onReceive**********");  
  27.     // 播放一首音乐  
  28.     // MediaPlayer.create(context, R.raw.babayetu).start();  
  29.    }  
  30.    
  31. }  

第二种方式,直接在代码中实现,但需要手动注册注销,以短信接收为例,实现如下:

[java] view plaincopyprint?
  1. IntentFilter filter = new IntentFilter();  
  2. filter.addAction("android.provider.Telephony.SMS_RECEIVED");  
  3. registerReceiver(mEvtReceiver, filter); //这时注册了一个recevier ,名为mEvtReceiver,然后同样用上面的方法以重写onReceiver,  
  4. 最后在程序的onDestroy中要注销广播,实现如下:  
  5. @Override  
  6. public void onDestroy() {  
  7.   super.onDestroy();  
  8.   unregisterReceiver(mPlayerEvtReceiver);  
  9. }  

完整实例:

[html] view plaincopyprint?
  1. < ?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.       package="android.basic.lesson21"  
  4.       android:versionCode="1"  
  5.       android:versionName="1.0">  
  6.     <uses -sdk android:minSdkVersion="5" />  
  7.    
  8.     <application android:icon="@drawable/icon" android:label="@string/app_name">  
  9.         <activity android:name=".MainBroadcastReceiver"  
  10.                   android:label="@string/app_name">  
  11.             <intent -filter>  
  12.                 <action android:name="android.intent.action.MAIN" />  
  13.                 <category android:name="android.intent.category.LAUNCHER" />  
  14.             </intent>  
  15.         </activity>  
  16.     </application>  
  17.   <uses -permission android:name="android.permission.RECEIVE_SMS"/>  
  18. </manifest>  

[java] view plaincopyprint?
  1. package android.basic.lesson21;  
  2.    
  3. import android.app.Activity;  
  4. import android.content.IntentFilter;  
  5. import android.os.Bundle;  
  6. import android.util.Log;  
  7. import android.view.View;  
  8. import android.widget.Button;  
  9.    
  10. public class MainBroadcastReceiver extends Activity {  
  11. /** Called when the activity is first created. */  
  12.   HelloBroadReciever br;  
  13.   @Override  
  14.   public void onCreate(Bundle savedInstanceState) {  
  15.     super.onCreate(savedInstanceState);  
  16.     setContentView(R.layout.main);  
  17.     Button b1 = (Button) findViewById(R.id.Button01);  
  18.     b1.setOnClickListener(new View.OnClickListener() {  
  19.       @Override  
  20.       public void onClick(View v) {  
  21.        Log.i("click","OnClick");  
  22.        br=new HelloBroadReciever();  
  23.        IntentFilter filter=new IntentFilter();  
  24.        filter.addAction("android.provider.Telephony.SMS_RECEIVED");  
  25.        registerReceiver(br, filter);  
  26.       }  
  27.     });  
  28.   }   
  29.    
  30.   @Override  
  31.   public void onDestroy() {  
  32.     super.onDestroy();  
  33.     unregisterReceiver(br);  
  34.     Log.i("br","onDestroy");  
  35.   }  
  36.    
  37. }  

[java] view plaincopyprint?
  1. package android.basic.lesson21;  
  2.    
  3. import android.content.BroadcastReceiver;  
  4. import android.content.Context;  
  5. import android.content.Intent;  
  6. import android.util.Log;  
  7.    
  8. public class HelloBroadReciever extends BroadcastReceiver {  
  9.   public HelloBroadReciever(){  
  10.     System.out.println("HelloBroadReciever");  
  11.   }  
  12.    
  13.   // 如果接收的事件发生  
  14.   @Override  
  15.   public void onReceive(Context context, Intent intent) {  
  16.    
  17.     // 对比Action决定输出什么信息  
  18.     if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {  
  19.      Log.i("HelloBroadReciever","SMS_RECEIVED !!!!!!!!!!!!!!!!!!!!!!!!!");  
  20.     }  
  21.     Log.i("HelloBroadReciever","onReceive**********");  
  22.   }  


原创粉丝点击