为了解决这个问题,我做了一个类VideoThumbLoader
。它异步生成位图并将其传递给适配器。所以主要的好处是整个过程都在后台线程中处理。
类的代码如下:
import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.media.ThumbnailUtils;
import android.os.AsyncTask;
import android.provider.MediaStore;
import android.support.v4.util.LruCache;
import android.widget.ImageView;
public class VideoThumbLoader {
private LruCache<String, Bitmap> lruCache;
@SuppressLint("NewApi")
public VideoThumbLoader() {
int maxMemory = (int) Runtime.getRuntime().maxMemory();// obtain maximum
// memory to run
int maxSize = maxMemory / 4;// get cache memory size 35
lruCache = new LruCache<String, Bitmap>(maxSize) {
@Override
protected int sizeOf(String key, Bitmap value) {
// this will be called when the cache deposited in each
return value.getByteCount();
}
};
}
public void addVideoThumbToCache(String path, Bitmap bitmap) {
if (getVideoThumbToCache(path) == null && bitmap != null) {
lruCache.put(path, bitmap);
}
}
public Bitmap getVideoThumbToCache(String path) {
return lruCache.get(path);
}
public void showThumbByAsynctack(String path, ImageView imgview) {
if (getVideoThumbToCache(path) == null) {
// asynchronous loading
new MyBobAsynctack(imgview, path).execute(path);
} else {
imgview.setImageBitmap(getVideoThumbToCache(path));
}
}
class MyBobAsynctack extends AsyncTask<String, Void, Bitmap> {
private ImageView imgView;
private String path;
public MyBobAsynctack(ImageView imageView, String path) {
this.imgView = imageView;
this.path = path;
}
@Override
protected Bitmap doInBackground(String... params) {
Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(params[0],
MediaStore.Video.Thumbnails.MINI_KIND);
// provide
if (getVideoThumbToCache(params[0]) == null) {
addVideoThumbToCache(path, bitmap);
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
if (imgView.getTag().equals(path)) {// through Tag can be bound
// pictures address and
// imageView, this address
// Listview loading the image
// dislocation solution
imgView.setImageBitmap(bitmap);
}
}
}
}
从适配器端,只需调用:
private VideoThumbLoader mVideoThumbLoader = new VideoThumbLoader();
imageThumbnail.setTag(videoValues.get(position).getFile()
.getAbsolutePath());// binding imageview
imageThumbnail.setImageResource(R.drawable.videothumb); //default image
mVideoThumbLoader.showThumbByAsynctack(videoValues.get(position)
.getFile().getAbsolutePath(), imageThumbnail);
PS:我注意到的一件重要的事情是,由于位图的异步下载,很少有缩略图容易混淆的情况。所以我用文件路径标记了imageview。这样,我将获得图像的确切缩略图。