前言
LocalBroadcastManager 简单使用。
1.注册 【添加IntentFilter】
2.反注册
3.发广播
public class Main2Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
//注册
LocalBroadcastManager.getInstance(this).registerReceiver(new DemoBroadcastReceiver(), new IntentFilter(LOCAL_ACTION));
}
public void testNotification(View view) {
LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent("123"));
//发送广播
LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(LOCAL_ACTION));
}
private static final String LOCAL_ACTION = "BROADCAST_ACTION";
@Override
protected void onDestroy() {
super.onDestroy();
//取消注册
LocalBroadcastManager.getInstance(this).unregisterReceiver(new DemoBroadcastReceiver());
}
final class DemoBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent != null && LOCAL_ACTION.equals(intent.getAction())) {
Log.v("zxy", "222222222222222222");
}
}
}
}
官方引用 :https://developer.android.google.cn/jetpack/androidx/releases/localbroadcastmanager?hl=zh-cn