Listview異步加載圖片之優化篇(有圖有碼有解釋)

分類: Android平臺

在APP應用中,listview的異步加載圖片方式能夠帶來很好的用戶體驗,同時也是考量程序性能的一個重要指標。關於listview的異步加載,網上其實很多示例了,中心思想都差不多,不過很多版本或是有bug,或是有性能問題有待優化。有鑑於此,本人在網上找了個相對理想的版本並在此基礎上進行改造,下面就讓在下闡述其原理以探索箇中奧祕,與諸君共賞…


貼張效果圖先:


         異步加載圖片基本思想:

1.      先從內存緩存中獲取圖片顯示(內存緩衝)

2.      獲取不到的話從SD卡里獲取(SD卡緩衝)

3.      都獲取不到的話從網絡下載圖片並保存到SD卡同時加入內存並顯示(視情況看是否要顯示)


OK,先上adapter的代碼:


點擊(此處)摺疊或打開

  1. public class LoaderAdapter extends BaseAdapter{
  2.  
  3.         private static final String TAG = "LoaderAdapter";
  4.         private boolean mBusy = false;
  5.  
  6.         public void setFlagBusy(boolean busy) {
  7.                 this.mBusy = busy;
  8.         }
  9.  
  10.          
  11.         private ImageLoader mImageLoader;
  12.         private int mCount;
  13.         private Context mContext;
  14.         private String[] urlArrays;
  15.          
  16.          
  17.         public LoaderAdapter(int count, Context context, String []url) {
  18.                 this.mCount = count;
  19.                 this.mContext = context;
  20.                 urlArrays = url;
  21.                 mImageLoader = new ImageLoader(context);
  22.         }
  23.          
  24.         public ImageLoader getImageLoader(){
  25.                 return mImageLoader;
  26.         }
  27.  
  28.         @Override
  29.         public int getCount() {
  30.                 return mCount;
  31.         }
  32.  
  33.         @Override
  34.         public Object getItem(int position) {
  35.                 return position;
  36.         }
  37.  
  38.         @Override
  39.         public long getItemId(int position) {
  40.                 return position;
  41.         }
  42.  
  43.         @Override
  44.         public View getView(int position, View convertView, ViewGroup parent) {
  45.  
  46.                 ViewHolder viewHolder = null;
  47.                 if (convertView == null) {
  48.                         convertView = LayoutInflater.from(mContext).inflate(
  49.                                         R.layout.list_item, null);
  50.                         viewHolder = new ViewHolder();
  51.                         viewHolder.mTextView = (TextView) convertView
  52.                                         .findViewById(R.id.tv_tips);
  53.                         viewHolder.mImageView = (ImageView) convertView
  54.                                         .findViewById(R.id.iv_image);
  55.                         convertView.setTag(viewHolder);
  56.                 } else {
  57.                         viewHolder = (ViewHolder) convertView.getTag();
  58.                 }
  59.                 String url = "";
  60.                 url = urlArrays[position % urlArrays.length];
  61.                  
  62.                 viewHolder.mImageView.setImageResource(R.drawable.ic_launcher);
  63.                  
  64.  
  65.                 if (!mBusy) {
  66.                         mImageLoader.DisplayImage(url, viewHolder.mImageView, false);
  67.                         viewHolder.mTextView.setText("--" + position
  68.                                         + "--IDLE ||TOUCH_SCROLL");
  69.                 } else {
  70.                         mImageLoader.DisplayImage(url, viewHolder.mImageView, true);                
  71.                         viewHolder.mTextView.setText("--" + position + "--FLING");
  72.                 }
  73.                 return convertView;
  74.         }
  75.  
  76.         static class ViewHolder {
  77.                 TextView mTextView;
  78.                 ImageView mImageView;
  79.         }
  80. }
關鍵代碼是ImageLoader的DisplayImage方法,再看ImageLoader的實現


點擊(此處)摺疊或打開

  1. public class ImageLoader {
  2.  
  3.         private MemoryCache memoryCache = new MemoryCache();
  4.         private AbstractFileCache fileCache;
  5.         private Map<ImageView, String> imageViews = Collections
  6.                         .synchronizedMap(new WeakHashMap<ImageView, String>());
  7.         // 線程池
  8.         private ExecutorService executorService;
  9.  
  10.         public ImageLoader(Context context) {
  11.                 fileCache = new FileCache(context);
  12.                 executorService = Executors.newFixedThreadPool(5);
  13.         }
  14.  
  15.         // 最主要的方法
  16.         public void DisplayImage(String url, ImageView imageView, boolean isLoadOnlyFromCache) {
  17.                 imageViews.put(imageView, url);
  18.                 // 先從內存緩存中查找
  19.  
  20.                 Bitmap bitmap = memoryCache.get(url);
  21.                 if (bitmap != null)
  22.                         imageView.setImageBitmap(bitmap);
  23.                 else if (!isLoadOnlyFromCache){
  24.                          
  25.                         // 若沒有的話則開啓新線程加載圖片
  26.                         queuePhoto(url, imageView);
  27.                 }
  28.         }
  29.  
  30.         private void queuePhoto(String url, ImageView imageView) {
  31.                 PhotoToLoad p = new PhotoToLoad(url, imageView);
  32.                 executorService.submit(new PhotosLoader(p));
  33.         }
  34.  
  35.         private Bitmap getBitmap(String url) {
  36.                 File f = fileCache.getFile(url);
  37.                  
  38.                 // 先從文件緩存中查找是否有
  39.                 Bitmap b = null;
  40.                 if (!= null && f.exists()){
  41.                         b = decodeFile(f);
  42.                 }
  43.                 if (!= null){
  44.                         return b;
  45.                 }
  46.                 // 最後從指定的url中下載圖片
  47.                 try {
  48.                         Bitmap bitmap = null;
  49.                         URL imageUrl = new URL(url);
  50.                         HttpURLConnection conn = (HttpURLConnection) imageUrl
  51.                                         .openConnection();
  52.                         conn.setConnectTimeout(30000);
  53.                         conn.setReadTimeout(30000);
  54.                         conn.setInstanceFollowRedirects(true);
  55.                         InputStream is = conn.getInputStream();
  56.                         OutputStream os = new FileOutputStream(f);
  57.                         CopyStream(is, os);
  58.                         os.close();
  59.                         bitmap = decodeFile(f);
  60.                         return bitmap;
  61.                 } catch (Exception ex) {
  62.                         Log.e("", "getBitmap catch Exception...\nmessage = " + ex.getMessage());
  63.                         return null;
  64.                 }
  65.         }
  66.  
  67.         // decode這個圖片並且按比例縮放以減少內存消耗,虛擬機對每張圖片的緩存大小也是有限制的
  68.         private Bitmap decodeFile(File f) {
  69.                 try {
  70.                         // decode image size
  71.                         BitmapFactory.Options o = new BitmapFactory.Options();
  72.                         o.inJustDecodeBounds = true;
  73.                         BitmapFactory.decodeStream(new FileInputStream(f), null, o);
  74.  
  75.                         // Find the correct scale value. It should be the power of 2.
  76.                         final int REQUIRED_SIZE = 100;
  77.                         int width_tmp = o.outWidth, height_tmp = o.outHeight;
  78.                         int scale = 1;
  79.                         while (true) {
  80.                                 if (width_tmp / 2 < REQUIRED_SIZE
  81.                                                 || height_tmp / 2 < REQUIRED_SIZE)
  82.                                         break;
  83.                                 width_tmp /= 2;
  84.                                 height_tmp /= 2;
  85.                                 scale *= 2;
  86.                         }
  87.  
  88.                         // decode with inSampleSize
  89.                         BitmapFactory.Options o2 = new BitmapFactory.Options();
  90.                         o2.inSampleSize = scale;
  91.                         return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
  92.                 } catch (FileNotFoundException e) {
  93.                 }
  94.                 return null;
  95.         }
  96.  
  97.         // Task for the queue
  98.         private class PhotoToLoad {
  99.                 public String url;
  100.                 public ImageView imageView;
  101.  
  102.                 public PhotoToLoad(String u, ImageView i) {
  103.                         url = u;
  104.                         imageView = i;
  105.                 }
  106.         }
  107.  
  108.         class PhotosLoader implements Runnable {
  109.                 PhotoToLoad photoToLoad;
  110.  
  111.                 PhotosLoader(PhotoToLoad photoToLoad) {
  112.                         this.photoToLoad = photoToLoad;
  113.                 }
  114.  
  115.                 @Override
  116.                 public void run() {
  117.                         if (imageViewReused(photoToLoad))
  118.                                 return;
  119.                         Bitmap bmp = getBitmap(photoToLoad.url);
  120.                         memoryCache.put(photoToLoad.url, bmp);
  121.                         if (imageViewReused(photoToLoad))
  122.                                 return;
  123.                         BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
  124.                         // 更新的操作放在UI線程中
  125.                         Activity a = (Activity) photoToLoad.imageView.getContext();
  126.                         a.runOnUiThread(bd);
  127.                 }
  128.         }
  129.  
  130.         /**
  131.          * 防止圖片錯位
  132.          * 
  133.          * @param photoToLoad
  134.          * @return
  135.          */
  136.         boolean imageViewReused(PhotoToLoad photoToLoad) {
  137.                 String tag = imageViews.get(photoToLoad.imageView);
  138.                 if (tag == null || !tag.equals(photoToLoad.url))
  139.                         return true;
  140.                 return false;
  141.         }
  142.  
  143.         // 用於在UI線程中更新界面
  144.         class BitmapDisplayer implements Runnable {
  145.                 Bitmap bitmap;
  146.                 PhotoToLoad photoToLoad;
  147.  
  148.                 public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
  149.                         bitmap = b;
  150.                         photoToLoad = p;
  151.                 }
  152.  
  153.                 public void run() {
  154.                         if (imageViewReused(photoToLoad))
  155.                                 return;
  156.                         if (bitmap != null)
  157.                                 photoToLoad.imageView.setImageBitmap(bitmap);
  158.          
  159.                 }
  160.         }
  161.  
  162.         public void clearCache() {
  163.                 memoryCache.clear();
  164.                 fileCache.clear();
  165.         }
  166.  
  167.         public static void CopyStream(InputStream is, OutputStream os) {
  168.                 final int buffer_size = 1024;
  169.                 try {
  170.                         byte[] bytes = new byte[buffer_size];
  171.                         for (;;) {
  172.                                 int count = is.read(bytes, 0, buffer_size);
  173.                                 if (count == -1)
  174.                                         break;
  175.                                 os.write(bytes, 0, count);
  176.                         }
  177.                 } catch (Exception ex) {
  178.                         Log.e("", "CopyStream catch Exception...");
  179.                 }
  180.         }
  181. }
先從內存中加載,沒有則開啓線程從SD卡或網絡中獲取,這裏注意從SD卡獲取圖片是放在子線程裏執行的,否則快速滑屏的話會不夠流暢,這是優化一。於此同時,在adapter裏有個busy變量,表示listview是否處於滑動狀態,如果是滑動狀態則僅從內存中獲取圖片,沒有的話無需再開啓線程去外存或網絡獲取圖片,這是優化二。ImageLoader裏的線程使用了線程池,從而避免了過多線程頻繁創建和銷燬,有的童鞋每次總是new一個線程去執行這是非常不可取的,好一點的用的AsyncTask類,其實內部也是用到了線程池。在從網絡獲取圖片時,先是將其保存到sd卡,然後再加載到內存,這麼做的好處是在加載到內存時可以做個壓縮處理,以減少圖片所佔內存,這是優化三。 

而圖片錯位問題的本質源於我們的listview使用了緩存convertView,假設一種場景,一個listview一屏顯示九個item,那麼在拉出第十個item的時候,事實上該item是重複使用了第一個item,也就是說在第一個item從網絡中下載圖片並最終要顯示的時候其實該item已經不在當前顯示區域內了,此時顯示的後果將是在可能在第十個item上輸出圖像,這就導致了圖片錯位的問題。所以解決之道在於可見則顯示,不可見則不顯示。在ImageLoader裏有個imageViews的map對象,就是用於保存當前顯示區域圖像對應的url集,在顯示前判斷處理一下即可。

下面再說下內存緩衝機制,本例採用的是LRU算法,先看看MemoryCache的實現


點擊(此處)摺疊或打開

  1. public class MemoryCache {
  2.  
  3.         private static final String TAG = "MemoryCache";
  4.         // 放入緩存時是個同步操作
  5.         // LinkedHashMap構造方法的最後一個參數true代表這個map裏的元素將按照最近使用次數由少到多排列,即LRU
  6.         // 這樣的好處是如果要將緩存中的元素替換,則先遍歷出最近最少使用的元素來替換以提高效率
  7.         private Map<String, Bitmap> cache = Collections
  8.                         .synchronizedMap(new LinkedHashMap<String, Bitmap>(10, 1.5f, true));
  9.         // 緩存中圖片所佔用的字節,初始0,將通過此變量嚴格控制緩存所佔用的堆內存
  10.         private long size = 0;// current allocated size
  11.         // 緩存只能佔用的最大堆內存
  12.         private long limit = 1000000;// max memory in bytes
  13.  
  14.         public MemoryCache() {
  15.                 // use 25% of available heap size
  16.                 setLimit(Runtime.getRuntime().maxMemory() / 10);
  17.         }
  18.  
  19.         public void setLimit(long new_limit) {
  20.                 limit = new_limit;
  21.                 Log.i(TAG, "MemoryCache will use up to " + limit / 1024. / 1024. + "MB");
  22.         }
  23.  
  24.         public Bitmap get(String id) {
  25.                 try {
  26.                         if (!cache.containsKey(id))
  27.                                 return null;
  28.                         return cache.get(id);
  29.                 } catch (NullPointerException ex) {
  30.                         return null;
  31.                 }
  32.         }
  33.  
  34.         public void put(String id, Bitmap bitmap) {
  35.                 try {
  36.                         if (cache.containsKey(id))
  37.                                 size -= getSizeInBytes(cache.get(id));
  38.                         cache.put(id, bitmap);
  39.                         size += getSizeInBytes(bitmap);
  40.                         checkSize();
  41.                 } catch (Throwable th) {
  42.                         th.printStackTrace();
  43.                 }
  44.         }
  45.  
  46.         /**
  47.          * 嚴格控制堆內存,如果超過將首先替換最近最少使用的那個圖片緩存
  48.          * 
  49.          */
  50.         private void checkSize() {
  51.                 Log.i(TAG, "cache size=" + size + " length=" + cache.size());
  52.                 if (size > limit) {
  53.                         // 先遍歷最近最少使用的元素
  54.                         Iterator<Entry<String, Bitmap>> iter = cache.entrySet().iterator();
  55.                         while (iter.hasNext()) {
  56.                                 Entry<String, Bitmap> entry = iter.next();
  57.                                 size -= getSizeInBytes(entry.getValue());
  58.                                 iter.remove();
  59.                                 if (size <= limit)
  60.                                         break;
  61.                         }
  62.                         Log.i(TAG, "Clean cache. New size " + cache.size());
  63.                 }
  64.         }
  65.  
  66.         public void clear() {
  67.                 cache.clear();
  68.         }
  69.  
  70.         /**
  71.          * 圖片佔用的內存
  72.          * 
  73.          * <a href="\"http://www.eoeandroid.com/home.php?mod=space&uid=2768922\"" target="\"_blank\"">@Param</a> bitmap
  74.          * 
  75.          * @return
  76.          */
  77.         long getSizeInBytes(Bitmap bitmap) {
  78.                 if (bitmap == null)
  79.                         return 0;
  80.                 return bitmap.getRowBytes() * bitmap.getHeight();
  81.         }
  82. }

首先限制內存圖片緩衝的堆內存大小,每次有圖片往緩存里加時判斷是否超過限制大小,超過的話就從中取出最少使用的圖片並將其移除,當然這裏如果不採用這種方式,換做軟引用也是可行的,二者目的皆是最大程度的利用已存在於內存中的圖片緩存,避免重複製造垃圾增加GC負擔,OOM溢出往往皆因內存瞬時大量增加而垃圾回收不及時造成的。只不過二者區別在於LinkedHashMap裏的圖片緩存在沒有移除出去之前是不會被GC回收的,而SoftReference裏的圖片緩存在沒有其他引用保存時隨時都會被GC回收。所以在使用LinkedHashMap這種LRU算法緩存更有利於圖片的有效命中,當然二者配合使用的話效果更佳,即從LinkedHashMap裏移除出的緩存放到SoftReference裏,這就是內存的二級緩存,有興趣的童鞋不凡一試。


下面附上工程鏈接:



亦可上github下載

github下載地址:https://github.com/geniusgithub/SyncLoaderBitmapDemo

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章