`

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

 
阅读更多

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
	 */

	private 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);
	}

	// 从本地读取图
	private Drawable getDrawableFromFile(String uri) {
		Bitmap bitmap = BitmapFactory.decodeFile(uri);
		Drawable drawable = new BitmapDrawable(bitmap);
		return drawable;
	}
/**
 * 设置imageview的bitmap
 * @param uri 圖片路徑
 * @param imageView 
 */
	public void setAsyDrawable(String uri, ImageView imageView) {// 使用软引用获取用于显示图片的drawable
		Drawable asyndrawable = loadDrawable(uri, imageView,
				new ImageCallback() {
					public void imageLoaded(Drawable imageDrawable,
							ImageView imageView, String imageUrl) {
						imageView.setImageDrawable(imageDrawable);

					}
				});

	}

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics