MapView v2 keeping Context around

家住魔仙堡 提交于 2019-12-04 02:07:55

Check if you are calling googleMap.setMyLocationEnabled(true) in your onMapReady() callback.

If you are then you should call googleMap.setMyLocationEnabled(false) in your onDestroy.

This worked for me:

@Override
    public void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
        if (mMap != null) {
            mMap.setMyLocationEnabled(false);
            mMap.clear();
        }
    }

Just to give another option as this solution didn't work for me.

I found this really useful thread where it propose some workarounds related to the memory leak in MapView:

https://github.com/googlesamples/android-play-location/issues/26

For me, the most interesting things from this thread (that worked for me) is:

1) Make sure to unregister your callbacks:

if (googleApiClient != null) {
        googleApiClient.unregisterConnectionCallbacks(this);
        googleApiClient.unregisterConnectionFailedListener(this);

        if (googleApiClient.isConnected()) {
                LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
        }

        googleApiClient.disconnect();
        googleApiClient = null;
 }

2) Use a WeakReference for LocationListener

public class WeakLocationListener implements LocationListener {

    private final WeakReference<LocationListener> locationListenerRef;

    public WeakLocationListener(@NonNull LocationListener locationListener) {
        locationListenerRef = new WeakReference<>(locationListener);
    }

    @Override
    public void onLocationChanged(android.location.Location location) {
        if (locationListenerRef.get() == null) {
            return;
        }
        locationListenerRef.get().onLocationChanged(location);
    }

}

Hope it helps!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!