对BroadCastReceiver注册分为代码注册和清单文件注册,在活动中代码注册,当活动销毁时,BroadCastReceiver也会失去作用,而在清单文件中注册BroadCastReceiver则会一直存在,并起作用.
清单文件注册:
<receiver android:name=".MessageReceiver"> <intent-filter android:priority="1000"> <action android:name="android.provider.Telephony.SMS_RECEIVED"/> </intent-filter> </receiver>
代码注册:
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { } }; String action = "XXX"; IntentFilter intentFilter = new IntentFilter(action); registerReceiver(broadcastReceiver,intentFilter);
发送一条广播:
//与之前BroadCastReceiver注册的action相匹配 String action ="XXX"; Intent intent = new Intent(action); //发送无须广播,广播不能被终止 sendBroadcast(intent); //发送有序广播,广播根据优先级大小依次执行,可以用abortBroadcast终止,第三个参数时指定的广播接收者,当广播 //终止时它依然可以接受广播 sendOrderedBroadcast(intent,null,null,null,0,null,null);