Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I release (forced, if necessary) 9-patch (NinePatchDrawable) from memory in Android?

Tags:

android

How Do You Force A NinePatchDrawable to release the BitMap bytes it parsed out of 'res'?


As an Android developer I face pressure to control memory utilization in my games.

I work to control memory utilization by releasing resources as quickly as I can after they are no longer used. To this end, I maintain a list of all loaded resources and purge / release them from memory as soon as I am done with them.

My application uses a number of different types of graphical resources

  • BitMap
  • BitMapDrawable
  • Drawable
  • NinePatchDrawable

How do I release these objects right now?

  • BitMap : I use the "recycle()" method
  • BitMapDrawable : I use the "getBitMap().recycle()" method
  • Drawable : I set these to null (not working)
  • NinePatchDrawable : I set these to null (not working)

What have you tried?

  • You cannot "getBitmap()" a NinePatchDrawable
  • You cannot convert a NinePatchDrawable to a BitMapDrawable (even if they are both Bitmap based Drawables)
  • There seems to be a way to parse the PNG yourself, feeding the bytes into NinePathDrawable yourself -- this might get me to a point where I can just "recycle()" the underlying BitMap myself, but that seems like I'm reinventing the wheel (http://code.google.com/p/android/issues/detail?id=13542)

My Current Rules:

  • Never use @drawable/ in XML
  • Never android:background in XML
  • Never android:src in XML
like image 761
Cory Trese Avatar asked Jun 13 '11 18:06

Cory Trese


1 Answers

To be able to use: @drawable/, android:background, android:src in xml, you can always use custom classes.

So instead of <ImageView android:src="@drawable/bg" /> you can use: <com.myPackage.CustomImageView android:src="@drawable/bg" />

Than in the CustomImageView in the constructor you can get the references to your xml attributes:

    
private Drawable bg2;
private Drawable bg1;
public void CustomImageView(Context context, Attrs attrs)
{
    super(context, attrs);

    // Use this to get references to your xml attributes
    int resourceId = attrs.getAttributeResourceValue("android", "src", 0);
    bg1 = getResources().getDrawable(resourceId);

    // Or for the 'background' attribute
    resourceid = attrs.getAttributeResourceValue("android", "background", 0);
    bg2 = getResources().getDrawable(resourceId);

    // Now you can recycle() your 'bg' whenever you're done
}

This way, you can extract references from your xml. And recycle() them when you think it's appropriate

like image 152
Entreco Avatar answered Sep 28 '22 08:09

Entreco