Android 编程下两种方式注册广播的区别

常驻型广播

常驻型广播,当你的应用程序关闭了,如果有广播信息来,你写的广播接收器同样的能接收到,它的注册方式就是在你应用程序的AndroidManifast.xml 中进行注册,这种注册方式通常又被称作静态注册。这种方式可以理解为通过清单文件注册的广播是交给操作系统去处理的。示例代码如下:

<!-- 订阅开机结束广播 -->
<receiver android:name=".receiver.BootCompleteReceiver" >
  <intent-filter android:priority="1000" >
      <action android:name="android.intent.action.BOOT_COMPLETED" />
  </intent-filter>
</receiver>

非常驻型广播

非常驻型广播,当应用程序结束了,广播自然就没有了,比如在 Activity 中的 onCreate 或者 onResume 中注册广播接收者,在 onDestory 中注销广播接收者。这样你的广播接收者就一个非常驻型的了,这种注册方式也叫动态注册。这种方式可以理解为通过代码注册的广播是和注册者关联在一起的。比如写一个监听 SDcard 状态的广播接收者:

package cn.sunzn.mosecurity.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Environment;

public class SDcard extends Activity {
   SdcardStateChanageReceiver sdcardStateReceiver;

   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       sdcardStateReceiver = new SdcardStateChanageReceiver();
       IntentFilter filter = new IntentFilter();
       filter.addAction(Intent.ACTION_MEDIA_REMOVED);
       filter.addAction(Intent.ACTION_MEDIA_EJECT);
       filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
       filter.addDataScheme("file");
       registerReceiver(sdcardStateReceiver, filter);
   }

   protected void onDestroy() {
       unregisterReceiver(sdcardStateReceiver);
   }

   class SdcardStateChanageReceiver extends BroadcastReceiver {
       public void onReceive(Context context, Intent intent) {
           checkSDCard();
       }

       public void checkSDCard() {
           String state = Environment.getExternalStorageState();
           System.out.println(state);
           if (state.equals(Environment.MEDIA_REMOVED) || state.equals(Environment.MEDIA_UNMOUNTED)) {
               System.out.println("SDCard 已卸载!");
           }
       }
   }
}

 

posted @ 2013-02-13 19:49  sunzn  阅读(38545)  评论(4编辑  收藏  举报