BroadcastReceiver不仅可以接收系统广播,也可接收自定义的广播
1.定义一个广播接收器
public class MyReceiver extends BroadcastReceiver
{
public MyReceiver()
{
Log.i(TAG,"MyReceiver");
}
//可用Intent的getAction()区分接收到的不同广播
@Override
public void onReceive(Context arg0, Intent arg1)
{
String action=intent.getAction();
//TO-DO LIST
}
}
2.发送广播,定义好action标志,用Intent发送
//实例化该BroadcastReceiver
MyReceiver mReceiver=new MyReceiver();
//设置唯一action,用Intent发送
Intent intent=new Intent();
intent.setAction(str);
sendBroadcast(intent);
3.注册只接收指定action的广播接收器
IntentFilter filter1=new IntentFilter();
filter1.addAction(str);
registerReceiver(mReceiver,filter1);
4.取消该广播接收器
unregisterReceiver(mReceiver);