实现异步加载本地图片,防止oom错误

package com.qiho.wheresmycar.util;

import java.lang.ref.SoftReference;
import java.util.HashMap;

import android.content.Context;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;
/**
 * 实现异步加载本地图片,防止oom错误
 * @author su
 *
 */
public class AsyncImageLoader {
	public Context mcontext;

	private HashMap<String, SoftReference<Drawable>> imageCache;

	public AsyncImageLoader(Context context) {
		this.mcontext = context;
		imageCache = new HashMap<String, SoftReference<Drawable>>();
	}

	/**
	 * 
	 * @param imageUri
	 *            图片路徑
	 * @param imageView
	 *            所要显示图片的imageview
	 * @param imageCallback
	 *            实现一个callback 比较固定
	 * @return
	 */

	public Drawable loadDrawable(final String uri,
			final ImageView imageView, final ImageCallback imageCallback) {

		if (imageCache.containsKey(uri)) {
			// 从缓存中获取
			SoftReference<Drawable> softReference = imageCache.get(uri);
			Drawable drawable = softReference.get();
			if (drawable != null) {
				return drawable;
			}
		}

		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				imageCallback.imageLoaded((Drawable) msg.obj, imageView,
						uri);
			}
		};

		// 建立新一个新的线程下载图片
		new Thread() {

			public void run() {
				Drawable drawable = null;
				drawable = getDrawableFromFile(uri);
				imageCache.put(uri, new SoftReference<Drawable>(drawable));
				Message msg = handler.obtainMessage(0, drawable);
				handler.sendMessage(msg);
			}
		}.start();
		return null;
	}

	// 回调接口
	public interface ImageCallback {
		public void imageLoaded(Drawable imageDrawable, ImageView imageView,
				String uri);
	}
	//从本地读取图片
	public static Drawable getDrawableFromFile(String uri) {
		Bitmap bitmap = BitmapFactory.decodeFile(uri);
		Drawable drawable = new BitmapDrawable(bitmap);
		return drawable;
	}

}

posted @ 2012-10-27 11:15  sfshine  阅读(484)  评论(0编辑  收藏  举报