MemoryCache和DiskCache在ListView和GridView中加载图片的总结(-)

一:用MemoryCache

在占用宝贵的应用程序内存的成本前提下,Memory cache 提供快速访问的位图。LruCache类特别适合于高速缓存位图的任务,能够保持最近引用的对象一个强有力的引用LinkedHashMap的和逐出最近最少使用的构件缓存超过其指定大小之前。

LruCache用法:

首先要为LruCache分配内存 分配内存要考虑的因素有:

①:你的Activity和/或application的其他部分如何内存密集型的?

②:一次加载位图的数量,接下来要加载位图的数量

③:该手机的屏幕大小和屏幕密度

④:位图的尺寸和配置,每一个位图所占用的内存

⑤:位图被访问的频率,

⑥:权衡数量与质量之间的平衡。有时也可以是更加有用以存储低质量位图较大数量,潜在地装入更高质量版本在另一个后台任务。

LruCache运用的例子

private LruCache<String, Bitmap> mMemoryCache;
@Override
protected void onCreate(Bundle savedInstanceState) {
    // Get max available VM memory, exceeding this amount will throw an
    // OutOfMemory exception. Stored in kilobytes as LruCache takes an
    // int in its constructor.
    final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);

    // Use 1/8th of the available memory for this memory cache.
    final int cacheSize = maxMemory / 8;

    mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
        @Override
        protected int sizeOf(String key, Bitmap bitmap) {
            // The cache size will be measured in kilobytes rather than
            // number of items.
            return bitmap.getByteCount() / 1024;
        }
    };
    ...
}

public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
    if (getBitmapFromMemCache(key) == null) {
        mMemoryCache.put(key, bitmap);
    }
}

public Bitmap getBitmapFromMemCache(String key) {
    return mMemoryCache.get(key);
}
加载图片时的代码:

public void loadBitmap(int resId, ImageView imageView) {
    final String imageKey = String.valueOf(resId);

    final Bitmap bitmap = getBitmapFromMemCache(imageKey);
    if (bitmap != null) {
        mImageView.setImageBitmap(bitmap);
    } else {
        mImageView.setImageResource(R.drawable.image_placeholder);
        BitmapWorkerTask task = new BitmapWorkerTask(mImageView);
        task.execute(resId);
    }
}
BitmapWorkTask类

class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {
    ...
    // Decode image in background.
    @Override
    protected Bitmap doInBackground(Integer... params) {
        final Bitmap bitmap = decodeBitmap();//该方法用来加载图片的具体方法,要看你加载图片资源的来源
        addBitmapToMemoryCache(String.valueOf(params[0]), bitmap);
        return bitmap;
    }
   
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值