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);

你可能感兴趣的:(Android番外篇,android,缓存,java)