LruCache缓存bitmap(二)

Lrucache缓存程序关闭缓存自动清除,所以要在onstart方法中调用,只要不关闭程序缓存就在,除以1024是以kb为单位

public class MainActivity extends AppCompatActivity {
    private LruCache<String, Bitmap> mMemoryCache;
    ImageView imageView;
    Bitmap bitmap;
    int cacheSize;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = findViewById(R.id.image);
        long maxMemory = Runtime.getRuntime().maxMemory();
        cacheSize = (int) (maxMemory / 8)/1024;
        mMemoryCache = new LruCache<String, Bitmap>(
                cacheSize) {
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                // 重写此方法来衡量每张图片的大小,默认返回图片数量。
                return bitmap.getRowBytes() * bitmap.getHeight() / 1024;
            }
            @Override
            protected void entryRemoved(boolean evicted, String key,
                                        Bitmap oldValue, Bitmap newValue) {
                Log.v("tag", "hard cache is full , push to soft cache");
            }
        };
    }
    @Override
    protected void onStart() {
        super.onStart();
        Bitmap bitmap2 = mMemoryCache.get("a");
        if (bitmap2 != null) {
            imageView.setImageBitmap(bitmap2);
        } else {
            bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon12);
            mMemoryCache.put("a",bitmap);
            imageView.setImageBitmap(bitmap);
        }
    }
}

猜你喜欢

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