Memory optimization for bitmap in Android application development

Source: Internet
Author: User
Tags exit garbage collection

In Android apps, the most memory-intensive is the picture resource. And in the Android system, when reading bitmap bitmap, the stack size of the picture in the virtual machine is only 8M, and if it is exceeded, a OutOfMemory exception appears. So, for the memory optimization of the picture, it is the important content of the Android application development.

1 to timely recovery of bitmap memory

The bitmap class has a method recycle (), which can be seen from the method name to be recycled. Here is the question, the Android system has its own garbage collection mechanism, can be periodically recycled unused memory space, of course, including bitmap space. So why do we need this method?

Bitmap classes are constructed in private, so developers cannot directly create a bitmap object, and can only instantiate a bitmap through various static methods of the Bitmapfactory class. With a closer look at Bitmapfactory's source code, you can see that the resulting bitmap object is ultimately implemented through JNI invocation. So, after loading the bitmap into memory, it contains two parts of the memory area. To put it simply, part of the Java section is part of the C section. This bitmap object is allocated by the Java part, the system will automatically recycle when not in use, but the corresponding C available memory area, the virtual machine can not be directly recycled, this can only call the underlying function release. So you need to call the Recycle () method to free the C part of the memory. As you can see from the source code of the bitmap class, the Recycle () method does invoke the Jni method.

So if you don't call recycle (), is there a memory leak? And it's not. Every application of Android runs in a separate process, with a separate memory, and if the entire process is applied or the system kills, memory is freed, including, of course, the C part of the memory.

Android is very complex to manage the process. Simply put, the Android process is divided into several levels, and the system kills some low-priority processes in the event of insufficient memory to provide sufficient memory space for other processes. In the actual project development process, some developers will exit the program using Process.killprocess (Process.mypid ()) way to kill their own process, but some applications will only use the call Activity.finish () Method of shutting off all activity.

Experience Sharing:

Users of Android phones, depending on their habits, may be able to exit the entire application in two ways: by pressing the home key to go straight to the desktop, or by quitting the program from the application's exit button or by pressing the back key. So what's the difference between these two approaches from a system perspective? by pressing the Home key, the application is not closed, but is a background application. Press the back key, in general, the application shuts down, but the process is not killed, but it becomes an empty process (the program itself does not take into account the special handling of the exit).

The Android system has done a lot of process management, which can already meet the needs of users. Personally, the application does not need to manually kill its own process when exiting the application. For the process management of the application itself, it is up to the Android system to handle it. What the application needs to do is to do as much as possible the memory management of the program itself.

In general, if you can get a reference to a bitmap object, you need to call Bitmap's recycle () method in time to free up the memory space that the bitmap occupies, rather than wait for the Android system to release.

The following is a sample code fragment that releases bitmap.

First to determine if it has been recycled

if (bitmap!= null &&!bitmap.isrecycled ()) {

Recycle and set to NULL

Bitmap.recycle ();

bitmap = null;

}

System.GC ();

As you can see from the above code, the Bitmap.recycle () method is used to reclaim the memory occupied by the bitmap, and then the bitmap is empty, then the system's garbage collector is used to reclaim it using System.GC (), which notifies the garbage collector to recycle as soon as possible. It should be noted here that invoking System.GC () does not guarantee the immediate start of the recycle process, but only to expedite the arrival of the recovery.

How to invoke the Recycle () method for recycling has been understood, when the release of bitmap memory is more appropriate? In general, if the code no longer needs to use the bitmap object, it can be freed. After freeing the memory, the bitmap object can no longer be used, and if used again, an exception is thrown. So be sure to release when you are no longer in use. For example, if you are using bitmap in an activity, you can recycle it in the OnStop () or OnDestroy () method of the activity.

2) Catch exception

Because bitmap is to eat large memory, in order to avoid application in allocating bitmap memory when the OutOfMemory exception crash out, you need to pay special attention to instantiate the bitmap part of the code. In general, it is important to capture the OutOfMemory exception in the code that instantiates bitmap.

The following is a code example.

Bitmap Bitmap = null;

try {

Instantiation of Bitmap

Bitmap = bitmapfactory.decodefile (path);

catch (OutOfMemoryError e) {

//

}

if (bitmap = = null) {

If the instantiation fails to return the default bitmap object

return defaultbitmapmap;

}

The outofmemory exception that may occur during initialization of the bitmap object is captured here. If a OutOfMemory exception occurs, the application does not crash, but it gets a default bitmap graph.

Experience Sharing:

Many developers will habitually capture exception directly in their code. But for OutOfMemoryError, this is not a catch. Because OutOfMemoryError is an error, not a exception. Just make a reminder here, avoid the wrong code and catch OutOfMemoryError.

3 Cache Common Bitmap objects

Sometimes, you may need to use the same picture more than once in an activity. An activity, for example, displays a list of the user's avatars, and if the user does not set the avatar, a default avatar is displayed, which is located in the application's own resource file.

If you have a scenario like the one above, you can cache the same bitmap. If you do not cache, although you see the same picture file, but using the method of Bitmapfactory class to instantiate the bitmap, is a different bitmap object. Caching avoids creating a new number of bitmap objects to avoid wasting memory.

Experience Sharing:

Web developers are familiar with caching techniques. In fact, in the Android application development process, also often use caching technology. The cache mentioned here has two levels, one is the hard disk cache, the other is the memory cache. For example, in the development of network applications, some data obtained from the network can be saved to the SD card, the next time directly from the SD card read, and not read from the network, thereby saving network traffic. This way is the hard disk cache. For example, an application often uses the same object, or it can be cached in memory and read directly from memory when needed. This approach is the memory cache.

4) Compress picture

If the picture pixel is too large, in the process of instantiating bitmap using the method of Bitmapfactory class, the memory space greater than 8M is required, and the outofmemory exception must occur. What should we do at this time? If this is the case, you can shrink the picture to reduce the use of memory during the loading of the picture to avoid exceptions.

You can shrink the picture by using the Bitmapfactory.options setting insamplesize. The property value Insamplesize represents a fraction of the size of the thumbnail size of the original picture. That is, if the value is 2, the width and height of the extracted thumbnail are 1/2 of the original picture, and the picture is 1/4 of its original size.

If you know that the pixel of the picture is too large, you can shrink it. So how do you know the picture is too big?

Using Bitmapfactory.options to set Injustdecodebounds to True, and then using methods such as DecodeFile (), does not really allocate space, that is, the decoded bitmap is null, However, you can calculate the width and height of the original picture, i.e. Options.outwidth and options.outheight. With these two values, you can tell if the picture is too large.

Bitmapfactory.options opts = new Bitmapfactory.options ();

Set Injustdecodebounds to True

Opts.injustdecodebounds = true;

Using the DecodeFile method to get the width and height of the picture

Bitmapfactory.decodefile (path, opts);

Print out the width and height of the picture

LOG.D ("Example", Opts.outwidth + "," + opts.outheight);

In the actual project, you can take advantage of the above code to get the true width and height of the picture, and then determine if you need to run the shrink. If you do not need to shrink, set the insamplesize value to 1. If you need to zoom out, you can dynamically calculate and set the value of the insamplesize to shrink the picture. Note that you should not forget to set opts.injustdecodebound back to False before you instantiate the bitmap object with the next method, such as Bitmapfactory decodefile (). Otherwise, the bitmap object obtained is null.

Experience Sharing:

If the source of the program's pictures are the resources in the package, or the picture on their own server, the size of the picture is the developer can adjust, then generally speaking, only need to pay attention to the use of the picture not too large, and pay attention to the quality of the code, timely recovery of bitmap objects, Can avoid the occurrence of outofmemory anomalies.

If the picture of the program comes from outside, this time special attention should be paid to the occurrence of outofmemory. One is that if you load a larger picture, you need to shrink first, and the other is to catch the exception to avoid the program crash.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.