Analysis of Android development optimization: Memory Optimization for Bitmap

Source: Internet
Author: User

1) reclaim the Bitmap memory in time

The Bitmap class has a recycle () method. The method name indicates recycling. Here I have doubts. The Android system has its own garbage collection mechanism, which can occasionally recycle unused memory space, including Bitmap space. So why do we still need this method?

The construction methods of the Bitmap class are private, so developers cannot create a Bitmap object directly. They can only instantiate a Bitmap through various static methods of the BitmapFactory class. By carefully checking the source code of BitmapFactory, we can see that the generated Bitmap object is ultimately implemented through the JNI call method. Therefore, after loading Bitmap into the memory, it contains two parts of the memory area. To put it simply, some are Java and some are C. This Bitmap object is allocated by the Java part, and will be automatically recycled when it is not used. However, the corresponding C-available memory area cannot be recycled directly by virtual machines, this can only call underlying functions for release. Therefore, you need to call the recycle () method to release part C memory. From the source code of the Bitmap class, we can see that the recycle () method indeed calls the JNI method.

If recycle () is not called, will there be Memory leakage? No. Every Android application runs in an independent process and has independent memory. If the entire process is killed by the application itself or the system, the memory will be released, of course, it also includes part C memory.

Android is very complicated in process management. To put it simply, the process of the Android system is divided into several levels. The system will kill some low-priority processes with insufficient memory to provide sufficient memory space for other processes. In the actual project development Process, some developers use Process when exiting the program. killProcess (Process. myPid () method to kill your process, but some applications only use to call Activity. close all the activities by using the finish () method.

Experience Sharing:

Users of Android phones may exit the entire application in two ways according to their habits: one is to press the Home Key to directly return to the desktop; the other is to exit the program from the application exit button or press the Back key. From the system perspective, what are the differences between the two methods? Press the Home key and the application is not closed, but a background application. Press the Back key. Generally, the application is closed, but the process is not killed. Instead, it becomes an empty process (the program itself does not take into account the special process of exit ).

The Android system has done a lot of process management work, which can meet users' needs. It is recommended that you do not need to manually kill the process in which the application exits. The Process Management of the application itself can be handled by the Android system. What applications need to do is to manage the memory of the program as much as possible.

Generally, if you can obtain the reference of a Bitmap object, you need to call the recycle () method of Bitmap in time to release the memory space occupied by Bitmap, instead of waiting for the Android system to release it.

The following is a sample code snippet for releasing Bitmap..

Copy codeThe Code is as follows: // first, judge whether it has been recycled.

If (bitmap! = Null &&! Bitmap. isRecycled ()){

// Recycle and set it to null

Bitmap. recycle ();

Bitmap = null;

}

System. gc ();

From the code above, we can see that bitmap. the recycle () method is used to reclaim the memory occupied by the Bitmap. Then, the bitmap is left empty and the System is used. gc () calls the system's Garbage Collector for recycling, which can notify the Garbage Collector to recycle it as soon as possible. It should be noted that calling System. gc () does not guarantee that the recycle process starts immediately, but only to speed up the collection.

How to call the recycle () method for recovery has been known, so when is it more appropriate to release the Bitmap memory? In general, if the Code no longer needs to use Bitmap objects, it can be released. After the memory is released, the Bitmap object cannot be used again. If you use it again, an exception is thrown. Therefore, you must ensure that it is released when it is no longer in use. For example, if Bitmap is used in an Activity, it can be recycled in the onStop () or onDestroy () method of the Activity.

2) Capture exceptions

Because Bitmap is a large memory user, in order to avoid Crash after the application encounters an OutOfMemory exception when allocating Bitmap memory, pay special attention to the code of instantiating Bitmap. Generally, the OutOfMemory exception must be captured in the code that instantiates Bitmap.

The following is a sample code.

Copy codeThe Code is as follows: Bitmap bitmap = null;

Try {

// Instantiate Bitmap

Bitmap = BitmapFactory. decodeFile (path );

} Catch (OutOfMemoryError e ){

//

}

If (bitmap = null ){

// If the instantiation fails, the default Bitmap object is returned.

Return defaultBitmapMap;

}

The OutOfMemory exception that may occur during the initialization of the Bitmap object is captured. If an OutOfMemory exception occurs, the application will not crash. Instead, a default Bitmap is obtained.

Experience Sharing:

Many developers will habitually capture exceptions directly in the code. However, for OutOfMemoryError, This is not captured. Because OutOfMemoryError is an Error rather than Exception. Here, we will just remind you to avoid writing error code and failing to capture OutOfMemoryError.

3) cache common Bitmap objects

Sometimes, you may need to use the same image multiple times in an Activity. For example, an Activity displays a list of user portraits. If you do not set an avatar, a default profile is displayed, which is in the resource file of the application.

If the preceding scenario is similar, the same Bitmap can be cached. If the image file is not cached, Bitmap is instantiated using the BitmapFactory class method, which is a different Bitmap object. Caching can avoid creating multiple Bitmap objects and avoiding memory waste.

Experience Sharing:

Web developers are familiar with the caching technology. In fact, cache technology is often used during Android application development. The cache here has two levels: hard disk cache and memory cache. For example, when developing a network application, you can save some data obtained from the network to the SD card. Next time, you can directly read data from the SD card instead of from the network, this saves network traffic. This method is hard disk cache. For example, applications often use the same object and can cache it in the memory. When needed, they can directly read it from the memory. This method is the memory cache.

4) compress images

If the image pixel is too large and the BitmapFactory class method is used to instantiate Bitmap, an OutOfMemory exception will occur if the memory size exceeds 8 Mb. What should I do at this time? In this case, you can reduce the image size to reduce the memory usage during image loading and avoid exceptions.

You can use BitmapFactory. Options to set inSampleSize to reduce the image size. The property value inSampleSize indicates that the thumbnail size is one of several points of the original image size. If the value is 2, the width and height of the thumbnail are 1/2 of the original image, and the image size is 1/4 of the original size.

If you know that the image pixel is too large, you can reduce it. So how can we know that the image is too large?

Use BitmapFactory. after setting inJustDecodeBounds to true in Options, you can use decodeFile () and other methods without actually allocating space. That is, the decoded Bitmap is null, however, the width and height of the original image can be calculated, that is, options. outWidth and options. outHeight. With these two values, you can see if the image is too large.

Copy codeThe Code is as follows: BitmapFactory. Options opts = new BitmapFactory. Options ();

// Set inJustDecodeBounds to true

Opts. inJustDecodeBounds = true;

// Use the decodeFile method to obtain the image width and height.

BitmapFactory. decodeFile (path, opts );

// Print the width and height of the image

Log. d ("example", opts. outWidth + "," + opts. outHeight );

In actual projects, you can use the code above to first obtain the true width and height of the image, and then determine whether to scale down. If you do not need to zoom in, set inSampleSize to 1. To reduce the image size, calculate and set the value of inSampleSize dynamically to reduce the image size. Note that you should not forget to set opts. inJustDecodeBound back to false before you use the decodeFile () method of BitmapFactory to instantiate a Bitmap object. Otherwise, the bitmap object is null.

Experience Sharing:

If the source image of the program is a package resource or an image on your server, the size of the image can be adjusted by the developer. In general, you only need to pay attention to the image size, pay attention to the quality of the code and recycle Bitmap objects in time to avoid the occurrence of OutOfMemory exceptions.

If the program image is from the outside world, pay special attention to the occurrence of OutOfMemory. One is to reduce the size of the loaded image first, and the other is to capture exceptions to avoid 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.