Basic Android tutorial -- 8.2.2 OOM problems caused by Bitmap

Source: Internet
Author: User

Basic Android tutorial -- 8.2.2 OOM problems caused by Bitmap
Basic Android tutorial -- 8.2.2 OOM problems caused by Bitmap

Tags (separated by spaces): basic Android tutorial

This section introduces:

In the previous section, we have learned the basic usage of Bitmap. In this section, we will discuss the OOM problem of Bitmap,
We may have encountered this problem in actual development or the OOM problem caused by Bitmap. In this section, we
Let's learn about this topic ~ Understand what is OOM, why it causes OOM, and how Bitmap improves
OOM problems ~

1. What is OOM? Why does OOM occur?

A:Out Of Memory(Memory overflow), we all know that the Android system will allocate an independent workspace for each APP,
Or assign a single Dalvik virtual machine so that each APP can run independently without affecting each other! Android
The Dalvik virtual machine has a maximum memory limit. If the memory occupied currently exceeds this limit and the memory resource we applied for exceeds this limit
The system will throw an OOM error! In addition, do not confuse RAM here. The remaining memory in the real-time RAM is more than 1 GB, but OOM will still happen! Don't drag RAM (physical memory) and OOM together! In addition, if RAM is insufficient, the app is killed, not just OOM!
The maximum memory standard in the Dalvik varies with different models and can be called:

ActivityManager activityManager = (ActivityManager) context. getSystemService (Context. ACTIVITY_SERVICE); Log. e (HEHE, maximum memory: + activityManager. getMemoryClass ());

>
To obtain the normal maximum memory standard, or directly type in the command line:

adb shell getprop | grep dalvik.vm.heapgrowthlimit

You can also open the system source code/system/build. prop file and view the information in this part of the file:

dalvik.vm.heapstartsize=8mdalvik.vm.heapgrowthlimit=192mdalvik.vm.heapsize=512mdalvik.vm.heaptargetutilization=0.75dalvik.vm.heapminfree=2mdalvik.vm.heapmaxfree=8m

There are three points of attention: the initial size of heapstartsize heap memory, and the maximum heap size of heapgrowthlimit standard applications.
Memory size. heapsize indicates the maximum heap memory size of applications that use android: largeHeap!
I tried the normal maximum memory allocation standard for several models at hand:

You can also try your own machine ~
Okay, don't talk about it. Let's talk about the generation of OOM problems here, and then go to the memory management section, but it's a big one,
It's still inactive... Let's take a look at some tips to avoid Bitmap OOM!

2. OOM tips to avoid Bitmap 1) encoding with low memory usage

As mentioned in the previous sectionBitmapFactory. OptionsIn this class, we can set the inPreferredConfig attribute,
The default value isBitmap. Config. ARGB_8888, We can modify itBitmap. Config. ARGB_4444
Bitmap. config ARGB_4444: each pixel occupies four places, that is, A = 4, R = 4, G = 4, B = 4. Therefore, one pixel occupies 4 + 4 + 4 + 4 = 16 digits.
Bitmap. config ARGB_8888: each pixel occupies eight bits, that is, A = 8, R = 8, G = 8, and B = 8. Then A pixel occupies 8 + 8 + 8 + 8 = 32 bits.
By default, ARGB_8888 is used, that is, one pixel occupies 4 bytes!

2) Image Compression

BitmapFactory. Options.InSampleSizeSet the scaling factor, such as write 2, that is, the length and width change to the original 1/2, and the image is the original 1/4. If you do not scale it, set it to 1! But it cannot be compressed. After all, this value is too small.
The image will be blurred, and we need to calculate it dynamically in the program.
The appropriate value of inSampleSize, and Options has the following method:InJustDecodeBounds, Set this parameter
True, decodeFiel does not allocate memory space, but can calculate the length and width of the original image.
Options.OutWidth/OutHeightObtain the width and height of the image, and then use a certain algorithm to obtain the appropriate
InSampleSize. Thank you.JieshenProvided code -- from Hongyang blog!

    public static int caculateInSampleSize(BitmapFactory.Options options, int reqWidth,                                           int reqHeight) {        int width = options.outWidth;        int height = options.outHeight;        int inSampleSize = 1;        if (width > reqWidth || height > reqHeight) {            int widthRadio = Math.round(width * 1.0f / reqWidth);            int heightRadio = Math.round(height * 1.0f / reqHeight);            inSampleSize = Math.max(widthRadio, heightRadio);        }        return inSampleSize;    }

Then, use the following method:

BitmapFactory. options options = new BitmapFactory. options (); options. inJustDecodeBounds = true; // you must set this attribute to false. Bitmap bitmap = null; bitmap = BitmapFactory. decodeFile (url, options); options. inSampleSize = computeSampleSize (options, 128,128); options. inPreferredConfig = Bitmap. config. ARGB_4444;/* the following two fields need to be combined with */options. inPurgeable = true; options. ininputwritable able = true; options. inJustDecodeBounds = false; try {bitmap = BitmapFactory. decodeFile (url, options);} catch (OutOfMemoryError e) {Log. e (TAG, OutOfMemoryError );}
3. Timely Image Recovery

If a large number of Bitmap objects are referenced, the application does not need to display all images at the same time. Bitmap objects temporarily not used
Timely recovery. You can take the initiative to recycle some scenarios that clearly know the image usage, such as the images on the boot page, use
Recycle, Frame Animation, load one, draw one, and release one! Load during use. If not displayed, set null or recycle directly!
For example, imageView. setImageResource (0 );
However, in some cases, some images may be repeatedly loaded, released, reloaded, or inefficient...

4. Other Methods

I have never used the following methods. You can refer to the relevant information on your own:

1. Use SoftReference reference to manage image resources

Create a hashmap for SoftReference
When using an image, first check whether the hashmap has softreference and whether the image in softreference is empty,
If it is null, load the image to softreference and add hashmap.
You do not need to explicitly process image collection and release in the Code. gc automatically processes resource release.
This method is simple and practical to avoid the inefficiency of the previous method. But it is not optimized enough.

Sample Code:

Private Map
  
   
> ImageMap = new HashMap
   
    
> (); Public Bitmap loadBitmap (final String imageUrl, final ImageCallBack imageCallBack) {SoftReference
    
     
Reference = imageMap. get (imageUrl); if (reference! = Null) {if (reference. get ()! = Null) {return reference. get () ;}} final Handler handler = new Handler () {public void handleMessage (final android. OS. message msg) {// Add Bitmap bitmap = (Bitmap) msg to the cache. obj; imageMap. put (imageUrl, new SoftReference
     
      
(Bitmap); if (imageCallBack! = Null) {imageCallBack. getBitmap (bitmap) ;}}; new Thread () {public void run () {Message message = handler. obtainMessage (); message. obj = downloadBitmap (imageUrl); handler. sendMessage (message );}}. start (); return null;} // download the image private Bitmap downloadBitmap (String imageUrl) {Bitmap bitmap = null; try {bitmap = BitmapFactory. decodeStream (new URL (imageUrl ). openStream (); return bitmap;} catch (Exception e) {e. printStackTrace (); return null ;}} public interface ImageCallBack {void getBitmap (Bitmap bitmap );}
     
    
   
  
2. LruCache + sd cache Method

From Android 3.1, the official version also provides LruCache for cache processing. When the size of the stored Image is greater than LruCache
If this parameter is set, images with the least recent usage will be recycled and the system will automatically release the memory!

Example:
Steps:
1) first set the memory size of the cached image. Here I set it to 1/8 of the memory of the mobile phone,
Phone memory acquisition method: int MAXMEMONRY = (int) (Runtime. getRuntime (). maxMemory ()/1024 );
2) The key-value pairs in LruCache are URLs and corresponding images.
3) rewrite a method called sizeOf and return the number of images.

Private LruCache
  
   
MMemoryCache; private LruCacheUtils () {if (mMemoryCache = null) mMemoryCache = new LruCache
   
    
(MAXMEMONRY/8) {@ Override protected int sizeOf (String key, Bitmap bitmap) {// rewrite this method to measure the size of each image. By default, the number of images is returned. Return bitmap. getRowBytes () * bitmap. getHeight ()/1024;} @ Override protected void entryRemoved (boolean evicted, String key, Bitmap oldValue, Bitmap newValue) {Log. v (tag, hard cache is full, push to soft cache );}};}
   
  

4) The following methods are used to clear the cache, add images to the cache, retrieve images from the cache, and remove images from the cache.
It is necessary to remove and clear the cache. If the image cache is improperly processed, a memory overflow is reported.

Public void upload AchE () {if (mMemoryCache! = Null) {if (mMemoryCache. size ()> 0) {Log. d (CacheUtils, mMemoryCache. size () + mMemoryCache. size (); mMemoryCache. evictAll (); Log. d (CacheUtils, mMemoryCache. size () + mMemoryCache. size ();} mMemoryCache = null;} public synchronized void addBitmapToMemoryCache (String key, Bitmap bitmap) {if (mMemoryCache. get (key) = null) {if (key! = Null & bitmap! = Null) mMemoryCache. put (key, bitmap);} else Log. w (TAG, the res is aready exits);} public synchronized Bitmap getBitmapFromMemCache (String key) {Bitmap bm = mMemoryCache. get (key); if (key! = Null) {return bm;} return null;}/*** remove cache ** @ param key */public synchronized void removeImageCache (String key) {if (key! = Null) {if (mMemoryCache! = Null) {Bitmap bm = mMemoryCache. remove (key); if (bm! = Null) bm. recycle ();}}}

The above content is taken from-image cache memory cache technology LruCache, soft reference

Summary:

This section describes the cause of the OOM problem and summarizes some features provided on the Internet to avoid OOM caused by Bitmap.
Because the company's apps are map-type and rarely involve images, I have never encountered the OOM problem,
So I am not familiar with this ~ In the future, we will gradually struggle with the OOM problem in the memory management of advanced courses. Okay,
This section is here. Thank you ~

 

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.