android代碼解析之圖片緩衝(ImageDownloader)

來源:互聯網
上載者:User

標籤:android開發   最佳化   緩衝   imageview   hashmap   

在android代碼裡development/samples有一個工具類:ImageDownloader,其作用是從網上下載圖片顯示到給定的ImageView.如下時原文說明:

This helper class download images from the Internet and binds those with the provided ImageView.

這裡來解析一下這個工具類是如何?的,下面一個一個來解釋.

(1)首先,他採用了強引用(StrongReference)和軟引用(SoftReference)來儲存下載的圖片(bitmap),具體做法是:StrongReference來儲存一定容量的圖片(bitmap),當超過這個容量的時候就將其移入SoftReference來儲存. 

其中這裡的強StrongReference來儲存圖片(bitmap)實際上是採用LinkedHashMap來實現的! 如下代碼所示:

    private final static HashMap<String, Bitmap> sHardBitmapCache =        new LinkedHashMap<String, Bitmap>(HARD_CACHE_CAPACITY / 2, 0.75f, true) {//        private static final long serialVersionUID = -7190622541619388252L;        @Override        protected boolean removeEldestEntry(Map.Entry<String, Bitmap> eldest) {            if (size() > HARD_CACHE_CAPACITY) {                // Entries push-out of hard reference cache are transferred to soft reference cache                sSoftBitmapCache.put(eldest.getKey(), new SoftReference<Bitmap>(eldest.getValue()));                return true;            } else {                return false;            }        }    };
上面的代碼定義來一個容量為HARD_CACHE_CAPACITY / 2的LinkedHashMap(這裡的HARD_CACHE_CAPACITY可以根據你的實際情況來定義,這裡定義的是40), 並且該LinkedHashMap時按照取用來排序的,增長率時0.75. 最重要的是從寫removeEldestEntry這個方法,這樣一來,一旦超過容量就會把最後一個元素移動到sSoftBitmapCache裡面.這裡的sSoftBitmapCache其實也是一個HashMap. 那sSoftBitmapCache到底是一個什麼HashMap呢,這裡先賣一個關子.

上面說到的儲存圖片資源的時使用map的鍵值對:Map.Entry<String, Bitmap> 這裡的String是我們需要下載的圖片的路徑(也就是網路地址).

(2)每次需要擷取一個圖片的時候首先檢測sHardBitmapCache和sSoftBitmapCache是否已經存在了,否則需要開一個任務來後台下載並處理.這裡的幕後處理實際上是採用來常用的AsyncTask來實現.下面看看給一個ImageView下載圖片的入口方法:

    private void forceDownload(String url, ImageView imageView, String cookie) {        // State sanity: url is guaranteed to never be null in DownloadedDrawable and cache keys.        if (url == null) {            imageView.setImageDrawable(null);            return;        }        if (cancelPotentialDownload(url, imageView)) {            BitmapDownloaderTask task = new BitmapDownloaderTask(imageView);            DownloadedDrawable downloadedDrawable = new DownloadedDrawable(task);            imageView.setImageDrawable(downloadedDrawable);            task.execute(url, cookie);        }    }
上面代碼中需要解釋DownloadedDrawable和BitmapDownloaderTask,其中DownloadedDrawable是一個ColorDrawable, 實際上這裡可以自己定義一個預存的圖片.

    static class DownloadedDrawable extends ColorDrawable {        private final WeakReference<BitmapDownloaderTask> bitmapDownloaderTaskReference;        public DownloadedDrawable(BitmapDownloaderTask bitmapDownloaderTask) {            super(Color.BLACK);            bitmapDownloaderTaskReference =                new WeakReference<BitmapDownloaderTask>(bitmapDownloaderTask);        }        public BitmapDownloaderTask getBitmapDownloaderTask() {            return bitmapDownloaderTaskReference.get();        }    }
實際上DownloadedDrawable還緩衝來他自己的BitmapDownloaderTask,後面就知道什麼用了.
BitmapDownloaderTask其實就是一個AsyncTask,在方法doInBackground裡面採用AndroidHttpClient進行從網上下載圖片資料並儲存為Bitmap.然後在onPostExecute裡面處理擷取的bitmap

        protected void onPostExecute(Bitmap bitmap) {            if (isCancelled()) {                bitmap = null;            }            // Add bitmap to cache            if (bitmap != null) {                synchronized (sHardBitmapCache) {                    sHardBitmapCache.put(url, bitmap);                }            }            if (imageViewReference != null) {                ImageView imageView = imageViewReference.get();                BitmapDownloaderTask bitmapDownloaderTask = getBitmapDownloaderTask(imageView);                // Change bitmap only if this process is still associated with it                if (this == bitmapDownloaderTask) {                    imageView.setImageBitmap(bitmap);                }            }        }
上面的代碼首先將擷取的bitmap緩衝到sHardBitmapCache裡面.然後找到對應的ImageView,並設定該bitmap顯示.

(3)我們現在思考一個問題: 一般來說手機的運行記憶體本來就緊張,這裡sHardBitmapCache和sSoftBitmapCache由於載入了大量的圖片資源,難免沒有上面問題,最重要的是sHardBitmapCache和sSoftBitmapCache都是static的變數.所以實際上他們儲存的資料時沒有必要一直存在的,所以只要不需要的時候就需要clear掉.

(4)最後來看看sSoftBitmapCache到底用什麼HashMap可以. 上面說了bitmap的載入實際上採用了AsyncTask的多線程方式, 所以是很可能出現多個修改並行作業的.所以採用ConcurrentHashMap最合適.ConcurrentHashMap採用了鎖分離技術可以很好的解決多操作並發進行,並且也是安全執行緒的.

    // Soft cache for bitmap kicked out of hard cache    private final static ConcurrentHashMap<String, SoftReference<Bitmap>> sSoftBitmapCache =        new ConcurrentHashMap<String, SoftReference<Bitmap>>(HARD_CACHE_CAPACITY / 2);

android代碼解析之圖片緩衝(ImageDownloader)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.