原文地址:http://developer.android.com/training/displaying-bitmaps/manage-memory.html html
在圖片緩存那節,已經介紹了關於垃圾回收和圖片重用的一些問題,被推薦的策略是依賴於android的版本的BitmapFun例子就包行了如何有效的在不一樣android版本中展現圖片。java
先奠基本節課的基礎,說明下如何在android中管理圖片緩存:android
一、在android2.2及以前的版本中,垃圾回收器要收集時,應用線程會被中止,這會致使延遲和性能下降。android2.3引入的併發式垃圾收集器,意味着若是圖片不被引用將被當即回收。緩存
二、在android2.3.3和以前的版本,返回的像素數據是存儲在一個本地內存中。他是獨立於位圖自己的(位圖自己是存儲在虛擬機的堆棧中)。存儲在本地內存中的像素數據不會有規律的被釋放。這回致使應用可能超出他的內存限制並奔潰。從android3.0開始,像素數據存儲在虛擬機的堆棧中與位圖相關聯。併發
下面將介紹如何在不一樣的android版本中操做圖片緩存的管理。ide
在android2.3.3及以前管理圖片緩存性能
在android2.3.3及以前的版本,使用recycle()是被推薦的,若是你的應用展現大量的圖片,你可能會遇到內存溢出的問題。使用recycle()會使應用快速回收緩存。
ui
使用recycle()時要確保圖片對象再也不被使用,他使用mDisplayRefCount和mCacheRefCount兩個參數來判斷圖片是否在展現或是在緩存中。只有在如下條件知足時圖片纔會回收:this
一、引用數mDisplayRefCount和mCacheRefcount爲0spa
二、圖片對象爲null,還沒被回收
private int mCacheRefCount = 0; private int mDisplayRefCount = 0; ... // Notify the drawable that the displayed state has changed. // Keep a count to determine when the drawable is no longer displayed. public void setIsDisplayed(boolean isDisplayed) { synchronized (this) { if (isDisplayed) { mDisplayRefCount++; mHasBeenDisplayed = true; } else { mDisplayRefCount--; } } // Check to see if recycle() can be called. checkState(); } // Notify the drawable that the cache state has changed. // Keep a count to determine when the drawable is no longer being cached. public void setIsCached(boolean isCached) { synchronized (this) { if (isCached) { mCacheRefCount++; } else { mCacheRefCount--; } } // Check to see if recycle() can be called. checkState(); } private synchronized void checkState() { // If the drawable cache and display ref counts = 0, and this drawable // has been displayed, then recycle. if (mCacheRefCount <= 0 && mDisplayRefCount <= 0 && mHasBeenDisplayed && hasValidBitmap()) { getBitmap().recycle(); } } private synchronized boolean hasValidBitmap() { Bitmap bitmap = getBitmap(); return bitmap != null && !bitmap.isRecycled(); }
在Android3.0及以後管理緩存
在android3.0包含了BitmapFactory.Options.InBitmap屬性。若是設置了這個參數,解析時會試圖重用以存在的緩存,這樣圖片緩存會被重複利用。然而使用inBitmap是有限制的。在Android4.4以前,只支持比較圖片的大小。
保存一個圖片爲以後使用
接下來的例子將會介紹如何存儲一個圖片爲以後使用。當應用是運行在Android3.0及以後的版本,而且圖片是存儲在LruCache中,那個一個軟引用在HashSet的圖片就有可能在以後被重用經過inBitmap參數。
Set<SoftReference<Bitmap>> mReusableBitmaps; private LruCache<String, BitmapDrawable> mMemoryCache; // If you're running on Honeycomb or newer, create a // synchronized HashSet of references to reusable bitmaps. if (Utils.hasHoneycomb()) { mReusableBitmaps = Collections.synchronizedSet(new HashSet<SoftReference<Bitmap>>()); } mMemoryCache = new LruCache<String, BitmapDrawable>(mCacheParams.memCacheSize) { // Notify the removed entry that is no longer being cached. @Override protected void entryRemoved(boolean evicted, String key, BitmapDrawable oldValue, BitmapDrawable newValue) { if (RecyclingBitmapDrawable.class.isInstance(oldValue)) { // The removed entry is a recycling drawable, so notify it // that it has been removed from the memory cache. ((RecyclingBitmapDrawable) oldValue).setIsCached(false); } else { // The removed entry is a standard BitmapDrawable. if (Utils.hasHoneycomb()) { // We're running on Honeycomb or later, so add the bitmap // to a SoftReference set for possible use with inBitmap later. mReusableBitmaps.add (new SoftReference<Bitmap>(oldValue.getBitmap())); } } } .... }
使用一個已經存在的圖片
public static Bitmap decodeSampledBitmapFromFile(String filename, int reqWidth, int reqHeight, ImageCache cache) { final BitmapFactory.Options options = new BitmapFactory.Options(); ... BitmapFactory.decodeFile(filename, options); ... // If we're running on Honeycomb or newer, try to use inBitmap. if (Utils.hasHoneycomb()) { addInBitmapOptions(options, cache); } ... return BitmapFactory.decodeFile(filename, options); }
private static void addInBitmapOptions(BitmapFactory.Options options, ImageCache cache) { // inBitmap only works with mutable bitmaps, so force the decoder to // return mutable bitmaps. options.inMutable = true; if (cache != null) { // Try to find a bitmap to use for inBitmap. Bitmap inBitmap = cache.getBitmapFromReusableSet(options); if (inBitmap != null) { // If a suitable bitmap has been found, set it as the value of // inBitmap. options.inBitmap = inBitmap; } } } // This method iterates through the reusable bitmaps, looking for one // to use for inBitmap: protected Bitmap getBitmapFromReusableSet(BitmapFactory.Options options) { Bitmap bitmap = null; if (mReusableBitmaps != null && !mReusableBitmaps.isEmpty()) { synchronized (mReusableBitmaps) { final Iterator<SoftReference<Bitmap>> iterator = mReusableBitmaps.iterator(); Bitmap item; while (iterator.hasNext()) { item = iterator.next().get(); if (null != item && item.isMutable()) { // Check to see it the item can be used for inBitmap. if (canUseForInBitmap(item, options)) { bitmap = item; // Remove from reusable set so it can't be used again. iterator.remove(); break; } } else { // Remove from the set if the reference has been cleared. iterator.remove(); } } } } return bitmap; }
static boolean canUseForInBitmap( Bitmap candidate, BitmapFactory.Options targetOptions) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // From Android 4.4 (KitKat) onward we can re-use if the byte size of // the new bitmap is smaller than the reusable bitmap candidate // allocation byte count. int width = targetOptions.outWidth / targetOptions.inSampleSize; int height = targetOptions.outHeight / targetOptions.inSampleSize; int byteCount = width * height * getBytesPerPixel(candidate.getConfig()); return byteCount <= candidate.getAllocationByteCount(); } // On earlier versions, the dimensions must match exactly and the inSampleSize must be 1 return candidate.getWidth() == targetOptions.outWidth && candidate.getHeight() == targetOptions.outHeight && targetOptions.inSampleSize == 1; } /** * A helper function to return the byte usage per pixel of a bitmap based on its configuration. */ static int getBytesPerPixel(Config config) { if (config == Config.ARGB_8888) { return 4; } else if (config == Config.RGB_565) { return 2; } else if (config == Config.ARGB_4444) { return 2; } else if (config == Config.ALPHA_8) { return 1; } return 1; }