android maps, markers and memory leaks

2019-02-15 02:36发布

问题:

I was reading the android docs http://developer.android.com/reference/com/google/android/gms/maps/MapFragment.html and I came across this sentence:

Any objects obtained from the GoogleMap is associated with the view. It's important to not hold on to objects (e.g. Marker) beyond the view's life. Otherwise it will cause a memory leak as the view cannot be released.

I don't fully understand that, and I'm not sure that it applies to me, but I just wanted to check: this only applies if the fragment is destroyed while the main view still exists, right? My map fragment is the only element in that layout's xml, so I assume that when the user navigates away, the marker objects (and everything else) get destroyed. Am I right, or is it the opposite?

回答1:

If you look at a fragments lifecycle you can see that the view may be destroyed while the fragment still lives. It can also recreate the view before the fragment is destroyed. This just means you should cleanup and create all markers in the onCreateView and onDestroyView callbacks instead. If you use those callbacks for marker manipulation you should be fine.