When registering code, you can write the broadcast receiver as an internal class in the Activity, or you can rewrite a class inherited from BroadCastReceiver, which needs to be registered with code (registered broadcast can be written in any place, only registered broadcast receivers can receive it) Corresponding broadcast), such as registering broadcast receivers in onCreate or onResume in Activity, and canceling broadcast receivers in onDestory, this registration method is also called dynamic registration. This method can be understood as the broadcast registered through the code is associated with the registrant.
Similarly, first create a broadcast receiver such as MyReceiver03
Override the onCreate method, dynamically register MyReceiver03, add the action (same channel) attribute to the intent filter, and add the MyReceiver03 object and intent filter through the registerReceiver method.
During dynamic registration, in order to save system resources and prevent broadcast receivers from monitoring all the time, you can log out. Override the onDestroy() method to unregister MyReceiver03 through unregisterReceiver
On exit, log out of MyReceiver03
The core code is as follows:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 动态注册广播3 MyReceiver03
// 获得 MyReceiver03的对象
myReceiver03 = new MyReceiver03();
// 创建意图过滤器
IntentFilter intentFilter = new IntentFilter();
// 向意图过滤器中添加action属性
String action = MY_ACTION;
intentFilter.addAction(action);
// 动态注册
registerReceiver(myReceiver03,intentFilter);
}
// Activity销毁时,注销广播
@Override
protected void onDestroy() {
super.onDestroy();
// 注销
unregisterReceiver(myReceiver03);
Toast.makeText(this,"myReceiver03广播被注销了",Toast.LENGTH_SHORT).show();
}