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

Source: Internet
Author: User
Tags hosting

http://blog.csdn.net/qqiabc521/article/details/20941273

Try not to use Setimagebitmap or Setimageresource or Bitmapfactory.decoderesource to set a larger picture,
Because these functions are finished decode, they end up with the Java layer's createbitmap, which consumes more memory.

Therefore, instead of using the Bitmapfactory.decodestream method first, create a bitmap, and then set it to ImageView source,
decodestream's greatest secret lies in its direct invocation of Jni>>nativedecodeasset () to complete decode,
No need to use Java layer CreateBitmap, thus saving the Java layer of space.
In addition, Decodestream directly take the picture to read the bytecode, not according to the machine's various resolutions to automatically adapt,
after using Decodestream, you need to hdpi and MDPI, LDPI configuration of the corresponding picture resources,

In addition, the following ways can help:
1. InputStream is = This.getresources (). Openrawresource (R.DRAWABLE.PIC1);
Bitmapfactory.options options=new bitmapfactory.options ();
Options.injustdecodebounds = false;
Options.insamplesize = 10; Width,hight is set to the original very
Bitmap BTP =bitmapfactory.decodestream (is,null,options);
2. if (!bmp.isrecycle ()) {
Bmp.recycle ()//Recover the memory occupied by the picture
System.GC ()//Alarm system timely recovery
}

Here's how:

Java code

  1. /**
  2. * Read pictures of local resources in the most memory-saving way
  3. * @param context
  4. * @param resId
  5. * @return
  6. */
  7. public static Bitmap Readbitmap (context context, int resId) {
  8. Bitmapfactory.options opt = new bitmapfactory.options ();
  9. Opt.inpreferredconfig = Bitmap.Config.RGB_565;
    1. Opt.inpurgeable = true;
    2. Opt.ininputshareable = true;
    3. Get a picture of a resource
    4. InputStream is = Context.getresources (). Openrawresource (ResId);
    5. Return Bitmapfactory.decodestream (is,null,opt);
    6. }

Workarounds for Android Memory overflow

Transferred from: Http://www.cppblog.com/iuranus/archive/2010/11/15/124394.html?opt=admin

When I put a picture on the simulator yesterday, gallery java.lang.OutOfMemoryError:bitmap size exceeds VM budget exception, the image size exceeds RAM memory.
Simulator RAM is relatively small, only 8 m of memory, when I put in a large number of pictures (about 100 more than K), the above reasons appear.
Since each picture was previously compressed, when placed into the bitmap, the size will become larger, resulting in more than RAM memory, the specific solution is as follows:

//solve the problem of loading picture memory overflow
//options save only the image size, Do not save picture to memory
bitmapfactory.options opts = new Bitmapfactory.options ();
//scale is difficult to scale in proportion to the prepared scale, and its value indicates a multiple of the scale, The SDK recommended that its value is 2 of the exponential value, the more the value of the general cause the picture is not clear
bitmap bmp = Null;
bmp = Bitmapfactory.decoderesource (Getresources (), mimageids[position],opts);

 1234 
 ...
  Recycle bmp.recycle (); 

Solved by the way above, but this is not the most perfect solution.

Through some understanding, learned as follows:

Optimize heap memory allocation for Dalvik virtual machines

For the Android platform, the Dalvik Java VM used by its hosting layer has many things to optimize for its current performance, such as we might consider manually interfering with GC processing in the development of some large-scale games or resource-consuming applications, using The Settargetheaputilization method provided by the Dalvik.system.VMRuntime class can enhance the processing efficiency of the program heap memory. Of course, we can refer to the specific principle of open source engineering, here we only say how to use: Private final static float target_heap_utilization = 0.75f; You can call Vmruntime.getruntime () when the program OnCreate. Settargetheaputilization (target_heap_utilization); Can.

Android heap memory can also define its own size

 1 
 for some Android projects, The main impact of the performance bottleneck is Android's own memory management mechanism, the current handset manufacturers are stingy with RAM, for the smoothness of the software is very sensitive to the impact of RAM on performance, in addition to optimizing the Dalvik virtual machine heap memory allocation, we can also force the definition of their own software memory size, We use the Dalvik.system.VMRuntime class provided by Dalvik to set the minimum heap memory as an example: 

Private final static int cwj_heap_size = 6* 1024* 1024;

Vmruntime.getruntime (). Setminimumheapsize (Cwj_heap_size); Sets the minimum heap memory size to 6MB. Of course, the memory crunch can also be handled by manually interfering with the GC.

Bitmap setting picture size to avoid memory overflow OutOfMemoryError optimization method
★android is easy to use when using bitmap memory overflow, reported the following error: Java.lang.OutOfMemoryError:bitmap size exceeds VM budget

The main addition is this paragraph:
Bitmapfactory.options Options = new Bitmapfactory.options ();
Options.insamplesize = 2;

EG1: (Take a picture by URI)
Private ImageView Preview;
Bitmapfactory.options Options = new Bitmapfactory.options ();
Options.insamplesize = 2;//Picture width is the original One-second, that is, the picture is the original One-fourth
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: (Through the path to the picture)
Private ImageView Preview;
Private String filename= "/sdcard/dcim/camera/2010-05-14 16.01.44.jpg";
Bitmapfactory.options Options = new Bitmapfactory.options ();
Options.insamplesize = 2;//Picture width is the original One-second, that is, the picture is the original One-fourth
Bitmap B = Bitmapfactory.decodefile (fileName, Options);
Preview.setimagebitmap (b);
Filepath.settext (FileName);

★android also has some performance-optimized methods:
First memory aspect, can refer to Android heap memory also can define size and optimize heap memory allocation of Dalvik virtual machine

On the underlying type, because Java has no actual pointers, the NDK is the way to do it with respect to sensitive operations. Android123 Tips Game Developers, this is more interesting is that Google launched the NDK may be to help game developers, such as OpenGL ES support significantly improved, local code to manipulate the graphical interface is necessary.

Graphical object optimization, here is to say that the bitmap object destruction on Android, you can use the Recycle () method to show the GC to reclaim a bitmap object, usually for a bitmap can be used in the following way, such as

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

Bitmapobject.recycle ();

At present, the system for animation support comparison of mental retardation for general application of the transition effect can be, but for the game general art may be accustomed to the GIF method of unified processing, the current Android system can only preview the first frame of GIF, Resources in the GIF89 format can be read in J2ME by threading and writing parsers themselves.

For most Android phones there are not too many physical keys that we may need to imagine to do with gesture recognition gesturedetector and gravity sensing to achieve control. In general, we also consider the noise reduction process for misoperation problems.

Android heap memory can also define its own size

For some large-scale Android projects or games in the algorithm processing is not a problem, the main impact of the performance bottleneck is Android's own memory management mechanism, the mobile phone manufacturers are stingy with RAM, for the smoothness of the software, the impact of RAM on performance is very sensitive, In addition to optimizing heap memory allocations for Dalvik virtual machines mentioned in the last Android development network, we can also enforce our own software's memory size, using the Dalvik.system.VMRuntime class provided by Dalvik to set the minimum heap memory as an example:

Private final static int cwj_heap_size = 6* 1024* 1024;

Vmruntime.getruntime (). Setminimumheapsize (Cwj_heap_size); Sets the minimum heap memory size to 6MB. Of course the memory crunch can also be handled by manually interfering with the GC, and we'll mention the application next time.

Optimize heap memory allocation for Dalvik virtual machines

for Android platforms, the Dalvik JAVAVM used by its hosting layer has many things to optimize for its current performance, such as the possibility of manually interfering with GC processing in the development of some large-scale games or resource-consuming applications, using The Settargetheaputilization method provided by the Dalvik.system.VMRuntime class can enhance the processing efficiency of the program heap memory. Of course, we can refer to the specific principle of open source engineering, here we only say how to use: Private final static floattarget_heap_utilization = 0.75f; You can call Vmruntime.getruntime () when the program OnCreate. Settargetheaputilization (target_heap_utilization); Can.

Introduce a memory algorithm that occupies a process.
The base class for working with images in Android is bitmap, as the name implies, bitmaps. The memory-hogging algorithm is as follows:
The width*height*config of the picture.
If config is set to argb_8888, then the config above is 4. A 480*320 picture takes up memory that is 480*320*4 byte.
Someone said the concept of 8M, in fact, by default, the Android process memory consumption of 16M, because bitmap he in addition to holding data in Java, the underlying C + + Skia graphics library will also hold a Skbitmap object, Therefore the general picture occupies memory recommended size should not exceed 8M. This can be adjusted, you can set the parameters when compiling the source code.

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

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.