Why to Cache Pictures:
(1) According to the specific device of the different Android system for each application allocated a fixed memory space supply use;
(2) The picture is a very memory resource file, if loading a picture in the interface is good to say, if you want to load a large number of pictures will exceed the system for the application allocated to the space of the oom abnormal, so that the program ran collapse;
2.LruCache:
Main algorithm principle: the most recently used objects are stored in the Linkedhashmap with strong applications, and the most recently used objects are removed from the buffer when the maximum cache value is reached;
3. Implementation steps:
(1) Create a buffer:
1. Declare the LruCache object, similar to map is also in the form of key-value pairs, where the key is using the int private Lrucache<integer, bitmap> bitmapcache = null; 2. Allocate memory space for LRUCache//2.1 first gets the maximum space allocated by the system to the application, in kilobytes, final int maxmemory = (int) (Runtime.getruntime (). MaxMemory ()/1024) //2.2 will apply the memory of 1/8 as the size of the buffer to instantiate the buffer object int cacheSize = Maxmemory/8;bitmapcache = new Lrucache<integer, bitmap> ( MaxMemory) {//2.3 Specifies the size of each item in the buffer, that is, the size of each picture, the default is the actual size, (in kilobytes) protected int sizeOf (Integer key, Bitmap Bitmap) {//the Cache size would be measured in kilobytes rather than//number of Items.return bitmap.getrowbytes () * Bitmap.getheight ()/ 1024;}};
(2) Put the resulting picture into the buffer in the method of loading the picture
Bitmapcache.put (Bitmapid, bitmap);
(3) When using bitmap to determine whether the buffer has a corresponding key value of the bitmap object, if there is a direct read, if not exist in the call to load the image method to obtain;
if (Bitmapcache.get (bitmapid)!=null) {bitmap = Bitmapcache.get (bitmapid); Iv.setimagebitmap (bitmap);} else{//Loading pictures According to the image loading method}
This article is from the "Androidcamera Summary" blog, please be sure to keep this source http://7183397.blog.51cto.com/7173397/1606933
android--using LRUCache to cache pictures