Android 异步加载图片的实例代码

时间:2022-02-14 20:52:21

异步加载图片的主要流程是进行判断缓存中是否存在图片,如果存在则直接返回,如果不存在则进行下载并进行缓存。

以下是建立一个异步下载类:

复制代码 代码如下:


/**
 * User: Tom
 * Date: 13-5-13
 * Time: 下午8:07
 */
public class AsnycImageLoader {

 

    //定义一个HashMap进行存放缓存的Image key为String Value为一个弱引用的一个资源文件
    // 图片 为了方便JAVA的回收
    private Map<String, SoftReference<Drawable>> imageCache = null;
    public AsnycImageLoader() {
        imageCache = new HashMap<String, SoftReference<Drawable>>();
    }

    /**
     * 加载图片
     * <p>imageurl为下载资源的URL,
     * ImageCallback当缓存中不存在相关图片时时行网络下载
     * 在多线程下要使用Handler进行操作UI 利用回调接口的方式进行更新UI
     * </p>
     * @param imageUrl
     * @param callback
     * @return
     */
    public Drawable loadDrawable(final String imageUrl, final ImageCallback callback) {
        //进行判断ImageCache中是否存在缓存图片
        if (imageCache.containsKey(imageUrl)) {
            SoftReference<Drawable> softReference = imageCache.get(imageUrl);
            if (softReference.get() != null) {
                return softReference.get();
            }
        }
        //定义操作UI的Handler
        final Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                callback.imageLoaded((Drawable) msg.obj);
            }
        };

        new Thread(new Runnable() {
            @Override
            public void run() {
                Drawable drawable = loadImageFromUrl(imageUrl);
                imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
                Message message = handler.obtainMessage(0, drawable);
                handler.sendMessage(message);
            }
        }).start();
        return null;
    }

    //根据URL地址进行获取资源
    protected Drawable loadImageFromUrl(String imageUrl) {
        try {
            return Drawable.createFromStream(new URL(imageUrl).openStream(), "src");
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }

    //回调接口
    public interface ImageCallback {
        public abstract void imageLoaded(Drawable drawable);
    }
}

 

 

主Activity:

复制代码 代码如下:


/**
 * User: Tom
 * Date: 13-5-13
 * Time: 下午8:33
 */
public class LoadImage extends Activity {
    private AsnycImageLoader loader = null;

 

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.loadimages);

        loader = new AsnycImageLoader();

        loadImage("http://www.zzvips.com/images/icon-partners.png", R.id.image1);
        loadImage("http://www.zzvips.com/images/icon-dev.png", R.id.image2);
        loadImage("http://pic28.jb51.net/20130421/12302174_231210305323_2.jpg", R.id.image3);


    }

    public void loadImage(String url, int id) {
        final ImageView imageView = (ImageView) findViewById(id);
        Drawable cacheImage = loader.loadDrawable(url, new AsnycImageLoader.ImageCallback() {
            @Override
            public void imageLoaded(Drawable drawable) {
                imageView.setImageDrawable(drawable);
            }
        });
        if (cacheImage != null) {
            imageView.setImageDrawable(cacheImage);
        }
    }
}