android管理bitmap的記憶體

來源:互聯網
上載者:User

android管理bitmap的記憶體
除了緩衝bitmap之外,你還能做其他一些事情來最佳化GC和bitmap的複用。推薦的策略取決於Android的系統版本。附件中的例子會向你展示如何設計app以便在不同的Android版本中提高app的記憶體效能。 在不同的Android版本中,bitmap的記憶體管理有所不同。 在Android2.2(api level8)和之前的版本中,當GC觸發的時候,App的主線程將會停止。這會導致一個明顯的卡頓,並降低使用者體驗。從Android2.3開始加入了並發GC,這意味著只要bitmap不再被引用,記憶體將會馬上被回收。 在Android2.3.3(api level 10)和以前的版本中,bitmap的像素資料儲存在底層記憶體中,而bitmap本身是儲存在虛擬機器的heap中。儲存在底層記憶體中的像素資料的回收是不可預測的,這會很容易引起App超過記憶體限制並且崩潰。在Android3.0以後,bitmap和關聯的像素資料都儲存在虛擬機器的heap中。 下面將介紹在不同的Android版本中如何最佳化bitmap的記憶體。 1.在Android2.3.3和之前版本中管理記憶體。 在Android2.3.3和之前的版本中,推薦使用recycle()方法來管理記憶體。如果在App中顯示很大的圖片,將很有可能引起 OutOfMemoryError異常。recycle()方法允許APP儘快回收記憶體。需要注意的是,只能在你確定bitmap不會再被使用時才能調用recycle()方法。如果後續要顯示一個已經調用過recycle()方法的bitmap,你將會得到Canvas: trying to use a recycled bitmap”異常。 以下的程式碼片段顯示調用recycle()方法的一個例子。這裡使用引用計數的方式來跟蹤現在正在顯示的和正在緩衝中的bitmap(變數mDisplayRefCount和mCacheRefCount)。當滿足下面兩個條件時將會執行圖片回收。 1)mDisplayRefCount和mCacheRefCount同時為0。 2)bitmap不為null,並且沒有調用過recycle()方法。

private int mCacheRefCount = 0;private int mDisplayRefCount = 0;...// drawable的顯示狀態發生改變.// 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();}
2.管理Android3.0和更高版本的記憶體 Android3.0(API level 11)新增了 BitmapFactory.Options.inBitmap欄位。如果這個選項被設定,那麼使用該Options 的decode方法將會嘗試複用一個已經存在的bitmap來載入新的bitmap。這意味著bitmap的記憶體將被複用,避免分配和釋放記憶體來提升效能。然後,使用inBitmap有一些限制。特別是在Android4.4(API level19)之前,只有尺寸相同的bitmap才能使用該特性。 以下程式碼片段顯示如何在APP中儲存一個現有的bitmap以便以後的複用。APP運行在Android3.0和更高版本中,當bitmap被LruCache釋放,使用一個HashSet來持有該bitmap的一個軟引用(soft reference)以便將來通過inBitmap來複用。
Set> mReusableBitmaps;private LruCache 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>());}mMemoryCache = new LruCache(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(oldValue.getBitmap()));            }        }    }....}
在APP運行中,以下方法檢查是否存在可以被複用的bitmap。
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);}

上述代碼中的addInBitmapOptions()方法具體實現如下所示。它用來尋找一個已存在的bitmap用來設定 inBitmap欄位。要注意該方法如果找到合適的bitmap只會設定 inBitmap欄位(你的代碼不應該假定總是能尋找到匹配)。
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> 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;}
最後,通過下面方法來判斷當前的bitmap是否滿足使用inBitmap的尺寸要求。
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;}

 





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.