Android uses LruCache to cache pictures

Source: Internet
Author: User

loading a picture in your application's UI interface is a simple matter, but when you need to load a lot of pictures on the interface, things get complicated. In many cases (such as using widgets such as ListView, GridView, or Viewpager), images displayed on the screen can be continuously increased through events such as sliding screens, eventually resulting in OOM. In order to ensure that the memory usage is always maintained in a reasonable range, the image removed from the screen is usually recycled. The garbage collector will also assume that you no longer have a reference to these pictures to perform GC operations on them. Using this approach to solve the problem is very good, but in order to allow the program to run quickly, in the interface to quickly load the picture, you have to consider that some pictures are recycled, the user then re-slide it into the screen this situation. It is a performance bottleneck to reload the images that have just been loaded, and you need to find a way to avoid the situation.

this time, the use of memory caching technology can be a good solution to this problem, it allows the component to quickly reload and process the picture. Let's take a look at how memory caching technology can be used to cache images so that your application will be able to improve responsiveness and fluency when loading many images. Memory Caching technology provides quick access to images that consume valuable memory from applications. The most core of these classes is LruCache (this class is provided in the ANDROID-SUPPORT-V4 package). This class is ideal for caching images, and its main algorithm is to store recently used objects in linkedhashmap with strong references, and to remove the least recently used objects from memory before the cached value reaches a predetermined value.

in the past, we often used an implementation of a very popular memory caching technique, either soft or weak (SoftReference or weakreference). However, this is no longer recommended because, starting with Android 2.3 (API Level 9), the garbage collector is more inclined to reclaim objects holding soft or weak references, which makes soft and weak references less reliable. In addition, in Android 3.0 (API level 11), image data is stored in local memory, so it cannot be released in a predictable way, which poses a potential risk of memory overflow and crash of the application. To be able to choose a suitable cache size for LruCache, there are several factors that should be taken into account, such as:

    1. How much memory can your device allocate for each application?
    2. How many pictures can I display on the device screen at a time?
    3. How many images need to be preloaded because it's possible to be displayed on the screen soon?
    4. What is the screen size and resolution of your device? An ultra-high-resolution device, such as a Galaxy nexus, requires more cache space than a lower-resolution device, such as a Nexus S, when holding the same number of images.
    5. can you maintain a balance between quantity and quality? In some cases, it is more effective to store multiple low-pixel images, while loads in the background to load high-resolution images.

And not a specified cache size can satisfy all applications, which is up to you. You should analyze the usage of the program's memory and then work out a suitable solution. A cache space that is too small can cause images to be released and reloaded frequently, which does not benefit. A cache space that is too large can still cause java.lang.OutOfMemory exceptions.

Here is an example of using LruCache to cache a picture:

PrivateLrucache<string, bitmap>Mmemorycache; @Overrideprotected voidonCreate (Bundle savedinstancestate) {//gets the maximum amount of free memory that is used to exceed this value to cause a OutOfMemory exception. //LRUCache passes through the constructor to the cache value, in kilobytes.     intMaxMemory = (int) (Runtime.getruntime (). MaxMemory ()/1024); //use 1/8 of the maximum available memory value as the size of the cache.     intCacheSize = MAXMEMORY/8; Mmemorycache=NewLrucache<string, bitmap>(cacheSize) {protected intsizeOf (String key, Bitmap Bitmap) {//Override this method to measure the size of each picture, returning the number of pictures by default.             returnBitmap.getbytecount ()/1024; }    };} Public voidAddbitmaptomemorycache (String key, Bitmap Bitmap) {if(Getbitmapfrommemcache (key) = =NULL) {mmemorycache.put (key, bitmap); }} PublicBitmap Getbitmapfrommemcache (String key) {returnMmemorycache.get (key);}

In this example, one-eighth of the memory allocated by the system to the application is used as the cache size. This will probably have 4 megabytes (32/8) of cache space in the high-profile handsets. A full-screen GridView is populated with 4 800x480 resolution images, which will probably take up 1.5 megabytes of space (800*480*4). Therefore, this cache size can store 2.5 pages of pictures. When a picture is loaded into the ImageView, it is first checked in the LruCache cache. If the corresponding key value is found, the ImageView is updated immediately, otherwise a background thread is opened to load the image.

 public  void  LoadBitmap (int   ResId, ImageView ImageView) { final<     /span> String imagekey = string.valueof (resId);  final  Bitmap Bitmap =     Getbitmapfrommemcache (ImageKey);  if  (bitmap! = null  ) {Imageview.setimagebitmap (bitmap);  else   {Imageview.setimageresource (R.D         Rawable.image_placeholder); Bitmapworkertask task  = new           Bitmapworkertask (ImageView);     Task.execute (RESID); } }

Bitmapworkertask also puts the key-value pairs of the newly loaded pictures into the cache.

class extends Asynctask<integer, Void, bitmap> {     //protected  Bitmap Doinbackground (Integer ... params) {         final Bitmap Bitmap = Decodesampledbitmapfromresource (                 getresources (), params[0], (+);         Addbitmaptomemorycache (string.valueof (params[0]), bitmap);          return bitmap;     } }

Android uses LruCache to cache pictures

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.