Android effectively solves the problem of memory overflow when loading large images

Source: Internet
Author: User

Do not use setimagebitmap, setimageresource, or bitmapfactory. decoderesource to set a large image,
Because after decode is completed, these functions are ultimately completed through the createbitmap on the Java layer, and more memory is required.

Therefore, use the bitmapfactory. decodestream method to create a bitmap and set it to the source of imageview,
The biggest secret of decodestream is that it directly calls JNI> nativedecodeasset () to complete decode,
You no longer need to use the createbitmap on the Java layer, thus saving the Java Layer Space.
If the configuration parameter of the part is added during reading, the load memory can be effectively reduced to prevent the throwing out of Memory exception.
In addition, decodestream reads bytecode directly from images and does not automatically adapt to various machine resolutions,
After decodestream is used, you need to configure the corresponding image resources in hdpi, mdpi, and ldpi,
Otherwise, the machine with different resolutions is of the same size (number of pixels), and the displayed size is incorrect.

In addition, the following methods are also helpful:
1. inputstream is = This. getresources (). openrawresource (R. drawable. pic1 );
Bitmapfactory. Options = new bitmapfactory. Options ();
Options. injustdecodebounds = false;
Options. insamplesize = 10; // width, hight is set to the original 10-minute-one
Bitmap BTP = bitmapfactory. decodestream (is, null, options );
2. If (! BMP. isrecycle ()){
BMP. Recycle () // reclaim the memory occupied by the image
System. GC () // remind the system to recycle it in time
}

Here is a method:

Java code

1 ./**
2. * read images of local resources in the most memory-saving manner
3. * @ Param Context
4. * @ Param resid
5. * @ return
6 .*/
7. Public static bitmap readbitmap (context, int resid ){
8. bitmapfactory. Options opt = new bitmapfactory. Options ();
9. Opt. inpreferredconfig = bitmap. config. rgb_565;
10. Opt. inpurgeable = true;
11. Opt. ininputretriable = true;
12. // obtain the resource Image
13. inputstream is = context. getresources (). openrawresource (resid );
14. Return bitmapfactory. decodestream (is, null, OPT );
15 .}

========================================================== ==========================================================
Android memory overflow Solution

From: http://www.cppblog.com/iuranus/archive/2010/11/15/124394.html? Opt = Admin

Java. Lang. outofmemoryerror: bitmap size exceeds VM budget exception occurred when the gallery was placed on the simulator yesterday. The image size exceeds the RAM memory.
The simulator Ram is relatively small and only has 8 MB of memory. When I put a large number of images (about 100 k each), the above problem occurs.
Since each image is compressed before, the size will increase when it is placed into bitmap, resulting in a memory exceeding the RAM. The specific solution is as follows:

// Solve the problem of memory overflow during image loading
// Options only saves the image size, not the image size to the memory
Bitmapfactory. Options opts = new bitmapfactory. Options ();
// Scale ratio. It is difficult to scale according to the prepared ratio. Its value indicates the zoom factor. In the SDK, it is recommended that its value be the exponential value of 2, the larger the value, the clearer the image.
Opts. insamplesize = 4;
Bitmap BMP = NULL;
BMP = bitmapfactory. decoderesource (getresources (), mimageids [position], opts );

...

// Recycle
BMP. Recycle ();

The above solution is used, but this is not the perfect solution.

For more information, see:

Optimize heap memory allocation of Dalvik virtual machines

For the Android platform, the Dalvik Java VM used by its hosting layer can be optimized from the current performance, for example, when developing large game or resource-consuming applications, we may consider Manual Interference with GC and use Dalvik. system. the settargetheaputilization method provided by the vmruntime class can improve the processing efficiency of the program heap memory. Of course, we can refer to the open-source project for specific principles. Here we only talk about the usage: Private Final Static float target_heap_utilization = 0.75f; vmruntime can be called during oncreate. getruntime (). settargetheaputilization (target_heap_utilization.

You can also customize the size of the android heap memory.

For some Android projects, the main cause of performance bottleneck is the memory management mechanism of Android. Currently, mobile phone manufacturers are stingy with Ram and are very sensitive to the impact of RAM on the Performance of software fluency, in addition to optimizing the heap memory allocation of the Dalvik virtual machine, we can also forcibly define the memory size of our software. We use the Dalvik provided by Dalvik. system. the following example uses the vmruntime class to set the minimum heap memory:

Private Final Static int cwj_heap_size = 6*1024*1024;

Vmruntime. getruntime (). setminimumheapsize (cwj_heap_size); // set the minimum heap memory size to 6 MB. Of course, for memory compression, manual GC interference can also be performed.

Bitmap sets the image size to avoid memory overflow outofmemoryerror.
★When bitmap is used in Android, memory overflow is very easy. The following error is reported: Java. Lang. outofmemoryerror: bitmap size exceeds VM budget

● This section is mainly added:
Bitmapfactory. Options = new bitmapfactory. Options ();
Options. insamplesize = 2;

● Eg1: (image retrieval through URI)
Private imageview preview;
Bitmapfactory. Options = new bitmapfactory. Options ();
Options. insamplesize = 2; // The image width and height are 1/2 of the original image, that is, the image is 1/4 of the original image.
Bitmap bitmap = bitmapfactory. decodestream (Cr
. Openinputstream (URI), null, options );
Preview. setimagebitmap (Bitmap );
The above code can optimize memory overflow, but it only changes the image size and does not completely resolve the memory overflow.
● Eg2: (image removal Through PATH)
Private imageview preview;
Private string filename = "/sdcard/dcim/camera/2010-05-14 16.01.44.jpg ";
Bitmapfactory. Options = new bitmapfactory. Options ();
Options. insamplesize = 2; // The image width and height are 1/2 of the original image, that is, the image is 1/4 of the original image.
Bitmap B = bitmapfactory. decodefile (filename, options );
Preview. setimagebitmap (B );
Filepath. settext (filename );

★There are also some Performance Optimization Methods for Android:
● In terms of memory, you can refer to the android heap memory and customize the size and optimize the heap memory allocation of the Dalvik virtual machine.

● In terms of basic types, Because Java does not have actual pointers, ndk must be used for sensitive operations. Android123 prompts game developers. What is interesting is that Google launches ndk to help game developers. For example, the support of OpenGL ES has been significantly improved, and it is necessary to operate the graphical interface of local code.

● Image object optimization. Here we will talk about the destruction of Bitmap objects on Android. You can use the recycle () method to display and let GC reclaim a bitmap object, the following method can be used for a non-bitmap, as shown in figure

If (bitmapobject. isrecycled () = false) // if not recycled
Bitmapobject. Recycle ();

● Currently, the system is relatively mentally retarded in supporting animation, which can be used for the interim Effect of regular applications. However, for games, normal artists may be used to unified GIF Processing, currently, the android system can only preview the first frame of a GIF. You can read Resources in the gif89 format by using a thread and a self-writing parser in j2s.

● For most Android phones without too many physical buttons, we may need to imagine a good gesture recognition gesturedetector and gravity sensing for control. We usually need to consider noise reduction for misoperation problems.

You can also customize the size of the android heap memory.

For some large Android projects or games, there is no problem in algorithm processing. The main cause of the performance bottleneck is the memory management mechanism of Android. Currently, mobile phone manufacturers are stingy with Ram, for the smoothness of software, Ram is very sensitive to the performance impact. Apart from the optimization of the heap memory allocation of the Dalvik Virtual Machine mentioned in the android Development Network last time, we can also forcibly define the memory size of our software. We use the Dalvik provided by Dalvik. system. the following example uses the vmruntime class to set the minimum heap memory:

Private Final Static int cwj_heap_size = 6*1024*1024;

Vmruntime. getruntime (). setminimumheapsize (cwj_heap_size); // set the minimum heap memory size to 6 MB. Of course, for memory compression, manual GC interference can also be performed. We will refer to the specific application next time.

Optimize heap memory allocation of Dalvik virtual machines

For the Android platform, the Dalvik JavaVM used by its hosting layer can be optimized from the current performance, for example, when developing large game or resource-consuming applications, we may consider Manual Interference with GC and use Dalvik. system. the settargetheaputilization method provided by the vmruntime class can improve the processing efficiency of the program heap memory. Of course, we can refer to the open-source project for specific principles. Here we only talk about the usage: Private Final Static floattarget_heap_utilization = 0.75f; vmruntime can be called during oncreate. getruntime (). settargetheaputilization (target_heap_utilization.

 

 

Introduce the memory algorithm used by a process.
In Android, the basic class for processing images is bitmap, which, as its name suggests, is bitmap. The memory usage algorithm is as follows:
The width * height * config of the image.
If config is set to argb_8888, the above config is 4. The memory occupied by a 480*320 image is 480*320*4 bytes.
Some people mentioned above the 8 m concept. In fact, by default, the memory usage of the android process is 16 m, because bitmap not only holds data in Java, the skia graphics library of the underlying C ++ will also hold a skbitmap object. Therefore, the recommended size of images in memory should not exceed 8 Mb. This can be adjusted, and parameters can be set during source code compilation.

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.