1. 程式人生 > >Android非同步載入影象小結

Android非同步載入影象小結

研究了android從網路上非同步載入影象,現總結如下:

(1)由於android UI更新支援單一執行緒原則,所以從網路上取資料並更新到介面上,為了不阻塞主執行緒首先可能會想到以下方法。

     在主執行緒中new 一個Handler物件,載入影象方法如下所示

    private void loadImage(final String url, final int id) {
         handler.post(new Runnable() {
                public void run() {
                    Drawable drawable = null;
                    try {
                        drawable = Drawable.createFromStream(new URL(url).openStream(), "image.png");
                    } catch (IOException e) {
                    }
                    ((ImageView) LazyLoadImageActivity.this.findViewById(id)).setImageDrawable(drawable);
                }
            });
    }

上面這個方法缺點很顯然,經測試,如果要載入多個圖片,這並不能實現非同步載入,而是等到所有的圖片都載入完才一起顯示,因為它們都執行在一個執行緒中。

然後,我們可以簡單改進下,將Handler+Runnable模式改為Handler+Thread+Message模式不就能實現同時開啟多個執行緒嗎?

(2)在主執行緒中new 一個Handler物件,程式碼如下:

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

    對應載入影象程式碼如下:

  //採用handler+Thread模式實現多執行緒非同步載入
     private void loadImage2(final String url, final int id) {
         Thread thread = new Thread(){
             @Override
             public void run() {
               Drawable drawable = null;
                    try {
                        drawable = Drawable.createFromStream(new URL(url).openStream(), "image.png");
                    } catch (IOException e) {
                    }

                Message message= handler2.obtainMessage() ;
                 message.arg1 = id;
                 message.obj = drawable;
                 handler2.sendMessage(message);
             }
         };
         thread.start();
         thread = null;
    }

這樣就簡單實現了非同步載入了。細想一下,還可以優化的,比如引入執行緒池、引入快取等,我們先介紹執行緒池。

(3)引入ExecutorService介面,於是程式碼可以優化如下:

       在主執行緒中加入:private ExecutorService executorService = Executors.newFixedThreadPool(5);   

       對應載入影象方法更改如下:

      // 引入執行緒池來管理多執行緒
    private void loadImage3(final String url, final int id) {
        executorService.submit(new Runnable() {
            public void run() {
                try {
                    final Drawable drawable = Drawable.createFromStream(new URL(url).openStream(), "image.png");
                    handler.post(new Runnable() {

                        public void run() {
                            ((ImageView) LazyLoadImageActivity.this.findViewById(id)).setImageDrawable(drawable);
                        }
                    });
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }

(4)為了更方便使用我們可以將非同步載入影象方法封裝一個類,對外界只暴露一個方法即可,考慮到效率問題我們可以引入記憶體快取機制,做法是

建立一個HashMap,其鍵(key)為載入影象url,其值(value)是影象物件Drawable。先看一下我們封裝的類

public class AsyncImageLoader3 {
   //為了加快速度,在記憶體中開啟快取(主要應用於重複圖片較多時,或者同一個圖片要多次被訪問,比如在ListView時來回滾動)
    public Map<String, SoftReference<Drawable>> imageCache = new HashMap<String, SoftReference<Drawable>>();
    private ExecutorService executorService = Executors.newFixedThreadPool(5);    //固定五個執行緒來執行任務
    private final Handler handler=new Handler();

     /**
     *
     * @param imageUrl     影象url地址
     * @param callback     回撥介面
     * @return     返回記憶體中快取的影象,第一次載入返回null
     */
    public Drawable loadDrawable(final String imageUrl, final ImageCallback callback) {
        //如果快取過就從快取中取出資料
        if (imageCache.containsKey(imageUrl)) {
            SoftReference<Drawable> softReference = imageCache.get(imageUrl);
            if (softReference.get() != null) {
                return softReference.get();
            }
        }
        //快取中沒有影象,則從網路上取出資料,並將取出的資料快取到記憶體中
         executorService.submit(new Runnable() {
            public void run() {
                try {
                    final Drawable drawable = Drawable.createFromStream(new URL(imageUrl).openStream(), "image.png");

                    imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));

                    handler.post(new Runnable() {
                        public void run() {
                           callback.imageLoaded(drawable);
                        }
                    });
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        });
        return null;
    }
     //從網路上取資料方法
    protected Drawable loadImageFromUrl(String imageUrl) {
        try {
            return Drawable.createFromStream(new URL(imageUrl).openStream(), "image.png");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    //對外界開放的回撥介面
    public interface ImageCallback {
        //注意 此方法是用來設定目標物件的影象資源
        public void imageLoaded(Drawable imageDrawable);
    }
}這樣封裝好後使用起來就方便多了。在主執行緒中首先要引入AsyncImageLoader3 物件,然後直接呼叫其loadDrawable方法即可,需要注意的是ImageCallback介面的imageLoaded方法是唯一可以把載入的影象設定到目標ImageView或其相關的元件上。

在主執行緒呼叫程式碼:

  先例項化物件 private AsyncImageLoader3 asyncImageLoader3 = new AsyncImageLoader3();

  呼叫非同步載入方法:

//引入執行緒池,並引入記憶體快取功能,並對外部呼叫封裝了介面,簡化呼叫過程
    private void loadImage4(final String url, final int id) {
          //如果快取過就會從快取中取出影象,ImageCallback介面中方法也不會被執行
         Drawable cacheImage = asyncImageLoader.loadDrawable(url,new AsyncImageLoader.ImageCallback() {
             //請參見實現:如果第一次載入url時下面方法會執行
             public void imageLoaded(Drawable imageDrawable) {
               ((ImageView) findViewById(id)).setImageDrawable(imageDrawable);
             }
         });
        if(cacheImage!=null){
          ((ImageView) findViewById(id)).setImageDrawable(cacheImage);
        }
    }

(5)同理,下面也給出採用Thread+Handler+MessageQueue+記憶體快取程式碼,原則同(4),只是把執行緒池換成了Thread+Handler+MessageQueue模式而已。程式碼如下:

public class AsyncImageLoader {
   //為了加快速度,加入了快取(主要應用於重複圖片較多時,或者同一個圖片要多次被訪問,比如在ListView時來回滾動)
    private Map<String, SoftReference<Drawable>> imageCache = new HashMap<String, SoftReference<Drawable>>();

     /**
     *
     * @param imageUrl     影象url地址
     * @param callback     回撥介面
     * @return     返回記憶體中快取的影象,第一次載入返回null
     */
    public Drawable loadDrawable(final String imageUrl, final ImageCallback callback) {
        //如果快取過就從快取中取出資料
        if (imageCache.containsKey(imageUrl)) {
            SoftReference<Drawable> softReference = imageCache.get(imageUrl);
            if (softReference.get() != null) {
                return softReference.get();
            }
        }

        final Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                callback.imageLoaded((Drawable) msg.obj);
            }
        };
        new Thread() {
            public void run() {
                Drawable drawable = loadImageFromUrl(imageUrl);
                imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
                handler.sendMessage(handler.obtainMessage(0, drawable));

            }

        }.start();
        /*
        下面註釋的這段程式碼是Handler的一種代替方法
         */
//        new AsyncTask() {
//            @Override
//            protected Drawable doInBackground(Object... objects) {
//                  Drawable drawable = loadImageFromUrl(imageUrl);
//                imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
//                return  drawable;
//            }
//
//            @Override
//            protected void onPostExecute(Object o) {
//                  callback.imageLoaded((Drawable) o);
//            }
//        }.execute();
        return null;
    }

    protected Drawable loadImageFromUrl(String imageUrl) {
        try {
            return Drawable.createFromStream(new URL(imageUrl).openStream(), "src");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    //對外界開放的回撥介面
    public interface ImageCallback {
        public void imageLoaded(Drawable imageDrawable);
    }
}

至此,非同步載入就介紹完了,下面給出的程式碼為測試用的完整程式碼:

package com.bshark.supertelphone.activity;

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;
import com.bshark.supertelphone.R;
import com.bshark.supertelphone.ui.adapter.util.AsyncImageLoader;
import com.bshark.supertelphone.ui.adapter.util.AsyncImageLoader3;

import java.io.IOException;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class LazyLoadImageActivity extends Activity {
       final Handler handler=new Handler();
      final Handler handler2=new Handler(){
          @Override
          public void handleMessage(Message msg) {
             ((ImageView) LazyLoadImageActivity.this.findViewById(msg.arg1)).setImageDrawable((Drawable)msg.obj);
          }
      };
 private ExecutorService executorService = Executors.newFixedThreadPool(5);    //固定五個執行緒來執行任務
    private AsyncImageLoader asyncImageLoader = new AsyncImageLoader();
    private AsyncImageLoader3 asyncImageLoader3 = new AsyncImageLoader3();

 @Override
 protected void onDestroy() {
  executorService.shutdown();
  super.onDestroy();
 }
    //執行緒載入影象基本原理
    private void loadImage(final String url, final int id) {
         handler.post(new Runnable() {
                public void run() {
                    Drawable drawable = null;
                    try {
                        drawable = Drawable.createFromStream(new URL(url).openStream(), "image.png");
                    } catch (IOException e) {
                    }
                    ((ImageView) LazyLoadImageActivity.this.findViewById(id)).setImageDrawable(drawable);
                }
            });
    }
     //採用handler+Thread模式實現多執行緒非同步載入
     private void loadImage2(final String url, final int id) {
         Thread thread = new Thread(){
             @Override
             public void run() {
               Drawable drawable = null;
                    try {
                        drawable = Drawable.createFromStream(new URL(url).openStream(), "image.png");
                    } catch (IOException e) {
                    }

                Message message= handler2.obtainMessage() ;
                 message.arg1 = id;
                 message.obj = drawable;
                 handler2.sendMessage(message);
             }
         };
         thread.start();
         thread = null;
    }
    // 引入執行緒池來管理多執行緒
    private void loadImage3(final String url, final int id) {
        executorService.submit(new Runnable() {
            public void run() {
                try {
                    final Drawable drawable = Drawable.createFromStream(new URL(url).openStream(), "image.png");
                    handler.post(new Runnable() {

                        public void run() {
                            ((ImageView) LazyLoadImageActivity.this.findViewById(id)).setImageDrawable(drawable);
                        }
                    });
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }
    //引入執行緒池,並引入記憶體快取功能,並對外部呼叫封裝了介面,簡化呼叫過程
    private void loadImage4(final String url, final int id) {
          //如果快取過就會從快取中取出影象,ImageCallback介面中方法也不會被執行
         Drawable cacheImage = asyncImageLoader.loadDrawable(url,new AsyncImageLoader.ImageCallback() {
             //請參見實現:如果第一次載入url時下面方法會執行
             public void imageLoaded(Drawable imageDrawable) {
               ((ImageView) findViewById(id)).setImageDrawable(imageDrawable);
             }
         });
        if(cacheImage!=null){
          ((ImageView) findViewById(id)).setImageDrawable(cacheImage);
        }
    }

    //採用Handler+Thread+封裝外部介面
    private void loadImage5(final String url, final int id) {
          //如果快取過就會從快取中取出影象,ImageCallback介面中方法也不會被執行
         Drawable cacheImage = asyncImageLoader3.loadDrawable(url,new AsyncImageLoader3.ImageCallback() {
             //請參見實現:如果第一次載入url時下面方法會執行
             public void imageLoaded(Drawable imageDrawable) {
               ((ImageView) findViewById(id)).setImageDrawable(imageDrawable);
             }
         });
        if(cacheImage!=null){
                    ((ImageView) findViewById(id)).setImageDrawable(cacheImage);
        }
    }


}

xml檔案大致如下:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="fill_parent"
              android:orientation="vertical"
              android:layout_height="fill_parent" >
  <ImageView android:id="@+id/image1" android:layout_height="wrap_content" android:layout_width="fill_parent"></ImageView>
   <ImageView android:id="@+id/image2" android:layout_height="wrap_content" android:layout_width="fill_parent"></ImageView>
    <ImageView android:id="@+id/image3" android:layout_height="wrap_content" android:layout_width="fill_parent"></ImageView>
    <ImageView android:id="@+id/image5" android:layout_height="wrap_content" android:layout_width="fill_parent"></ImageView>
    <ImageView android:id="@+id/image4" android:layout_height="wrap_content" android:layout_width="fill_parent"></ImageView>
</LinearLayout>