[mono-android] Memory Leak with Background Image

Jonathan Pryor jonp at xamarin.com
Tue Jan 24 20:14:38 UTC 2012


On Jan 23, 2012, at 6:19 AM, subsembly wrote:
> it seems that bitmap images attached as background drawables are never released.

They're released, they're just not released soon enough. Hopefully this will provide some background and clarification:

	http://docs.xamarin.com/android/advanced_topics/garbage_collection#Helping_the_GC

If that doesn't help, please let me know how I can improve that.

In your specific case, the problem is that Mono for Android's GC hasn't executed, so after you rotate the screen a few times none of the previously created Activities have been collected, and all the Java-side memory won't be freed until the Mono for Android objects are collected.

The fix is to cause a GC by overriding Activity.OnDestroy():

	protected override void OnDestroy ()
	{
		base.OnDestroy ();
		GC.Collect ();
	}

When I add the above method to the Activity, I'm able to constantly rotate my phone without getting a crash, whereas before that change it would crash after 3 rotations.

 - Jon



More information about the Monodroid mailing list