Broadcast Receiver有两种注册方式,一是静态注册,一是动态注册;二者在实现方法上不尽相同,使用场景也随之不同;
静态注册的Broadcat会从application启动开始就一直常驻监听,直到application消亡;
动态注册较之前者会比较灵活,可动态地在需要监听的地方加注册,但要注意在不需要时调用unregister,取消注册。
静态注册实现方法:
直接在AndroidManifest.xml中注册过滤器
<receiver android:name=".receiver.BootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
<intent-filter android:priority="1000" >
<action android:name="android.intent.action.MEDIA_MOUNTED" />
<data android:scheme="file" />
</intent-filter>
</receiver>
然后在BootReceiver.java监听类中处理监听结果
public class BootReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Log.e(TAG, "onReceive:"+intent.getAction());
// TODO Something
}
}
动态注册实现方法:
定义监听类
BroadcastReceiver alarmReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.e(TAG, intent.getAction());
if(intent.getAction().equals("com.android.deskclock.ALARM_ALERT")) {
//TODO
}
}
};
定义过滤器
IntentFilter filter = new IntentFilter();
// 闹钟响起时触发com.android.deskclock.ALARM_ALERT
filter.addAction("com.android.deskclock.ALARM_ALERT");
注册
registerReceiver(alarmReceiver, filter);
取消注册
unregisterReceiver(alarmReceiver);
其间注意是否需要在AndroidManifest.xml中添加相应的监听权限。