天天看點

Android番外篇 LruCache緩存機制

一、引言

Android提供的使用了(Least Recently Used)近期最少使用算法的緩存類,内部基于LinkedHashMap實作。

  1. 構造時需要确定

    Cache

    的最大記憶體
//擷取程式最大可用記憶體
    int max = (int)Runtime.getRuntime().maxMemory();
    //取可用記憶體的四分之一做緩存
    int size = max/4;
           
  1. sizeOf()

    方法
在添加value到Cache時會被調用,需要傳回添加進資料的位元組大小
           
  1. 在 put(key,value)添加時先通過get(key)判斷是否已經有key對應的value存在

二、例子展示

(1)例子一

import android.util.LruCache;
/**
 * @author : Dumplings
 * @version : v1.0.0
 * @ClassName : MyLruCache.java
 * @Function :    緩存算法
 * @Description : 記憶體緩存圖檔Bitmap
 * @Idea :
 * {@link  }
 * @Encourage :And the more we try to understand one another, the more exceptional each of us will be.
 * 我們越是努力了解他人,自身也越發變得優秀。
 * @date : 2021/6/3
 */
public class MyLruCache extends LruCache<String, Bitmap> {

    private static MyLruCache myLruCache;

    private MyLruCache(int maxSize) {
        super(maxSize);
    }

    public static MyLruCache getMyLruCache() {
        if (myLruCache == null) {
            int maxMemory = (int) Runtime.getRuntime().maxMemory();
            int maxSize = maxMemory / 4;
            myLruCache = new MyLruCache(maxSize);
        }
        return myLruCache;
    }

    //每次存入bitmap時調用,傳回存入的資料大小
    @Override
    protected int sizeOf(String key, Bitmap value) {
        return value.getByteCount();
    }

	//添加
    public void add(String key, Bitmap bitmap) {
        if (get(key) == null) {
            put(key, bitmap);
        }
    }
 
 	//擷取
    public Bitmap getBitmap(String key) {
        return get(key);
    }

}
           

(2)例子二

import android.util.LruCache;
/**
 * @author : Dumplings
 * @version : v1.0.0
 * @ClassName : MyLruCache.java
 * @Function : 緩存算法
 * @Description :
 * @Idea :
 * {@link  }
 * @Encourage :And the more we try to understand one another, the more exceptional each of us will be.
 * 我們越是努力了解他人,自身也越發變得優秀。
 * @date : 2021/6/3
 */
public class MyLruCache<T> extends LruCache<String, T> {

    private static volatile MyLruCache instance = null;

    private MyLruCache(int maxSize) {
        super(maxSize);
    }

    public static <T> MyLruCache getInstance() {
        if (instance == null) {
            synchronized (MyLruCache.class) {
                if (instance == null) {
                    instance = new MyLruCache<T>(1024 * 1024 * 20);
                }
            }
        }
        return instance;
    }
}
           

調用:

MyLruCache<Drawable> myLruCache = MyLruCache.getInstance();
  Drawable thatDrawable = myLruCache.get("key");
	if (thatDrawable == null) {
	//data.getAppIcon() 圖檔路徑 or 圖檔資源 ...
	thatDrawable = data.getAppIcon();
	myLruCache.put("key", thatDrawable);
  }
  //圖檔控件imageView(你自己的圖檔控件變量名稱)顯示
  imageView.setBackground(thatDrawable);