Android异步加载图像(含线程池,缓存方法)


研究了Android从网络上异步加载图像:

(1)由于android UI更新支持单一线程原则,所以从网络上取数据并更新到界面上,为了不阻塞主线程首先可能会想到以下方法。

在主线程中new 一个Handler对象,加载图像方法如下所示

  1. private void loadImage(final String url, final int id) {  
  2.         handler.post(new Runnable() {  
  3.                public void run() {  
  4.                    Drawable drawable = null;  
  5.                    try {  
  6.                        drawable = Drawable.createFromStream(new URL(url).openStream(), "image.png");  
  7.                    } catch (IOException e) {  
  8.                    }  
  9.                    ((ImageView) LazyLoadImageActivity.this.findViewById(id)).setImageDrawable(drawable);  
  10.                }  
  11.            });  
  12.    }  

上面这个方法缺点很显然,经测试,如果要加载多个图片,这并不能实现异步加载,而是等到所有的图片都加载完才一起显示,因为它们都运行在一个线程中。

然后,我们可以简单改进下,将Handler+Runnable模式改为Handler+Thread+Message模式不就能实现同时开启多个线程吗?

(2)在主线程中new 一个Handler对象,代码如下:

  1. final Handler handler2=new Handler(){  
  2.          @Override  
  3.          public void handleMessage(Message msg) {  
  4.             ((ImageView) LazyLoadImageActivity.this.findViewById(msg.arg1)).setImageDrawable((Drawable)msg.obj);  
  5.          }  
  6.      };  

对应加载图像代码如下:对应加载图像代码如下:对应加载图像代码如下:

  1. // 引入线程池来管理多线程   
  2.    private void loadImage3(final String url, final int id) {  
  3.        executorService.submit(new Runnable() {  
  4.            public void run() {  
  5.                try {  
  6.                    final Drawable drawable = Drawable.createFromStream(new URL(url).openStream(), "image.png");  
  7.                    handler.post(new Runnable() {  
  8.   
  9.                        public void run() {  
  10.                            ((ImageView) LazyLoadImageActivity.this.findViewById(id)).setImageDrawable(drawable);  
  11.                        }  
  12.                    });  
  13.                } catch (Exception e) {  
  14.                    throw new RuntimeException(e);  
  15.                }  
  16.            }  
  17.        });  
  18.    }  

(4)为了更方便使用我们可以将异步加载图像方法封装一个类,对外界只暴露一个方法即可,考虑到效率问题我们可以引入内存缓存机制,做法是

建立一个HashMap,其键(key)为加载图像url,其值(value)是图像对象Drawable。先看一下我们封装的类

  1. public class AsyncImageLoader3 {  
  2.    //为了加快速度,在内存中开启缓存(主要应用于重复图片较多时,或者同一个图片要多次被访问,比如在ListView时来回滚动)   
  3.     public Map<String, SoftReference<Drawable>> imageCache = new HashMap<String, SoftReference<Drawable>>();  
  4.     private ExecutorService executorService = Executors.newFixedThreadPool(5);    //固定五个线程来执行任务   
  5.     private final Handler handler=new Handler();  
  6.   
  7.      /** 
  8.      * 
  9.      * @param imageUrl     图像url地址 
  10.      * @param callback     回调接口 
  11.      * @return     返回内存中缓存的图像,第一次加载返回null 
  12.      */  
  13.     public Drawable loadDrawable(final String imageUrl, final ImageCallback callback) {  
  14.         //如果缓存过就从缓存中取出数据   
  15.         if (imageCache.containsKey(imageUrl)) {  
  16.             SoftReference<Drawable> softReference = imageCache.get(imageUrl);  
  17.             if (softReference.get() != null) {  
  18.                 return softReference.get();  
  19.             }  
  20.         }  
  21.         //缓存中没有图像,则从网络上取出数据,并将取出的数据缓存到内存中   
  22.          executorService.submit(new Runnable() {  
  23.             public void run() {  
  24.                 try {  
  25.                     final Drawable drawable = Drawable.createFromStream(new URL(imageUrl).openStream(), "image.png");  
  26.   
  27.                     imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));  
  28.   
  29.                     handler.post(new Runnable() {  
  30.                         public void run() {  
  31.                            callback.imageLoaded(drawable);  
  32.                         }  
  33.                     });  
  34.                 } catch (Exception e) {  
  35.                     throw new RuntimeException(e);  
  36.                 }  
  37.             }  
  38.         });  
  39.         return null;  
  40.     }  
  41.      //从网络上取数据方法   
  42.     protected Drawable loadImageFromUrl(String imageUrl) {  
  43.         try {  
  44.             return Drawable.createFromStream(new URL(imageUrl).openStream(), "image.png");  
  45.         } catch (Exception e) {  
  46.             throw new RuntimeException(e);  
  47.         }  
  48.     }  
  49.     //对外界开放的回调接口   
  50.     public interface ImageCallback {  
  51.         //注意 此方法是用来设置目标对象的图像资源   
  52.         public void imageLoaded(Drawable imageDrawable);  
  53.     }  
  54. }  

这样封装好后使用起来就方便多了。在主线程中首先要引入AsyncImageLoader3 对象,然后直接调用其loadDrawable方法即可,需要注意的是ImageCallback接口的imageLoaded方法是唯一可以把加载的图像设置到目标ImageView或其相关的组件上。

  • 1
  • 2
  • 下一页

相关内容