Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android MapView v2 Context Issues and Memory Leak

I'm using MapView v2 in my application (not MapFragment) and it's causing a memory leak. The leak occurs when I pass the Activity context to the MapView constructor. If I pass the Application Context to the MapView constructor the memory leak goes away, however the MapView starts performing badly when I scroll the ScrollView it's in.

Here's a snapshot of where the leak is happening:

enter image description here

The relevant code in MapView is:

public class MapView extends android.widget.FrameLayout {
  private final com.google.android.gms.maps.MapView.b gD;

  static class b extends com.google.android.gms.dynamic.a<com.google.android.gms.maps.MapView.a> {
    private final android.content.Context mContext;
    // Here's the Context MapView is leaking

  }

  static class a implements com.google.android.gms.dynamic.LifecycleDelegate {
    // More stuff in here
  }
}

I've been messing with MapView for a few weeks now trying to get it to behave correctly in a ScrollView, to no avail. I'm about to give up on it.

Also, the snapshot() method that was recently added isn't an option because I have already tried it, and it doesn't give a reliable snapshot of the map. I have an open question on this here, and another related open question here and here, all of which have not been answered.

like image 828
Christopher Perry Avatar asked Dec 06 '25 20:12

Christopher Perry


2 Answers

In project that I was working we had similar issue. We were using mapView inside viewholder. Solution was to call onPause and then onDestroy on mapview. After that memory leaks were not observed.

like image 60
Jakub Szczygieł Avatar answered Dec 08 '25 11:12

Jakub Szczygieł


Possibily related to danielgomezrico's answer, there is a confirmed bug related to my location layer in MapView that leaks memory.

The workaround is to make sure you disable my location using GoogleMap.setMyLocationEnabled(false) before the map is destroyed. Also make sure to call other map view's lifecycle methods as well.

private MapView mMapView;
private GoogleMap mMap;

...

@Override
public void onResume() {
    super.onResume();
    mMapView.onResume();
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    mMapView.onSaveInstanceState(outState);
}

@Override
public void onPause() {
    super.onPause();
    mMapView.onPause();
}

@Override
public void onLowMemory() {
    super.onLowMemory();
    mMapView.onLowMemory();
}

@Override
public void onDestroy() {
    super.onDestroy();
    if (mMap != null) {
        mMap.setMyLocationEnabled(false);
    }
    mMapView.onDestroy();
}
like image 30
hidro Avatar answered Dec 08 '25 11:12

hidro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!