Android Memory Overflow approach (java.lang.OutOfMemoryError:bitmap size exceeds VM budget exception)

Source: Internet
Author: User
Tags memory usage

Yesterday in the simulator to put the picture on the gallery, java.lang.OutOfMemoryError:bitmap size exceeds VM budget exception, the image size exceeds the RAM memory.
Simulator RAM is relatively small, only 8 m memory, when I put in a lot of pictures (each more than 100 k), on the above reasons.
Because each picture is previously compressed, when put into the bitmap, the size will become larger, resulting in excess RAM memory, the specific solution is as follows:
Solve the problem of loading a picture memory overflow
Options Save picture size only, do not save picture to memory
Bitmapfactory.options opts = new Bitmapfactory.options ();
Scaling, scaling is difficult to scale by the prepared scale, its value indicates the magnification of the scale, the SDK recommended its value is 2 of the exponential value, the value of the assembly resulting in the picture is not clear
Opts.insamplesize = 4;
Bitmap bmp = null;
BMP = Bitmapfactory.decoderesource (Getresources (), mimageids[position],opts);
...
Recovery
Bmp.recycle ();
Solved by the way above, but this is not the perfect solution.
Through some understanding, learned as follows:
Optimizing heap memory allocations for Dalvik virtual machines
For the Android platform, the Dalvik Java VM used by its hosting layer can be optimized for the present performance, such as we may consider manual interference GC processing in the development of some large 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 principles of open source Engineering, here we only say the use of the method: private final static float target_heap_utilization = 0.75f; Vmruntime.getruntime (). Settargetheaputilization (target_heap_utilization) can be invoked when the program is OnCreate. Can.
Android heap memory can also be defined by its own size
For some Android projects, the main impact of performance bottlenecks is Android's own memory management mechanism, the current mobile phone manufacturers are stingy with RAM, for software fluency, RAM is sensitive to performance, in addition to optimizing the Dalvik virtual machine heap memory allocation, We can also force the definition of the memory size of our own software, and 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); Set minimum heap memory to 6MB size. Of course, for memory crunch, it can be handled by a manual interference GC.
Bitmap set picture size, avoid memory overflow outofmemoryerror optimization method
It is easy to overflow memory when using bitmap in ★android, reported as 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 pictures 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 the memory overflow, but it simply changes the size of the picture 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);

The first project into the company met a more difficult customer, but finally dealt with the past. In the first project because the app loaded pictures, reports more, so often reported the error of memory overflow, it is a headache. But under project leader lead, basically be solved. Thank you for my leader,samuel.cai hard. Ha ha......
Here are some summary, PS: From my leader over there, and share with you, haha
1. When a project contains a large number of pictures, or the picture is too large, you may oom the
 
Method 1: , such as scaling down the picture   &NBSP
 
                Bitmapfactory.options Options = new Bitmapfactory.options ();
                Options.insamplesize = 4;

 
Method 2:  a soft reference to the picture, in a timely manner recyle () operation
 
                 softreference<bitmap> Bitmap;
                bitmap = new Softreference<bitmap> (PBITMAP);
    if (bitmap!= null) {
 
             if (bitmap.get ()!= null &&!bitmap.get (). isrecycled ()) {
                 bitmap.get (). Recycle ();
                bitmap = null;
           }
       }


Method 3: To design and encode the complicated listview:
1. Attention to reuse adapter inside the Convertview and holder mechanism of use-----Reference: API Demo list 14. Efficient Adapter

Public View GetView (int position, View Convertview, ViewGroup parent) {
if (Convertview = = null) {
v = minflater.inflate (resource, parent, false);

Final int[] to = mTo;
Final int count = To.length;
Final view[] holder = new View[count];

for (int i = 0; i < count; i++) {
Holder[i] = V.findviewbyid (To[i]);
}

V.settag (holder);
} else {



2. The above method attempt has not been successful, available lazy loading data-----Reference: API Demo List 13


Method 4: Single page, the screen switch n times after OOM
1. Look at the layout of the page there are no big pictures, such as the background picture. Remove the related settings in the XML, and change the background image in the program (in the OnCreate () method):
drawable bg = getresources (). getdrawable (r.drawable.bg);
Xxx.setbackgrounddrawable (RLADDETAILONE_BG);
Note In activity destory, bg.setcallback (null); Prevent activity from being released in a timely manner


2. Similar to the above method, directly load the XML configuration file into a View and then put in a container, and then directly call This.setcontentview (view view);

Avoid repeated loading of XML



Method 5: Use as little code as possible during page transitions, such as repeating calls to databases, reusing objects, and so on ...

Method 6:android Heap Memory can also define its own size and optimize heap memory allocations for Dalvik virtual machines

Note If you use this method: project build target can only select <= 2.2, otherwise the compilation will not pass. So it's not recommended in this way

Private final static int cwj_heap_size= 6*1024*1024;
Private final static float target_heap_utilization = 0.75f;
Vmruntime.getruntime (). Setminimumheapsize (Cwj_heap_size);
Vmruntime.getruntime (). Settargetheaputilization (target_heap_utilization);

Author "This second does not give up

An analysis of the Android memory overflow problem

Www.diybl.com Time: 2012-01-11 Author: Network editor: Hawk click: 36 [Comments]

-

-

In the most recent project, memory has been growing, but do not know what is the problem, resulting in memory overflow, on the Internet to see such a memory analysis and management of the article, to solve some of the problems, feeling this article is not bad, reprint to my blog, I hope to help. If there is a bad place to leave a message, and then we continue to improve the memory leak problem, for everyone will be helpful, hehe

I. Overview 1

Second, Android (Java) common in the memory leak-prone code 1

(i) Query database does not close cursor 2

(ii) When constructing adapter, no cached Convertview 3 is used

(iii) recycle () Bitmap object is not invoked when used () free memory 4

(iv) Release of references to Objects 4

(e) Other 5

Three, memory monitoring tool DDMS--> Heap 5

Four, Memory analysis tool MAT (Memory Analyzer Tool) 7

(i) Generate. hprof File 7

(ii) Use MAT to import. hprof file 8

(iii) Use MAT view tool to analyze memory 8

I. Overview

Java programming is often easy to ignore, but itself a very important problem is the memory use of the problem. Android apps are written mostly in the Java language, so the problem is also in Android development. This article does not discuss Java programming issues, but rather the collation of such issues in Android, especially in application development.

Since the author's exposure to Android is not very long, please correct me if there are any improper descriptions.

Second, the common in Android (Java) is prone to memory leaks bad code

Android is mainly used in embedded devices, and embedded devices, due to some well-known constraints, usually do not have a high configuration, especially memory is relatively limited. If we write the code there are too many of the improper use of memory, will inevitably make our equipment running slow, or even panic. To enable the Android application to run safely and quickly, each Android application runs with a proprietary Dalvik virtual machine instance, which is hatched by the zygote service process, which means that each application runs in its own process. On the one hand, if the program in the process of running a memory leak problem, will only make their own process is killed, and will not affect other processes (if it is system_process and other systems process problems, it will cause the system to restart). On the other hand, Android allocates different memory usage caps for different types of processes, and if the application process uses more memory than the upper limit, it will be killed by the system as a memory leak. The memory caps that Android allocates to the application process are as follows:

Location:/android_source/system/core/rootdir/init.rc part of script

# Define The Oom_adj values for the classes of processes which can be

# Killed by the kernel. These are are used in Activitymanagerservice.

SetProp ro. Foreground_app_adj 0

SetProp ro. Visible_app_adj 1

SetProp ro. Secondary_server_adj 2

SetProp ro. Backup_app_adj 2

SetProp ro. Home_app_adj 4

SetProp ro. Hidden_app_min_adj 7

SetProp ro. Content_provider_adj 14

SetProp ro. Empty_app_adj 15

# Define the memory thresholds at which above process classes would

# be killed. These are numbers are in pages (4k).

SetProp ro. Foreground_app_mem 1536

SetProp ro. Visible_app_mem 2048

SetProp ro. Secondary_server_mem 4096

SetProp ro. Backup_app_mem 4096

SetProp ro. Home_app_mem 4096

SetProp ro. Hidden_app_mem 5120

SetProp ro. Content_provider_mem 5632

SetProp ro. Empty_app_mem 6144

# Write value must is consistent with the above properties.

# The driver only supports 6 slots, so we have home_app at the

# Same memory level as services.

Write/sys/module/lowmemorykiller/parameters/adj 0,1,2,7,14,15

Write/proc/sys/vm/overcommit_memory 1

Write/proc/sys/vm/min_free_order_shift 4

Write/sys/module/lowmemorykiller/parameters/minfree 1536,2048,4096,5120,5632,6144

# Set init its forked children ' s oom_adj.

Write/proc/1/oom_adj-16

Because our applications can use limited memory, we need to pay special attention to memory usage issues when writing code. The following are some common memory usage irregularities.

(i) The query database does not have a closed cursor

Describe:

The operation of the query database is often done in the program, but there is often no shutdown after the cursor is used. If our query result set is relatively small, the memory consumption is not easy to find, only in the case of a large number of times to reproduce the memory problem, which will give future testing and troubleshooting problems and risks.

Sample code:

Cursor Cursor = Getcontentresolver (). Query (URI ...);

if (Cursor.movetonext ()) {

... ...

}

To fix the sample code:

Cursor Cursor = null;

try {

cursor = Getcontentresolver (). Query (URI ...);

if (cursor!= null && cursor.movetonext ()) {

... ...

}

finally {

if (cursor!= null) {

try {

Cursor.close ();

catch (Exception e) {

Ignore this

}

}

}

(ii) When constructing adapter, no cached Convertview is used

Describe:

Taking the baseadapter of tectonic ListView as an example, the method was improved in Baseadapter:

Public View GetView (int position, View Convertview, ViewGroup parent)

To provide ListView with the View object that each item requires. Initially ListView will instantiate a certain number of view objects from the Baseadapter based on the current screen layout, and ListView will cache the view objects. When the ListView is scrolled up, the View object originally located at the top of the list item is reclaimed and then used to construct the newly appearing bottom list item. This construction process is done by the GetView () method, and the second parameter view of GetView () is the view object of the cached list item (the cache does not have a view object when it is initialized Convertview is null )。

It can be seen that if we do not use Convertview, but each time in the GetView () to instantiate a view object, that is, waste resources and waste of time, will also make the memory footprint more and more big. ListView the procedure for retrieving the View object of the list item to view:

Android.widget.AbsListView.java--> void Addscrapview (View scrap) method.

Sample code:

Public View GetView (int position, View Convertview, ViewGroup parent) {

View view = new Xxx (...);

... ...

return view;

}

To fix the sample code:

Public View GetView (int position, View Convertview, ViewGroup parent) {

View view = null;

if (Convertview!= null) {

view = Convertview;

Populate (view, GetItem (position));

...

} else {

view = new Xxx (...);

...

}

return view;

}

(iii) Bitmap Object recycle () free memory when not in use

Describe:

Sometimes we do things manually.

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.