詳細講解Android圖片下載框架UniversialImageLoader之內存緩存(三)

前面的兩篇文章著重介紹的是磁盤緩存,這篇文章主要是講解一下內存緩存。對於內存緩存,也打算分兩篇文章來進行講解。在這一篇文章中,我們主要是關註三個類,

MemoryCache、BaseMemoryCache以及LimitedMemoryCache。

首先我們先看一下內存緩存的接口MemoryCache。

put(String key, Bitmap value);
Bitmap get(String key);
Bitmap remove(String key);
Collection keys();
void clear();

從上面可以看出,整體的接口的設計分為5個方法,1、存入真正的Bitmap 2、通過鍵獲取Bitmap 3、通過鍵刪除Bitmap 4、迭代獲取所有的鍵的集合 5、清空內存的緩存。

接下來我們看實現內存緩存的接口的抽象類BaseMemoryCache。

與前面的文章一樣,還是先從變量入手。

/** Stores not strong references to objects */
	private final Map<String, Reference> softMap = Collections.synchronizedMap(new HashMap<String, Reference>());

正如所說的那樣,這個變量是存儲非強引用的對象。

稍微的關註一下下面的方法

@Override
	public Bitmap get(String key) {
		Bitmap result = null;
		Reference reference = softMap.get(key);
		if (reference != null) {
			result = reference.get();
		}
		return result;
	}

通過鍵獲取軟引用中的數值Bitmap。

最後我們來看一下有限內存緩存空間的緩存類LimitedMemoryCache,從繼承關系上來看,它是對BaseMemoryCache的進一步擴展。

從變量上來看:

private static final int MAX_NORMAL_CACHE_SIZE_IN_MB = 16;
private static final int MAX_NORMAL_CACHE_SIZE = MAX_NORMAL_CACHE_SIZE_IN_MB * 1024 * 1024;
private final int sizeLimit;
private final AtomicInteger cacheSize;
private final List hardCache = Collections.synchronizedList(new LinkedList());

從變量的定義來看,包括最大的緩存的限制,當前的緩存的尺寸以及強引用對象的集合。

拿其中的對象的存儲的方法來分析一下:

public boolean put(String key, Bitmap value) {
		boolean putSuccessfully = false;
		// Try to add value to hard cache
		int valueSize = getSize(value);
		int sizeLimit = getSizeLimit();
		int curCacheSize = cacheSize.get();
		if (valueSize  sizeLimit) {
				Bitmap removedValue = removeNext();
				if (hardCache.remove(removedValue)) {
					curCacheSize = cacheSize.addAndGet(-getSize(removedValue));
				}
			}
			hardCache.add(value);
			cacheSize.addAndGet(valueSize);

			putSuccessfully = true;
		}
		// Add value to soft cache
		super.put(key, value);
		return putSuccessfully;
	}

很明顯,在緩存圖片的時候,先需要判斷一下當前的圖片的加入有沒有超過整體的緩存的內存的尺寸的限制。如果超過,先根據不同的策略,刪除優先需要刪除的圖片,如果合適,當前的圖片插入,如果不合適,繼續迭代。

Ok,關於圖片的內存緩存的第一篇先講到這裡,後面會繼續分析。希望對大傢有所幫助哦~

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *