Java tutorial
/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intuit.qboecoui.feeds.util; import java.io.File; import java.io.FileDescriptor; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.ref.SoftReference; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import android.annotation.TargetApi; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.os.Build.VERSION_CODES; import android.os.StatFs; import android.support.v4.app.FragmentManager; import android.support.v4.util.LruCache; import com.intuit.elves.log.CustomLog; import com.intuit.elves.util.ElvesUtil; import com.intuit.qboecocomp.qbo.feeds.util.ImageCacheParams; import com.intuit.qboecoui.BuildConfig; import com.jakewharton.disklrucache.DiskLruCache; /** * This class handles disk and memory caching of bitmaps in conjunction with the * {@link ImageWorker} class and its subclasses. Use * {@link ImageCache#getInstance(FragmentManager, ImageCacheParams)} to get an instance of this * class, although usually a cache should be added directly to an {@link ImageWorker} by calling * {@link ImageWorker#addImageCache(FragmentManager, ImageCacheParams)}. */ public class ImageCache { private static final String TAG = "ImageCache"; private static final int DISK_CACHE_INDEX = 0; private DiskLruCache mDiskLruCache; private LruCache<String, BitmapDrawable> mMemoryCache; private ImageCacheParams mCacheParams; private final Object mDiskCacheLock = new Object(); private boolean mDiskCacheStarting = true; private boolean mEvictAndRecycle = false; private Set<SoftReference<Bitmap>> mReusableBitmaps; /** * Create a new ImageCache object using the specified parameters. This should not be * called directly by other classes, instead use * {@link ImageCache#getInstance(FragmentManager, ImageCacheParams)} to fetch an ImageCache * instance. * * @param cacheParams The cache parameters to use to initialize the cache */ private ImageCache(ImageCacheParams cacheParams) { init(cacheParams); } /** * Return an {@link ImageCache} instance. A {@link RetainFragment} is used to retain the * ImageCache object across configuration changes such as a change in device orientation. * * @param fragmentManager The fragment manager to use when dealing with the retained fragment. * @param cacheParams The cache parameters to use if the ImageCache needs instantiation. * @return An existing retained ImageCache object or a new one if one did not exist */ public static ImageCache getInstance(FragmentManager fragmentManager, ImageCacheParams cacheParams) { return new ImageCache(cacheParams); } /** * Initialize the cache, providing all parameters. * * @param cacheParams The cache parameters to initialize the cache */ private void init(ImageCacheParams cacheParams) { mCacheParams = cacheParams; // Set up memory cache if (mCacheParams.memoryCacheEnabled) { if (BuildConfig.DEBUG) { CustomLog.logDebug(TAG, "[Feed] ImageCache:Memory cache created (size = " + mCacheParams.memCacheSize + ")"); } // If we're running on Honeycomb or newer, create a set of reusable bitmaps that can be // populated into the inBitmap field of BitmapFactory.Options. Note that the set is // of SoftReferences which will actually not be very effective due to the garbage // collector being aggressive clearing Soft/WeakReferences. A better approach // would be to use a strongly references bitmaps, however this would require some // balancing of memory usage between this set and the bitmap LruCache. It would also // require knowledge of the expected size of the bitmaps. From Honeycomb to JellyBean // the size would need to be precise, from KitKat onward the size would just need to // be the upper bound (due to changes in how inBitmap can re-use 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()) { if (mEvictAndRecycle) { //QBM Mobile:: Take more control of Bitmap memory management. Bitmap recycleBitmap = oldValue.getBitmap(); if (recycleBitmap != null) { recycleBitmap.recycle(); recycleBitmap = null; } } else { // 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())); } } } } /** * Measure item size in kilobytes rather than units which is more practical * for a bitmap cache */ @Override protected int sizeOf(String key, BitmapDrawable value) { final int bitmapSize = getBitmapSize(value) / 1024; return bitmapSize == 0 ? 1 : bitmapSize; } }; } // By default the disk cache is not initialized here as it should be initialized // on a separate thread due to disk access. if (cacheParams.initDiskCacheOnCreate) { // Set up disk cache initDiskCache(); } } /** * Initializes the disk cache. Note that this includes disk access so this should not be * executed on the main/UI thread. By default an ImageCache does not initialize the disk * cache when it is created, instead you should call initDiskCache() to initialize it on a * background thread. */ public void initDiskCache() { // Set up disk cache synchronized (mDiskCacheLock) { if (mDiskLruCache == null || mDiskLruCache.isClosed()) { final File diskCacheDir = mCacheParams.diskCacheDir; if (mCacheParams.diskCacheEnabled && diskCacheDir != null) { if (!diskCacheDir.exists()) { diskCacheDir.mkdirs(); } if (getUsableSpace(diskCacheDir) > mCacheParams.diskCacheSize) { try { mDiskLruCache = DiskLruCache.open(diskCacheDir, 1, 1, mCacheParams.diskCacheSize); if (BuildConfig.DEBUG) { CustomLog.logDebug(TAG, "[Feed] ImageCache:Disk cache initialized"); } } catch (final IOException e) { mCacheParams.diskCacheDir = null; CustomLog.logError(TAG, e, "[Feed] ImageCache:initDiskCache exception"); } } } } mDiskCacheStarting = false; mDiskCacheLock.notifyAll(); } } /** * Adds a bitmap to both memory and disk cache. * @param value The bitmap drawable to store */ public void addBitmapToCache(String keyString, BitmapDrawable value) { if (keyString == null || value == null) { return; } CustomLog.logDebug(TAG, "[Feed] ImageCache:addBitmapToCache - for : " + keyString); // Add to memory cache if (mMemoryCache != null) { if (RecyclingBitmapDrawable.class.isInstance(value)) { // The removed entry is a recycling drawable, so notify it // that it has been added into the memory cache ((RecyclingBitmapDrawable) value).setIsCached(true); } mMemoryCache.put(keyString, value); CustomLog.logDebug(TAG, "[Feed] ImageCache:addBitmapToCache - added in LRU cache"); } synchronized (mDiskCacheLock) { // Add to disk cache if (mDiskLruCache != null) { final String key = ImageCacheParams.hashKeyForDisk(keyString); OutputStream out = null; try { final DiskLruCache.Snapshot snapshot = mDiskLruCache.get(key); if (snapshot == null) { final DiskLruCache.Editor editor = mDiskLruCache.edit(key); if (editor != null) { out = editor.newOutputStream(DISK_CACHE_INDEX); value.getBitmap().compress(mCacheParams.compressFormat, mCacheParams.compressQuality, out); editor.commit(); out.close(); CustomLog.logDebug(TAG, "[Feed] ImageCache:addBitmapToCache - added in Disk cache"); flush(); } } else { snapshot.getInputStream(DISK_CACHE_INDEX).close(); } } catch (final IOException e) { CustomLog.logError(TAG, e, "[Feed] ImageCache:addBitmapToCache IOexception"); } catch (final Exception e) { CustomLog.logError(TAG, e, "[Feed] ImageCache:addBitmapToCache exception"); } finally { try { if (out != null) { out.close(); } } catch (final IOException e) { } } } } } /** * Get from memory cache. * * @param data Unique identifier for which item to get * @return The bitmap drawable if found in cache, null otherwise */ public BitmapDrawable getBitmapFromMemCache(String data) { BitmapDrawable memValue = null; if (mMemoryCache != null) { memValue = mMemoryCache.get(data); } if (memValue != null) { CustomLog.logDebug(TAG, "[Feed] ImageCache:Memory cache hit for : " + data); } return memValue; } /** * Get from disk cache. * * @param data Unique identifier for which item to get * @return The bitmap if found in cache, null otherwise */ public Bitmap getBitmapFromDiskCache(String data) { final String key = ImageCacheParams.hashKeyForDisk(data); Bitmap bitmap = null; synchronized (mDiskCacheLock) { while (mDiskCacheStarting) { try { mDiskCacheLock.wait(); } catch (final InterruptedException e) { } } if (mDiskLruCache != null) { InputStream inputStream = null; try { final DiskLruCache.Snapshot snapshot = mDiskLruCache.get(key); if (snapshot != null) { CustomLog.logDebug(TAG, "[Feed] ImageCache:Disk cache hit for : " + data); inputStream = snapshot.getInputStream(DISK_CACHE_INDEX); if (inputStream != null) { final FileDescriptor fd = ((FileInputStream) inputStream).getFD(); // Decode bitmap, but we don't want to sample so give // MAX_VALUE as the target dimensions bitmap = ImageResizer.decodeSampledBitmapFromDescriptor(fd, Integer.MAX_VALUE, Integer.MAX_VALUE, this); } } } catch (final IOException e) { CustomLog.logError(TAG, e, "[Feed] ImageCache:getBitmapFromDiskCache exception"); } finally { try { if (inputStream != null) { inputStream.close(); } } catch (final IOException e) { } } } return bitmap; } } /** * @param options - BitmapFactory.Options with out* options populated * @return Bitmap that case be used 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; } /** * Clears both the memory and disk cache associated with this ImageCache object. Note that * this includes disk access so this should not be executed on the main/UI thread. */ public void clearCache() { if (mMemoryCache != null) { mMemoryCache.evictAll(); if (BuildConfig.DEBUG) { CustomLog.logDebug(TAG, "[Feed] ImageCache:Memory cache cleared"); } } synchronized (mDiskCacheLock) { mDiskCacheStarting = true; if (mDiskLruCache != null && !mDiskLruCache.isClosed()) { try { mDiskLruCache.delete(); if (BuildConfig.DEBUG) { CustomLog.logDebug(TAG, "[Feed] ImageCache:Disk cache cleared"); } } catch (final IOException e) { CustomLog.logError(TAG, e, "[Feed] ImageCache:clearCache exception"); } mDiskLruCache = null; initDiskCache(); } } } /** * Flushes the disk cache associated with this ImageCache object. Note that this includes * disk access so this should not be executed on the main/UI thread. */ public void flush() { synchronized (mDiskCacheLock) { if (mDiskLruCache != null) { try { mDiskLruCache.flush(); if (BuildConfig.DEBUG) { CustomLog.logDebug(TAG, "[Feed] ImageCache:Disk cache flushed"); } } catch (final IOException e) { CustomLog.logError(TAG, e, "[Feed] ImageCache:flush - "); } } } } /** * Closes the disk cache associated with this ImageCache object. Note that this includes * disk access so this should not be executed on the main/UI thread. */ public void close() { synchronized (mDiskCacheLock) { if (mDiskLruCache != null) { try { if (!mDiskLruCache.isClosed()) { mDiskLruCache.close(); mDiskLruCache = null; if (BuildConfig.DEBUG) { CustomLog.logDebug(TAG, "[Feed] ImageCache:Disk cache closed"); } } } catch (final Exception e) { CustomLog.logError(TAG, e, "[Feed] ImageCache:close - "); } } } //QBM Mobile: Release all the bit maps for better memory management if (mMemoryCache != null) { mEvictAndRecycle = true; mMemoryCache.evictAll(); // now remove the reusable bit maps if (mReusableBitmaps != null && !mReusableBitmaps.isEmpty()) { synchronized (mReusableBitmaps) { final Iterator<SoftReference<Bitmap>> iterator = mReusableBitmaps.iterator(); Bitmap item; while (iterator.hasNext()) { item = iterator.next().get(); if (item != null) { item.recycle(); item = null; } } mReusableBitmaps.clear(); } } } } /** * @param candidate - Bitmap to check * @param targetOptions - Options that have the out* value populated * @return true if <code>candidate</code> can be used for inBitmap re-use with * <code>targetOptions</code> */ //@TargetApi(VERSION_CODES.KITKAT) private static boolean canUseForInBitmap(Bitmap candidate, BitmapFactory.Options targetOptions) { // if (!Utils.hasKitKat()) { // 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; // } // 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(); } /** * Return the byte usage per pixel of a bitmap based on its configuration. * @param config The bitmap configuration. * @return The byte usage per pixel. */ private 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; } /** * Get the size in bytes of a bitmap in a BitmapDrawable. Note that from Android 4.4 (KitKat) * onward this returns the allocated memory size of the bitmap which can be larger than the * actual bitmap data byte count (in the case it was re-used). * * @param value * @return size in bytes */ // @TargetApi(VERSION_CODES.KITKAT) public static int getBitmapSize(BitmapDrawable value) { final Bitmap bitmap = value.getBitmap(); // From KitKat onward use getAllocationByteCount() as allocated bytes can potentially be // larger than bitmap byte count. // if (Utils.hasKitKat()) { // return bitmap.getAllocationByteCount(); // } if (Utils.hasHoneycombMR1()) { return bitmap.getByteCount(); } // Pre HC-MR1 return bitmap.getRowBytes() * bitmap.getHeight(); } /* (non-Javadoc) * @see java.lang.Object#finalize() */ @Override protected void finalize() throws Throwable { super.finalize(); mReusableBitmaps = null; mMemoryCache = null; } /** * Check how much usable space is available at a given path. * * @param path The path to check * @return The space available in bytes */ @TargetApi(VERSION_CODES.GINGERBREAD) public static long getUsableSpace(File path) { if (ElvesUtil.hasGingerbread()) { return path.getUsableSpace(); } final StatFs stats = new StatFs(path.getPath()); return (long) stats.getBlockSize() * (long) stats.getAvailableBlocks(); } }