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

本文介绍了一种使用软引用缓存图片并实现异步加载的方法,有效防止了内存溢出(OOM)错误。通过本地图片路径加载图片到ImageView,并实现了图片加载的回调接口。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



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

					}
				});

	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值