Search code examples
androidandroid-activityonactivityresult

Pass information to a paused activity to call a method (Not UI update)


Scenerio:

Activity A opens Activity B. Activity B has some filters based on which the content of Activity A will change. To reduce waiting time for the users, I want to notify Activity A to start fetching the content as soon as there is a change on Activity B.

What would be the best way to achieve this without changing activity's structure ?


Solution

  • Ended up using a LocalBroadcastManager. Register a LocalBroadCastManager in Activity A and send a message from Activity B. Unregister it upon exiting Activity A.

    In Activity A:

    LocalBroadcastManager.getInstance(this).registerReceiver(
      mMessageReceiver, new IntentFilter("CUSTOM-EVENT_NAME"));
    
    private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
          // process the message here
          String data = intent.getStringExtra("intent-key")
        }
    };
    

    In Activity B:

    Intent intent = new Intent("CUSTOM-EVENT_NAME");
    intent.putExtra("intent-key","data");
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);