Android Development #9: Passing Values Using LocalBroadcastManager

First posted on 11/09/2014

Sometimes, we would want to go back to a fragment from another Activity. We can use interface for this matter, but what if the Fragment where we left is from a drawer activity or tab activity? I've been trying to find a better way to do this, and it turns out using LocalBroadcastManager is much simpler than I have thought. If any of you readers have any better idea, please share :)

Fragment:

public class DemoFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        ...

        // Broadcast message from NextActivity to this fragment
        IntentFilter intentFilter = new IntentFilter();
        // Add intent tag for our broadcast message
        intentFilter.addAction("SomeTagHere");
        // Register broadcast
        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(
                mUpdateUIReceiver, intentFilter);

        ...
  }

    private BroadcastReceiver mUpdateUIReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent data) {
         // Receive message via intent tag
            if(data.getAction().equalsIgnoreCase("SomeTagHere")) {
                Log.d(TAG, "data from NextActivity= "+data.getStringExtra("next_activity"));
            }
        }
    };

    // Unregister in onDestroy instead of onPause because of Fragment lifecycle
    // SO related question bit.ly/1qIlbng 
    @Override
    public void onDestroy() {
        super.onDestroy();
        LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mUpdateUIReceiver);
    }

    @Override
    public void onClick(View view) {
        Intent i = new Intent(getActivity(), NextActivity.class);
      i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(i);
  }
}

In a Activity:

public class NextActivity extends FragmentActivity {

   ...

    @Override
    public void onClick(View view) {

       // Set intent tag to pass across the app
        Intent i = new Intent("SomeTagHere");
        i.putExtra("next_activity", "I like to touch myself");
        LocalBroadcastManager.getInstance(this).sendBroadcast(i); // send broadcast
        finish();
    }
}
Show Comments

Get the latest posts delivered right to your inbox.