Search code examples
androidmemory-leaksosmdroidmylocationoverlay

OsmDroid MyLocationNewOverlay.enableMyLocation() cause memory leak


There is a memory leak in my app that is using OsmDroid. After some search, I found the leak is caused by the MyLocationNewOverlay.enableMyLocation() method:

mMyLocationNewOverlay.enableMyLocation();

If I comment that line out, there will be no memory leak. I think I forgot to deregister the location listener at onPause() or OnStop(). So I try to deregister it at onPause() by using:

mMyLocationNewOverlay.disableMyLocation();

However, the leak still occurs. I even tried to remove the whole mMyLocationNewOverlay but it still doesn't work. I am wondering what is the proper way to deregister the location listener in OsmDroid and fix the memory leak?


Solution

  • Shortly after I posted the question, I found the solution myself. In short, the solution is whenever a new MyLocationNewOverlay is added, the old MyLocationNewOverlay must be disabled BEFORE removal by calling:

    MyLocationNewOverlay.disableMyLocation();
    MyLocationNewOverlay.disableFollowLocation(); // if you enabled this function on the overlay
    

    Simply removing the overlay wouldn't work because the callback is still holding the reference of the overlay.

    Of course, the best practice is to have only one MyLocationNewOverlay and manage the same (I made the mistake of adding a new one). I hope this will help someone with the same problem.