从网络上下载图片在Listview中显示,网上相关例子非常多,抄了一些过来,大致能看懂,但是让自己写,肯定还是写不出来的,暂且记下来吧。大致效果如下
1.FileCache,将从网络上下载的图片保存在本地
import java.io.File;
import android.content.Context;
public class FileCache {
private File cacheDir;
public FileCache(Context context) {
// 如果有SD卡则在SD卡中建一个LazyList的目录存放缓存的图片
// 没有SD卡就放在系统的缓存目录中
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
cacheDir = new File(android.os.Environment.getExternalStorageDirectory(), "LazyList");
} else {
cacheDir = context.getCacheDir();
}
if (!cacheDir.exists()) {
cacheDir.mkdirs();
}
}
public File getFile(String url){
// 将url的hashCode作为缓存的文件名
String fileName = String.valueOf(url.hashCode());
return new File(cacheDir,fileName);
}
public void clear(){
File[] files = cacheDir.listFiles();
if (files == null) {
return;
}
for (File file : files) {
file.delete();
}
}
}
2.MemoryCache,将下载的图片存放在内存中
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import android.graphics.Bitmap;
public class MemoryCache {
private Map<String, Bitmap> cache = Collections.synchronizedMap(new LinkedHashMap<String, Bitmap>(10, 1.5f, true));
// 缓存中图片所占用的字节,初始0,将通过此变量严格控制缓存所占用的堆内存
private long size = 0;
// 缓存只能占用的最大堆内存
private long limit = 1000000;
public MemoryCache(){
// use 25% of available heap size
setLimit(Runtime.getRuntime().maxMemory() / 4);
}
public void setLimit(long new_limit){
limit = new_limit;
}
public Bitmap get(String id){
try {
if (!cache.containsKey(id)) {
return null;
}else {
return cache.get(id);
}
} catch (NullPointerException e) {
e.printStackTrace();
return null;
}
}
long getSizeInBytes(Bitmap bitmap){
//图片占用的内存
if (bitmap == null) {
return 0;
}else {
return bitmap.getRowBytes() * bitmap.getHeight();
}
}
public void put(String id, Bitmap bitmap){
try {
if (cache.containsKey(id)) {
size -= getSizeInBytes(cache.get(id));
}else {
cache.put(id, bitmap);
size += getSizeInBytes(bitmap);
checkSize();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void checkSize() {
// 严格控制堆内存,如果超过将首先替换最近最少使用的那个图片缓存
if (size > limit) {
Iterator<Entry<String, Bitmap>> iter = cache.entrySet().iterator();
while(iter.hasNext()){
Entry<String, Bitmap> entry = iter.next();
size -= getSizeInBytes(entry.getValue());
iter.remove();
if (size <= limit) {
break;
}
}
}
}
public void clear() {
cache.clear();
}
}
3.ImageLoader,下载图片,更新UI
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import android.R.menu;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageButton;
import android.widget.ImageView;
public class ImageLoader {
MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews = Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService; // 线程池
public ImageLoader(Context context){
fileCache = new FileCache(context);
executorService = Executors.newFixedThreadPool(5);
}
public void displayImage(String url, ImageView imageView){
imageViews.put(imageView, url);
Bitmap bitmap = memoryCache.get(url); // 先从内存缓存中查找
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
}else {
// 若没有的话则开启新线程加载图片
queuePhoto(url, imageView);
}
}
private void queuePhoto(String url, ImageView imageView) {
PhotoToLoad photoToLoad = new PhotoToLoad(url, imageView);
executorService.submit(new PhotosLoader(photoToLoad));
}
class PhotosLoader implements Runnable{
PhotoToLoad photoToLoad;
public PhotosLoader(PhotoToLoad photoToLoad) {
this.photoToLoad = photoToLoad;
}
@Override
public void run() {
if (imageViewReused(photoToLoad)) {
return;
}
Bitmap bmp = getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url, bmp);
if (imageViewReused(photoToLoad)) {
return;
}
BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
Activity activity = (Activity) photoToLoad.imageView.getContext();
activity.runOnUiThread(bd);
// 更新的操作放在UI线程中
}
}
class BitmapDisplayer implements Runnable{
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap bitmap, PhotoToLoad photoToLoad) {
BitmapDisplayer.this.bitmap = bitmap;
BitmapDisplayer.this.photoToLoad = photoToLoad;
}
@Override
public void run() {
if (imageViewReused(photoToLoad)) {
return;
}
if (bitmap != null) {
photoToLoad.imageView.setImageBitmap(bitmap);
}
}
}
private Bitmap getBitmap(String url) {
File f = fileCache.getFile(url);
// 先从文件缓存中查找是否有
Bitmap b = decodeFile(f);
if (b != null) {
return b;
}
// 最后从指定的url中下载图片
try {
Bitmap bitmap = null;
URL imageUrl = new URL(url);
HttpURLConnection connection = (HttpURLConnection)imageUrl.openConnection();
connection.setConnectTimeout(30000);
connection.setReadTimeout(30000);
connection.setInstanceFollowRedirects(true);
InputStream is = connection.getInputStream();
OutputStream os = new FileOutputStream(f);
copyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void copyStream(InputStream is, OutputStream os) {
final int buffer_size = 1024;
try {
byte[] bytes = new byte[buffer_size];
for(;;){
int count = is.read(bytes, 0, buffer_size);
if (count == -1) {
break;
}
os.write(bytes, 0, count);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private Bitmap decodeFile(File f) {
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true; // 如果设置为true,并不会把图像的数据完全解码,亦即decodeXyz()返回值为null,但是Options的outAbc中解出了图像的基本信息
BitmapFactory.decodeStream(new FileInputStream(f), null, options);
final int REQUIRED_SIZE = 70;
int width_tmp = options.outHeight, height_tmp = options.outHeight, scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE) {
break;
}
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
BitmapFactory.Options options2 = new BitmapFactory.Options();
options2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, options2);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
boolean imageViewReused(PhotoToLoad photoToLoad){ //防止图片错位
String tag = imageViews.get(photoToLoad.imageView);
if (tag == null || !tag.equals(photoToLoad.url)) {
return true;
}
return false;
}
private class PhotoToLoad{
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i){
url = u;
imageView = i;
}
}
}