常驻型广播
当你的应用程序关闭了,如果有广播信息来,你写的广播接收器同样的能接收到,它的注册方式就是在你应用程序的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 中注销广播接收者。这样你的广播接收者就一个非常驻型的了,这种注册方式也叫动态注册。
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 已卸载!");
}
}
}
}