1.What is OOM? Why does it cause OOM?
answer:Out Of Memory(Memory overflow), we all know that the Android system will allocate an independent workspace for each APP, or assign a separate Dalvik virtual machine, so that each APP can run independently without affecting each other! Android will have a maximum memory limit for each Dalvik virtual machine. If the current memory occupied plus the memory resources we applied for exceed this limit, the system will throw an OOM error! In addition, don’t be confused with RAM here. In fact, the remaining memory in the current RAM is more than 1G, but OOM will still happen! Don't combine RAM (physical memory) with OOM! In addition, if there is insufficient RAM, it will kill the application, not just OOM! The maximum memory standard in Dalvik is different for different models, and you can call:
ActivityManager activityManager = (ActivityManager)(Context.ACTIVITY_SERVICE); ("HEHE","Maximum memory:" + ());
Get the normal maximum memory standard, or type directly on the command line:
adb shell getprop | grep
You can also open the system source code/system/ file and read the information in this part of the file to get:
=8m =192m =512m =0.75 =2m =8m
You can also try the machine you have~
Okay, let’s not talk about it. This is all about the occurrence of OOM problems, and then it’s about the memory management. But I’m a big guy and I can’t even chew on it now... Let’s take a look at some tips to avoid Bitmap OOM!
2. Summary of OOM tips caused by Bitmap
1) Adopt a low memory usage encoding method
Said in the previous sectionIn this class, we can set the inPreferredConfig property, the default is.ARGB_8888, we can modify it to.ARGB_4444ARGB_4444: Each pixel occupies four bits, that is, A=4, R=4, G=4, B=4, then one pixel point occupies 4+4+4+4=16 bits ARGB_8888: Each pixel occupies eight bits, that is, A=8, R=8, G=8, B=8, then one pixel point occupies 8+8+8+8=32 bits by default, that is, one pixel occupies 4 bytes!
2) Picture compression
Again, we passinSampleSizeSet the scaling multiple, such as writing 2, that is, the length and width become the original 1/2, and the picture is the original 1/4. If you do not scale, set it to 1! But we cannot simply compress it. After all, if this value is too small, the picture will be blurry, and we must avoid the stretching and deformation of the picture. Therefore, we need to calculate dynamically in the program, and the appropriate value of this inSampleSize, and there is another method in Options:inJustDecodeBounds, after setting this parameter to true, decodeFiel will not allocate memory space, but the length and width of the original image can be calculated and options are called.outWidth/outHeightGet the width and height of the picture, and then use a certain algorithm to get the appropriate inSampleSize. Thank you hereStreet GodThe code provided - excerpted from Hongyang blog!
public static int caculateInSampleSize( options, int reqWidth, int reqHeight) { int width = ; int height = ; int inSampleSize = 1; if (width > reqWidth || height > reqHeight) { int widthRadio = (width * 1.0f / reqWidth); int heightRadio = (height * 1.0f / reqHeight); inSampleSize = (widthRadio, heightRadio); } return inSampleSize; }
Then use the above method:
options = new (); = true; // If you set this property, remember to set the value to falseBitmap bitmap = null; bitmap = (url, options); = computeSampleSize(options,128,128); = .ARGB_4444; /* The following two fields need to be used in combination */ = true; = true; = false; try { bitmap = (url, options); } catch (OutOfMemoryError e) { (TAG, "OutOfMemoryError"); }
3. Recycle images in a timely manner
If a large number of Bitmap objects are referenced, and the application does not need to display all images at the same time. You can recycle Bitmap objects that are temporarily unused in time. For some scenarios that clearly know the usage of the image, you can actively recycle the recycle, such as the picture on the boot page, recycle it after use, frame animation, load one, draw one, and release one! Loading when using, and null or recycle when not displayed! For example: (0); However, in some cases, specific images will be repeatedly loaded, released, loaded, etc., which are inefficient...
4. Other methods
I have not used the following methods, you can check the relevant information by yourself:
1. Simple management of image resources through SoftReference reference
When using the image, first check whether the hashmap has softreference, whether the picture in the softreference is empty. If it is empty, load the picture into the softreference and add the hashmap. There is no need to explicitly process the recycling and release of images in the code, gc will automatically handle the release of resources. This method is simple and practical to handle, and can avoid the inefficiency of repeated loading and release of the former method to a certain extent. But it's not optimized enough.
Sample code:
private Map<String, SoftReference<Bitmap>> imageMap = new HashMap<String, SoftReference<Bitmap>>(); public Bitmap loadBitmap(final String imageUrl,final ImageCallBack imageCallBack) { SoftReference<Bitmap> reference = (imageUrl); if(reference != null) { if(() != null) { return (); } } final Handler handler = new Handler() { public void handleMessage(final msg) { //Add to cache Bitmap bitmap = (Bitmap); (imageUrl, new SoftReference<Bitmap>(bitmap)); if(imageCallBack != null) { (bitmap); } } }; new Thread(){ public void run() { Message message = (); = downloadBitmap(imageUrl); (message); } }.start(); return null ; } // Download pictures from the Internetprivate Bitmap downloadBitmap (String imageUrl) { Bitmap bitmap = null; try { bitmap = (new URL(imageUrl).openStream()); return bitmap ; } catch (Exception e) { (); return null; } } public interface ImageCallBack{ void getBitmap(Bitmap bitmap); }
+ sd cache method
Starting from Android 3.1, the official also provides LruCache for cache processing. When the size of the storage Image is greater than the value set by LruCache, the picture with the least usage in the near future will be recycled and the system will automatically release the memory!
Example of usage:
step:
1) To set the memory size of the cached image first, I set it to 1/8 of the mobile phone memory here. The way to obtain the mobile phone memory: int MAXMEMONRY = (int) (() .maxMemory() / 1024);
2) The key-value pairs in LruCache are URLs and corresponding pictures respectively
3) Rewrite a method called sizeOf, which returns the number of pictures.
private LruCache<String, Bitmap> mMemoryCache; private LruCacheUtils() { if (mMemoryCache == null) mMemoryCache = new LruCache<String, Bitmap>( MAXMEMONRY / 8) { @Override protected int sizeOf(String key, Bitmap bitmap) { // Rewrite this method to measure the size of each image, and the number of images is returned by default. return () * () / 1024; } @Override protected void entryRemoved(boolean evicted, String key, Bitmap oldValue, Bitmap newValue) { ("tag", "hard cache is full , push to soft cache"); } }; }
4) The following methods are to clear the cache, add pictures to the cache, get pictures from the cache, and remove them from the cache.
Removing and clearing caches is a must-do, because improper processing of image cache will cause memory overflow, so you must pay attention.
public void clearCache() { if (mMemoryCache != null) { if (() > 0) { ("CacheUtils", "() " + ()); (); ("CacheUtils", "()" + ()); } mMemoryCache = null; } } public synchronized void addBitmapToMemoryCache(String key, Bitmap bitmap) { if ((key) == null) { if (key != null && bitmap != null) (key, bitmap); } else (TAG, "the res is aready exits"); } public synchronized Bitmap getBitmapFromMemCache(String key) { Bitmap bm = (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 = (key); if (bm != null) (); } } }
This is all about this article about OOM problems caused by Bitmap. For more related Bitmap OOM content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!