简体   繁体   中英

Using BroadcastReceiver to pass Intent.EXTRAS

Main Question: Can I use a BroadcastReceiver to pass an intent with extras to an Activity?

Setup: I have a recorded date from a DatePicker fragment and I want to make sure that the Millis time is passed to another activity, but that activity is not immediately called from that Activity that contains that fragment

I tried using the following code in the activity with the datePicker Fragment:

Intent intent = new Intent().putExtra(EVENT_MILLIS, eventDateMillis); 
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

in the "receiving" activity:

@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstatnceState);
setContentView...
LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, new IntentFilter(EVENT_MILLIS));

and my call to initiate the receiver:

private BroadcastReceiver mReceiver = new BroadcastReceiver () {
@Override
public void onReceive(Content content, Intent intent) {
   setReceivedDate(intent.getLongExtra(EVENT_MILLIS,0));
}
}

Using Broadcast is not a good pattern and it looses efficiency of your app. Try using EventBus instead. It's easy to use with lower issues.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM