0

I have a Fragment with a ListView and a BroadcastReceiver that updates the ListView when new data arrives. The Fragments life is controlled by a ViewPager.

In regard to where to (un)register the BroadcastReceiver, I found several places suggesting to do it in

onResume():

refreshReceiver = new RefreshReceiver();
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(
        refreshReceiver,
        refreshIntentFilter);

onPause():

LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(refreshReceiver);

However, this does not work properly. When I long-press the home button to get to the Recent apps screen, onPause() is called. When new information comes in while I'm on Recent apps, the ListView misses the update and shows old information after I go back there.

Now I was thinking about moving the unregistering to the onStop() method (or even in onDestroy()), but is that guaranteed to be called when the fragment is destroyed? I was worried because if the BroadcastManager holds a reference to the BroadcastReceiver and that in turn holds a reference to the Fragment, it would be quite a serious memory leak.

Community
  • 1
  • 1
AndreKR
  • 32,613
  • 18
  • 106
  • 168

2 Answers2

0

if you don't need receiver, then unregister it. if you use it only in that fragment, you may consider unregistering it onViewDestroyed().

Alpha
  • 1,754
  • 3
  • 21
  • 39
0

According this answer , if your fragment is single and not in pager you can un/register LBM in :

@Override
public void onResume() {
    super.onResume();
    LocalBroadcastManager.getInstance(getActivity()).registerReceiver(
            broadcast_manager, new IntentFilter("filter"));
}

@Override
public void onPause() {
    super.onPause();
    LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(broadcast_manager);
}

Else you need to find out when fragment is visible then register LBM.

through this:

public class MyFragment extends Fragment {
  @Override
  public void setMenuVisibility(final boolean visible) {
      super.setMenuVisibility(visible);
      if (visible) {
          // Register LBM
      }
   }
 // ...
}

you can register LBM in fragment

Community
  • 1
  • 1
Saeid
  • 2,261
  • 4
  • 27
  • 59