转自http://hualikejava.iteye.com/blog/1461383
1.常驻型广播
常驻型广播,当你的应用程序关闭了,如果有广播信息来,你写的广播接收器同样的能接受到,
他的注册方式就是在你的应用程序中的AndroidManifast.xml进行注册。通常说这种方式是静态注册
下面是配置例子
<!-- 桌面 -->
<receiver android:name=".widget.DeskWidgeWeather">
<meta-data android:name="android.appwidget.provider" android:resource="@xml/widget_weather_provider" />
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE"/>
<action android:name="action_weather"/>
</intent-filter>
</receiver>
2.非常驻型广播
当应用程序结束了,广播自然就没有了,比如你在activity中的onCreate或者onResume中注册广播接收器
在onDestory中卸载广播接收器。这样你的广播接收器就一个非常驻型的了。这种也叫动态注册。
比如写一个监听SDcard状态的广播接收器
SdcardStateChanageReceiver sdcardStateReceiver;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
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");
sdcardStateReceiver = new SdcardStateChanageReceiver();
registerReceiver(sdcardStateReceiver,filter);
}
@Override
protected void onDestroy(){
unregisterReceiver(sdcardStateReceiver);
}
class SdcardStateChanageReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent)
{
String state=android.os.Environment.getExternalStorageState();
System.out.println("SDCard 发生改变! 状态:"+state);
//checkSDCard();
}
public void checkSDCard(){
String state=android.os.Environment.getExternalStorageState();
System.out.println(state);
if(state.equals(android.os.Environment.MEDIA_REMOVED ) || state .equals(android.os.Environment.MEDIA_UNMOUNTED)){
System.out.println("SDCard 已卸载!");
}
}
}