listView异步处理图片下载缓存

时间:2022-07-19 22:43:02
listView异步处理图片下载缓存

package cn.wangmeng.test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class AsyncImageLoader {
private static final String TAG="AsyncImageLoader";

private HashMap<String, SoftReference<Drawable>> imageCache;
private BlockingQueue queue ;
private ThreadPoolExecutor executor ;

public AsyncImageLoader() {
imageCache = new HashMap<String, SoftReference<Drawable>>();

// 线程池:最大50条,每次执行:1条,空闲线程结束的超时时间:180秒
queue = new LinkedBlockingQueue();
executor = new ThreadPoolExecutor(1, 50, 180, TimeUnit.SECONDS, queue);
}

public Drawable loadDrawable(final Context context, final String imageUrl, final ImageCallback imageCallback) {
if (imageCache.containsKey(imageUrl)) {
SoftReference<Drawable> softReference = imageCache.get(imageUrl);
Drawable drawable = softReference.get();
if (drawable != null) {
return drawable;
}
}
final Handler handler = new Handler() {
public void handleMessage(Message message) {
imageCallback.imageLoaded((Drawable) message.obj, imageUrl);
}
};

// 用线程池来做下载图片的任务
executor.execute(new Runnable() {
@Override
public void run() {
Drawable drawable = loadImageFromUrl(context, imageUrl);
imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
Message message = handler.obtainMessage(0, drawable);
handler.sendMessage(message);
}
});

return null;
}

// 网络图片先下载到本地cache目录保存,以imagUrl的图片文件名保存。如果有同名文件在cache目录就从本地加载
public static Drawable loadImageFromUrl(Context context, String imageUrl) {
Drawable drawable = null;
if(imageUrl == null )
return null;
String imagePath = "";
String fileName = "";

// 获取url中图片的文件名与后缀
if(imageUrl!=null&&imageUrl.length()!=0){
fileName = imageUrl.substring(imageUrl.lastIndexOf("/")+1);
}

// 图片在手机本地的存放路径,注意:fileName为空的情况
imagePath = context.getCacheDir() + "/" + fileName;

// Log.i(TAG,"imagePath = " + imagePath);
File file = new File(context.getCacheDir(),fileName);// 保存文件
// Log.i(TAG,"file.toString()=" + file.toString());
if(!file.exists()&&!file.isDirectory())
{
try {
// 可以在这里通过文件名来判断,是否本地有此图片

FileOutputStream fos=new FileOutputStream( file );
InputStream is = new URL(imageUrl).openStream();
int data = is.read();
while(data!=-1){
fos.write(data);
data=is.read();;
}
fos.close();
is.close();
// drawable = Drawable.createFromStream(
// new URL(imageUrl).openStream(), file.toString() ); // (InputStream) new URL(imageUrl).getContent();
drawable = Drawable.createFromPath(file.toString());
// Log.i(TAG, "file.exists()不文件存在,网上下载:" + drawable.toString());
} catch (IOException e) {
Log.e(TAG, e.toString() + "图片下载及保存时出现异常!");
}
}else
{
drawable = Drawable.createFromPath(file.toString());
// Log.i("test", "file.exists()文件存在,本地获取");
}
return drawable ;
}

public interface ImageCallback {
public void imageLoaded(Drawable imageDrawable, String imageUrl);
}

}

package cn.wangmeng.test;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;

/**
* 图片异步下载的Activity类
*
*
* @author Tim http://doinone.iteye.com/blog/
* @created 2011-6-22
* @since 2011-6-22
*/

public class AsyncListImage extends Activity {
private ListView list;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
list=(ListView)findViewById(R.id.list);
List<ImageAndText> dataArray=new ArrayList<ImageAndText>();
ImageAndText test=new ImageAndText("http://www.wangmeng.cn/images/logo.gif", "test");
ImageAndText test1=new ImageAndText("http://www.wangmeng.cn/images/ad/t1.gif", "test1");
ImageAndText test2=new ImageAndText("http://www.wangmeng.cn/images/ad/t3.gif", "test2");
ImageAndText test3=new ImageAndText("http://www.wangmeng.cn/images/ad/logo.gif", "test3"); // 错误的图片url
ImageAndText test4=new ImageAndText("http://www.wangmeng.cn/images/ad/t22223.gif", "test4:错误的图片url");// 错误的图片url
ImageAndText test5=new ImageAndText("http://www.wangmeng.cn/images/ad/t222223.gif", "test5:错误的图片url");// 错误的图片url
ImageAndText test6=new ImageAndText("http://www.wangmeng.cn/images/logo.gif", "test6");
ImageAndText test7=new ImageAndText("http://www.wangmeng.cn/images/ad/t3.gif", "test7");
ImageAndText test8=new ImageAndText("http://www.wangmeng.cn/images/ad/t3.gif", "test8");
ImageAndText test9=new ImageAndText("http://www.wangmeng.cn/images/ad/t2222.gif", "test9:错误的图片url");// 错误的图片url
ImageAndText test10=new ImageAndText("http://www.wangmeng.cn/images/ad/t3.gif", "test10");
ImageAndText test11=new ImageAndText("http://www.wangmeng.cn/images/ad/t1.gif", "test11");
ImageAndText test12=new ImageAndText("http://www.wangmeng.cn/images/ad/t1.gif", "test12");
ImageAndText test13=new ImageAndText("http://www.wangmeng.cn/images/ad/t1.gif", "test13");
ImageAndText test14=new ImageAndText("http://www.wangmeng.cn/images/ad/t1.gif", "test14");
ImageAndText test15=new ImageAndText("http://www.wangmeng.cn/images/ad/t1.gif", "test15");
ImageAndText test16=new ImageAndText("http://www.wangmeng.cn/images/ad/t1.gif", "test16");
ImageAndText test17=new ImageAndText("http://www.wangmeng.cn/images/ad/t1.gif", "test17");
ImageAndText test18=new ImageAndText("http://www.wangmeng.cn/images/ad/t1.gif", "test18");

ImageAndText test19=new ImageAndText("", "test19:错误的图片url");

dataArray.add(test);
dataArray.add(test1);
dataArray.add(test2);
dataArray.add(test3);
dataArray.add(test4);
dataArray.add(test5);
dataArray.add(test6);
dataArray.add(test7);
dataArray.add(test8);
dataArray.add(test9);
dataArray.add(test10);
dataArray.add(test11);
dataArray.add(test12);
dataArray.add(test13);
dataArray.add(test14);
dataArray.add(test15);
dataArray.add(test16);
dataArray.add(test17);
dataArray.add(test18);
dataArray.add(test19);
dataArray.add(test2);
ImageAndTextListAdapter adapter=new ImageAndTextListAdapter(this, dataArray, list);
list.setAdapter(adapter);

}
}

package cn.wangmeng.test;

/**
* 保存ListView的item的实体
*
*
* @author Tim http://doinone.iteye.com/blog/
* @created 2011-6-22
* @since 2011-6-22
*/

public class ImageAndText {
private String imageUrl;
private String text;

public ImageAndText(String imageUrl, String text) {
this.imageUrl = imageUrl;
this.text = text;
}
public String getImageUrl() {
return imageUrl;
}
public String getText() {
return text;
}
}

package cn.wangmeng.test;

import java.util.List;

import cn.wangmeng.test.AsyncImageLoader.ImageCallback;
import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

/**
* 图片异步下载类
* (如该图片已存在即显示图片,否则通过URL下载图片并显示)
*
* @author Tim http://doinone.iteye.com/blog/
* @created 2011-6-22
* @since 2011-6-22
*/

public class ImageAndTextListAdapter extends ArrayAdapter<ImageAndText> {

private ListView listView;
private AsyncImageLoader asyncImageLoader;
private LayoutInflater inflater ;
private Context context;

public ImageAndTextListAdapter(Activity activity, List<ImageAndText> imageAndTexts, ListView listView) {
super(activity, 0, imageAndTexts);
this.listView = listView;
asyncImageLoader = new AsyncImageLoader();
inflater = activity.getLayoutInflater();
this.context = activity;
}

public View getView(int position, View convertView, ViewGroup parent) {
// Activity activity = (Activity) getContext();

Holder holder ;

if (convertView == null) {
convertView = inflater.inflate(R.layout.image_and_text_row, null);
holder = new Holder();
holder.imageView = (ImageView) convertView.findViewById(R.id.image);
holder.textView = (TextView)convertView.findViewById(R.id.text);

convertView.setTag(holder);
} else {
holder = (Holder) convertView.getTag();
}

// 获取item对应第几条(position)的Model实体
ImageAndText imageAndText = getItem(position);

// Load the image and set it on the ImageView
String imageUrl = imageAndText.getImageUrl();
holder.imageView.setTag(imageUrl);

// 延遲加載圖片 : imageUrl 是 圖片的http鏈接地址,後面是回调函數
Drawable cachedImage = asyncImageLoader.loadDrawable(context, imageUrl, new ImageCallback() {
public void imageLoaded(Drawable imageDrawable, String imageUrl) {
ImageView imageViewByTag = (ImageView) listView.findViewWithTag(imageUrl);
Log.i("test", "Drawable cachedImage = asyncImageLoader.loadDrawable( )-->");
if (imageViewByTag != null && imageDrawable != null ) { // 防止图片url获取不到图片是,占位图片不见了的情况
imageViewByTag.setImageDrawable(imageDrawable);
}
}
});
if (cachedImage == null) {
holder.imageView.setImageResource(R.drawable.default_image);
}else{
holder.imageView.setImageDrawable(cachedImage);
}

// Set the text on the TextView
holder.textView.setText(imageAndText.getText());

Log.i("test","position = " + position);

return convertView;
}

static class Holder{
ImageView imageView;
TextView textView;
}

}