LruCache缓存bitmap

Lrucache是把图片缓存到内置sd卡,设置缓存容量为系统分配容量的八分之一,单位byte,超过缓存容量gc会自动回收不长使用的缓存.觉得lrucache就先map一样,放入键值对就行了,比较方便,现在官方不让用软引用缓存了softpreference,好像是容易内存泄漏

public class MainActivity extends AppCompatActivity {
    private LruCache<String, Bitmap> lruCache;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ImageView imageView = findViewById(R.id.image);
        long maxMemory = Runtime.getRuntime().maxMemory();
        int cacheSize = (int) (maxMemory / 8);
        lruCache = new LruCache<String, Bitmap>(cacheSize) {
            @Override
            protected int sizeOf(String key, Bitmap value) {
                return value.getByteCount();
            }

        };
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon12);
        lruCache.put("a", bitmap);
        Bitmap bitmap2 = lruCache.get("a");
        if (bitmap2 == null) {
            System.out.println("无缓存");
        } else {
            imageView.setImageBitmap(bitmap2);
        }
    }
}

因为是存在内部存储所以不用获取外部存储权限,输出无缓存就是没缓存上,可以把第二个a改成b试一下就输出无缓存

猜你喜欢

转载自www.cnblogs.com/Ocean123123/p/10980691.html