BroadcastReceiver是一个系统级的监听器,它拥有自己的进程,只要存在与之匹配的Intent被广播出来,BroadcastReceiver就会被激发。
实现BroadcastReceiver只要重写onReceive(Context context, Intent intent),实现BroadcastReceiver有两种方法:
一、可以新建一个类去继承BroadcastReceiver,然后重写onReceive(Context context, Intent intent);
二、可以不用去新建一个类,直接在Activity里new BroadcastReceiver()时并重写onReceive(Context context, Intent intent);
private BroadcastReceiver broadCastReceiver=new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
}
};
当实现了BroadcastReceiver,接下来就是注册广播。注册也有两种方法:
一、在Activity里用代码指定(动态注册),调用BroadcastReceiver的Context的
registerReceiver(receiver, filter)方法指定。例如:
registerReceiver(broadCastReceiver,new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
二、在AndroidManifest.xml中配置:(静态声明)
<receiver android:name=“.BatteryReceiver”>
<intent-filter>
<action android:name=“android.intent.action.BATTERY_CHANGED”></action>
</intent-filter>
</receiver>
这样每次广播监听到与它匹配的Intent时,系统就创建广播实例,并自动触发onReceive()方法,当onReceive()方法执行完后,该广播实例就会被注销。广播实例可以参考手机电池电量。