图片缓存
2018-04-04 本文已影响0人
银弹星空
图片缓存加载方法
public class MyVideoThumbLoader {
private ImageView imgView;
private String path;
//创建cache
private LruCache<String, Bitmap> lruCache;
public MyVideoThumbLoader() {
int maxMemory = (int) Runtime.getRuntime().maxMemory();//获取最大的运行内存
int maxSize = maxMemory / 4;//拿到缓存的内存大小
lruCache = new LruCache<String, Bitmap>(maxSize) {
@Override
protected int sizeOf(String key, Bitmap value) {
//这个方法会在每次存入缓存的时候调用
return value.getByteCount();
}
};
}
public void addVideoThumbToCache(String path, Bitmap bitmap) {
if (getVideoThumbToCache(path) == null) {
//当前地址没有缓存时,就添加
lruCache.put(path, bitmap);
}
}
public Bitmap getVideoThumbToCache(String path) {
return lruCache.get(path);
}
public void showThumbByAsyncTask(String path, ImageView imgView) {
if (getVideoThumbToCache(path) == null) {
//异步加载
imgView.setImageResource(R.drawable.video); //设置默认图片
new MyAsyncTask(imgView, path).execute(path);
} else {
imgView.setImageBitmap(getVideoThumbToCache(path));
}
}
class MyAsyncTask extends AsyncTask<String, Void, Bitmap> {
private ImageView imgView;
private String path;
public MyAsyncTask(ImageView imageView, String path) {
this.imgView = imageView;
this.path = path;
}
@Override
protected Bitmap doInBackground(String... params) {
//通过 android中提供的 ThumbnailUtils.createVideoThumbnail(vidioPath, kind);
Bitmap bitmap = ThumbnailUtils.extractThumbnail(ThumbnailUtils.createVideoThumbnail(params[0], MediaStore.Images.Thumbnails.MICRO_KIND), 100, 100); //加入缓存中
Log.v("getVideoThumbToCache:", "path:" + path);
// Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(params[0], MediaStore.Video.Thumbnails.MICRO_KIND);
if (bitmap != null) {
if (getVideoThumbToCache(params[0]) == null) {
addVideoThumbToCache(path, bitmap);
}
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
if (imgView.getTag().equals(path)) {//通过 Tag可以绑定 图片地址和 imageView,这是解决Listview加载图片错位的解决办法之一
if (bitmap == null) {
imgView.setImageResource(R.drawable.video);
} else {
imgView.setImageBitmap(bitmap);
}
}
}
}
}