用Broadcast广播在activity之间、fragment之间、activity和fragment之间相互传数据

时间:2023-03-09 00:01:25
用Broadcast广播在activity之间、fragment之间、activity和fragment之间相互传数据

例如:A界面要收到B界面的更变信息

一、A界面注册广播

private static final String INTENT_BROADCAST = "android.intent.action.MEDICAL_BROADCAST";// 广播跳转意图

LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(getActivity());
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(INTENT_BROADCAST);
            BroadcastReceiver bordcastReceiver = new BroadcastReceiver() {

@Override
                public void onReceive(Context context, Intent intent) {
                      //信息处理

Toast.makeText(context, "信息更新", Toast.LENGTH_SHORT).show();

}
           };
  broadcastManager.registerReceiver(bordcastReceiver, intentFilter);

二、B界面发送广播通知A界面改变信息

Intent broadcast = new Intent(INTENT_BROADCASTS);

LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast);