Android中ListView是使用平率最高的控制項之一(GridView跟ListView是兄弟,都是繼承AbsListView),ListView最佳化最有效無非就是採用ViewHolder來減少頻繁的對view查詢和更新,緩衝圖片加快解碼,減小圖片尺寸。
關於listview的非同步載入,網上其實很多樣本了,中心思想都差不多,不過很多版本或是有bug,或是有效能問題有待最佳化,下面就讓在下闡述其原理以探索箇中奧秘在APP應用中,listview的非同步載入圖片方式能夠帶來很好的使用者體驗,同時也是考配量序效能的一個重要指標。關於listview的非同步載入,網上其實很多樣本了,中心思想都差不多,不過很多版本或是有bug,或是有效能問題有待最佳化。有鑒於此,本人在網上找了個相對理想的版本並在此基礎上進行改造,下面就讓在下闡述其原理以探索箇中奧秘,與諸君共賞…
非同步載入圖片基本思想:
1.先從記憶體緩衝中擷取圖片顯示(記憶體緩衝)
2.擷取不到的話從SD卡裡擷取(SD卡緩衝)
3.都擷取不到的話從網路下載圖片並儲存到SD卡同時加入記憶體並顯示(視情況看是否要顯示)
OK,先上adapter的代碼:
public class LoaderAdapter extends BaseAdapter{ private static final String TAG = "LoaderAdapter"; private boolean mBusy = false; public void setFlagBusy(boolean busy) { this.mBusy = busy; } private ImageLoader mImageLoader; private int mCount; private Context mContext; private String[] urlArrays; public LoaderAdapter(int count, Context context, String []url) { this.mCount = count; this.mContext = context; urlArrays = url; mImageLoader = new ImageLoader(context); } public ImageLoader getImageLoader(){ return mImageLoader; } @Override public int getCount() { return mCount; } @Override public Object getItem(int position) { return position; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder = null; if (convertView == null) { convertView = LayoutInflater.from(mContext).inflate( R.layout.list_item, null); viewHolder = new ViewHolder(); viewHolder.mTextView = (TextView) convertView .findViewById(R.id.tv_tips); viewHolder.mImageView = (ImageView) convertView .findViewById(R.id.iv_image); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } String url = ""; url = urlArrays[position % urlArrays.length]; viewHolder.mImageView.setImageResource(R.drawable.ic_launcher); if (!mBusy) { mImageLoader.DisplayImage(url, viewHolder.mImageView, false); viewHolder.mTextView.setText("--" + position + "--IDLE ||TOUCH_SCROLL"); } else { mImageLoader.DisplayImage(url, viewHolder.mImageView, true); viewHolder.mTextView.setText("--" + position + "--FLING"); } return convertView; } static class ViewHolder { TextView mTextView; ImageView mImageView; } }
關鍵代碼是ImageLoader的DisplayImage方法,再看ImageLoader的實現
public class ImageLoader { private MemoryCache memoryCache = new MemoryCache(); private AbstractFileCache fileCache; private Map<ImageView, String> imageViews = Collections .synchronizedMap(new WeakHashMap<ImageView, String>()); // 線程池 private ExecutorService executorService; public ImageLoader(Context context) { fileCache = new FileCache(context); executorService = Executors.newFixedThreadPool(5); } // 最主要的方法 public void DisplayImage(String url, ImageView imageView, boolean isLoadOnlyFromCache) { imageViews.put(imageView, url); // 先從記憶體緩衝中尋找 Bitmap bitmap = memoryCache.get(url); if (bitmap != null) imageView.setImageBitmap(bitmap); else if (!isLoadOnlyFromCache){ // 若沒有的話則開啟新線程載入圖片 queuePhoto(url, imageView); } } private void queuePhoto(String url, ImageView imageView) { PhotoToLoad p = new PhotoToLoad(url, imageView); executorService.submit(new PhotosLoader(p)); } private Bitmap getBitmap(String url) { File f = fileCache.getFile(url); // 先從檔案快取中尋找是否有 Bitmap b = null; if (f != null && f.exists()){ b = decodeFile(f); } if (b != null){ return b; } // 最後從指定的url中下載圖片 try { Bitmap bitmap = null; URL imageUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) imageUrl .openConnection(); conn.setConnectTimeout(30000); conn.setReadTimeout(30000); conn.setInstanceFollowRedirects(true); InputStream is = conn.getInputStream(); OutputStream os = new FileOutputStream(f); CopyStream(is, os); os.close(); bitmap = decodeFile(f); return bitmap; } catch (Exception ex) { Log.e("", "getBitmap catch Exception...\nmessage = " + ex.getMessage()); return null; } } // decode這個圖片並且按比例縮放以減少記憶體消耗,虛擬機器對每張圖片的緩衝大小也是有限制的 private Bitmap decodeFile(File f) { try { // decode image size BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; BitmapFactory.decodeStream(new FileInputStream(f), null, o); // Find the correct scale value. It should be the power of 2. final int REQUIRED_SIZE = 100; int width_tmp = o.outWidth, height_tmp = o.outHeight; int scale = 1; while (true) { if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE) break; width_tmp /= 2; height_tmp /= 2; scale *= 2; } // decode with inSampleSize BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize = scale; return BitmapFactory.decodeStream(new FileInputStream(f), null, o2); } catch (FileNotFoundException e) { } return null; } // Task for the queue private class PhotoToLoad { public String url; public ImageView imageView; public PhotoToLoad(String u, ImageView i) { url = u; imageView = i; } } class PhotosLoader implements Runnable { PhotoToLoad photoToLoad; PhotosLoader(PhotoToLoad photoToLoad) { this.photoToLoad = photoToLoad; } @Override public void run() { if (imageViewReused(photoToLoad)) return; Bitmap bmp = getBitmap(photoToLoad.url); memoryCache.put(photoToLoad.url, bmp); if (imageViewReused(photoToLoad)) return; BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad); // 更新的操作放在UI線程中 Activity a = (Activity) photoToLoad.imageView.getContext(); a.runOnUiThread(bd); } } /** * 防止圖片錯位 * * @param photoToLoad * @return */ boolean imageViewReused(PhotoToLoad photoToLoad) { String tag = imageViews.get(photoToLoad.imageView); if (tag == null || !tag.equals(photoToLoad.url)) return true; return false; } // 用於在UI線程中更新介面 class BitmapDisplayer implements Runnable { Bitmap bitmap; PhotoToLoad photoToLoad; public BitmapDisplayer(Bitmap b, PhotoToLoad p) { bitmap = b; photoToLoad = p; } public void run() { if (imageViewReused(photoToLoad)) return; if (bitmap != null) photoToLoad.imageView.setImageBitmap(bitmap); } } public void clearCache() { memoryCache.clear(); fileCache.clear(); } public static void CopyStream(InputStream is, OutputStream os) { final int buffer_size = 1024; try { byte[] bytes = new byte[buffer_size]; for (;;) { int count = is.read(bytes, 0, buffer_size); if (count == -1) break; os.write(bytes, 0, count); } } catch (Exception ex) { Log.e("", "CopyStream catch Exception..."); } } }
先從記憶體中載入,沒有則開啟線程從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的實現
public class MemoryCache { private static final String TAG = "MemoryCache"; // 放入緩衝時是個同步操作 // LinkedHashMap構造方法的最後一個參數true代表這個map裡的元素將按照最近使用次數由少到多排列,即LRU // 這樣的好處是如果要將緩衝中的元素替換,則先遍曆出最近最少使用的元素來替換以提高效率 private Map<String, Bitmap> cache = Collections .synchronizedMap(new LinkedHashMap<String, Bitmap>(10, 1.5f, true)); // 緩衝中圖片所佔用的位元組,初始0,將通過此變數嚴格控制緩衝所佔用的堆記憶體 private long size = 0;// current allocated size // 緩衝只能佔用的最大堆記憶體 private long limit = 1000000;// max memory in bytes public MemoryCache() { // use 25% of available heap size setLimit(Runtime.getRuntime().maxMemory() / 10); } public void setLimit(long new_limit) { limit = new_limit; Log.i(TAG, "MemoryCache will use up to " + limit / 1024. / 1024. + "MB"); } public Bitmap get(String id) { try { if (!cache.containsKey(id)) return null; return cache.get(id); } catch (NullPointerException ex) { return null; } } public void put(String id, Bitmap bitmap) { try { if (cache.containsKey(id)) size -= getSizeInBytes(cache.get(id)); cache.put(id, bitmap); size += getSizeInBytes(bitmap); checkSize(); } catch (Throwable th) { th.printStackTrace(); } } /** * 嚴格控制堆記憶體,如果超過將首先替換最近最少使用的那個圖片緩衝 * */ private void checkSize() { Log.i(TAG, "cache size=" + size + " length=" + cache.size()); if (size > limit) { // 先遍曆最近最少使用的元素 Iterator<Entry<String, Bitmap>> iter = cache.entrySet().iterator(); while (iter.hasNext()) { Entry<String, Bitmap> entry = iter.next(); size -= getSizeInBytes(entry.getValue()); iter.remove(); if (size <= limit) break; } Log.i(TAG, "Clean cache. New size " + cache.size()); } } public void clear() { cache.clear(); } /** * 圖片佔用的記憶體 * * <A href='\"http://www.eoeandroid.com/home.php?mod=space&uid=2768922\"' target='\"_blank\"'>@Param</A> bitmap * * @return */ long getSizeInBytes(Bitmap bitmap) { if (bitmap == null) return 0; return bitmap.getRowBytes() * bitmap.getHeight(); } }
首先限制記憶體配置圖片緩衝的堆記憶體大小,每次有圖片往緩衝裡加時判斷是否超過限制大小,超過的話就從中取出最少使用的圖片並將其移除,當然這裡如果不採用這種方式,換做軟引用也是可行的,二者目的皆是最大程度的利用已存在於記憶體中的圖片緩衝,避免重複製造垃圾增加GC負擔,OOM溢出往往皆因記憶體瞬時大量增加而記憶體回收不及時造成的。只不過二者區別在於LinkedHashMap裡的圖片緩衝在沒有移除出去之前是不會被GC回收的,而SoftReference裡的圖片緩衝在沒有其他引用儲存時隨時都會被GC回收。所以在使用LinkedHashMap這種LRU演算法緩衝更有利於圖片的有效命中,當然二者配合使用的話效果更佳,即從LinkedHashMap裡移除出的緩衝放到SoftReference裡,這就是記憶體的二級緩衝,有興趣的童鞋不凡一試。
以上所述是針對listview的非同步載入效能最佳化的全部介紹,希望對大家有所協助。