Android Training要件(7)メモリ管理


2.3.3以降:
2つの整形変数を定義することによってbitmapがdisplayしたか、キャッシュ中であるかを検出します.
次のコードはbitmapが2つの条件を満たすと回収されます.
1.両方の整形変数が0になる
2.bitmapは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以上のバージョンのメモリ管理
BitmapFactory.Options.inBitmap:デコーダは既存のビットマップオブジェクトを再利用しようとします.
4.4以前に以下の要求があった
•再利用されるビットマップオブジェクトは、ソースコンテンツのサイズと一致し、JPEGまたはPNG形式である必要があります.
•inSampleSizeは1に設定する必要があります
•再利用されたビットマップのconfigurationはinPreferredConfig設定を上書きします.
•復号方法で返されるビットマップオブジェクトを使用します.再利用されたビットマップがまだ使えるとは限らない
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())); 
            } 
        } 
    } 
.... 
}




Decodeメソッドは、既存のビットマップが使用可能かどうかを確認します.
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; 
}