• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Ocean123123
博客园    首页    新随笔    联系   管理    订阅  订阅

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

 

posted @ 2019-06-05 18:43  Ocean123123  阅读(252)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3