该方法可以实现动态注册广播接受者
receiver = new ScreemRecevicer();
IntentFilter filter = new IntentFilter();
filter.addAction("android.intent.action.SCREEN_OFF");
filter.addAction("android.intent.action.SCREEN_ON");
registerReceiver(receiver, filter);
用法如上:一个在 服务中动态注册接受屏幕锁定和打开广播的案例
动态注册电话reciver接受电话广播:使用内部类注册广播
//服务中的onCreate()
public void onCreate() {
//TODO 自定义广播内部类
// TODO 自定义广播
private class OutPhone extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String phoneNum = getResultData();
String adress = getAdress(phoneNum);
getMyToast(adress);
}
}
// TODO 注册广播
OutPhone phone = new OutPhone();
IntentFilter filter = new IntentFilter();
filter.addAction("android.intent.action.NEW_OUTGOING_CALL");
registerReceiver(phone, filter);
super.onCreate();
}