1

I have a MapView that I use inside a fragment:

<com.google.android.gms.maps.MapView
    android:id="@+id/mapView"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"/>

Following the documentation I get the map view:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
   mapView = (MapView) view.findViewById(R.id.mapView);
   mapView.onCreate(savedInstanceState);
   mapView.getMapAsync(this);
   ...
}

And implement OnMapReadyCallback since my map is ready I want to register a customer listener that will add points to my map.

@Override
public void onMapReady(GoogleMap googleMap) {
    map = googleMap;

    // setup custom listener
    // this will call me back when there are points that
    // need to be added/removed from the map
    myPointService.registerListener(this);
    ...
}

And I want to stop listening when the mapview is not on the screen:

@Override
public void onPause() {
    super.onPause();
    mapView.onPause();

    // stop listener
    myPointService.unregisterListener(this);
}

The problem with that is when onResume() is called I am not longer listening.

I can re-register in onResume(), but I don't think I can be assured that a map is available. I also don't want to register twice, so I would need to check if a map is available and I am not already listening. IE when the activity is first initialized onCreateView() and onResume() might get called before onMapReady is called.

I can keep a flag to indicated if I have already setup my listener and check in both onMapReady() and onResume() if the listener has already been setup, and if not, set them up, and update the flag so the listener does not get setup more than once.

public void onMapReady(GoogleMap googleMap) {
    map = googleMap;

    // setup custom listener
    // this will call me back when there are points that
    // need to be added/removed from the map
    if (!mListenersRegistered) {
       myPointService.registerListener(this);
       mListenersRegistered = true;
    }
    ...
}

@Override
public void onResume() {
    super.onResume();
    mapView.onResume();

    // There is a change on map ready already set this up
    // so need to check before adding the listener.

    // also need to make sure that the GoogleMap has been initialized
    if (!mListenersRegistered && mMap != null) {
       myPointService.registerListener(this);
       mListenersRegistered = true;
    }
}

Setting up the map has changed to be async recently and since that has happened I have not seen any examples of how to handle this situation.

lostintranslation
  • 23,756
  • 50
  • 159
  • 262

0 Answers0