Mono for Android - OutOfMemoryError

三世轮回 提交于 2019-12-22 14:05:48

问题


I am having problems finding a memory leak in my Mono for Android application. I believe I am following all best practices, outlined later, but I keep getting OutOfMemoryError after a consistent, reproducible number of run-throughs of an activity.

Using ddms on the emulator I can see that my app is consuming around 200 extra "data objects" and about 30kB of memory every time our ViewFlipper flips to the next page. We are also consuming other resources, but at a much lower rate.

I use the ViewFlipper a little unconventionally; it only flips in one direction, and remove the Views that have already been shown:

while (flipper.ChildCount > 2)
{
    flipper.RemoveViewAt(0);
}

I have taken great care to Dispose() of any references to any Views we have used, as described in this blog post. I use using religiously for all UI components (which automatically Dispose() the object at the end of the scope):

using (TextView questionView = header.FindViewById<TextView>(Resource.Id.question))
{
    questionView.Text = question.Text;
}

This does not seem to have any effect on the memory leak. I use the same pattern whenever I load Bitmaps (usually PNG files, less than 20kB in size), which I do quite frequently.

Update: I load bitmaps using an extension method:

public static Bitmap BitmapFromAsset(this Context context, String asset)
{
    Bitmap bitmap;
    using (Stream stream = context.Assets.Open(asset))
    {
        bitmap = BitmapFactory.DecodeStream(stream);
        stream.Close();
    }
    return bitmap;
}

The bitmaps are then used like this:

using (Bitmap b = this.BitmapFromAsset(path))
{
    imageView.SetImageBitmap(b);
}

Update: As Aranda suggests below, I use delegates, so this is a common pattern in my code:

using (View button = FindViewById(Resource.Id.button))
{
    button.Click += delegate
    {
        // do something
    };
}

Changing this so that I remove the handlers when the View is removed makes no difference in the leaking.

Update: Bug posted with Xamarin with example project.


回答1:


I had a slightly similar, and very hard to find issue (albiet on WP7, but it's still relevant as it's all .Net). Turned out I had attached some delegates to my GameScreen class from another class that didn't go out of scope. Make sure you are doing -= any attached events and delegates as well as losing the reference to the view instance.



来源:https://stackoverflow.com/questions/7331417/mono-for-android-outofmemoryerror

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