I'm trying to lower the memory usage of my app, and I noticed most of it is caused by the activities' backgrounds: in XHDPI, 720*1280*4 = 3.6Mbytes each, and Android doesn't seem to release them as soon as they're not in use anymore.
Is there any way to tell Android to load certain resource images as RGB 565
instead of RGB 8888
in order to save some memory on those larger images without alpha channel ?
I know this can be done programmatically, but I was wondering if this can also be done with images and backgrounds used in the activities' layouts or with setBackgroundResource()
.
You can do it like this:
protected void onCreate(Bundle savedInstanceState)
{
setContentView(R.layout.high_scores);
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inPreferredConfig = Config.RGB_565;
BitmapDrawable highScoresBg = BitmapFactory.decodeResource(getResources(), R.drawable.achievements, opts);
findViewById(R.id.high_scores_root).setBackgroundDrawable(highScoresBg);
Pixels of your image will be stored on 2 bytes, instead of 4 when using ARGB_8888. 50% saved memory, but of course less quality.
This article tells us that on Android < 2.3 the images are in RGB_565 by default. However, if the image has alpha channel (PNG for instance), it will be loaded in ARGB_8888. On Android >= 2.3 all the images are loaded in ARGB_8888 by default.
There's currently no way to flag a resource to be RGB_565.
The best you could do, would be to provide a subsequent data file which maps your image files to desired in-memory formats. At load time, you can check each resource ID against the file to determine if you'd like to set the BitmapFactory options to 565 or 8888.
A similar process is used by most applications that pull down image data. For example, some JPG images which have a small resolution, are assumed to be thumbnails, and loaded into memory using the 565 path. Where full-screen JPGs are allowed to load into memory as 8888.
Basically, you'll always need some level of logic in your app to set the BitmapOptions accordingly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With