Example usage for android.support.v4.util LruCache LruCache

List of usage examples for android.support.v4.util LruCache LruCache

Introduction

In this page you can find the example usage for android.support.v4.util LruCache LruCache.

Prototype

public LruCache(int maxSize) 

Source Link

Usage

From source file:com.manning.androidhacks.hack040.util.ImageCache.java

/**
 * Initialize the cache, providing all parameters.
 * /*from   ww w .  j ava 2 s.  c o m*/
 * @param context
 *          The context to use
 * @param cacheParams
 *          The cache parameters to initialize the cache
 */
private void init(Context context, ImageCacheParams cacheParams) {
    final File diskCacheDir = DiskLruCache.getDiskCacheDir(context, cacheParams.uniqueName);

    // Set up disk cache
    if (cacheParams.diskCacheEnabled) {
        mDiskCache = DiskLruCache.openCache(context, diskCacheDir, cacheParams.diskCacheSize);
        mDiskCache.setCompressParams(cacheParams.compressFormat, cacheParams.compressQuality);
        if (cacheParams.clearDiskCacheOnStart) {
            mDiskCache.clearCache();
        }
    }

    // Set up memory cache
    if (cacheParams.memoryCacheEnabled) {
        mMemoryCache = new LruCache<String, Bitmap>(cacheParams.memCacheSize) {
            /**
             * Measure item size in bytes rather than units which is more practical
             * for a bitmap cache
             */
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                return Utils.getBitmapSize(bitmap);
            }
        };
    }
}

From source file:io.indy.seni.util.ImageCache.java

/**
 * Initialize the cache, providing all parameters.
 *
 * @param cacheParams The cache parameters to initialize the cache
 *///from  w w  w . j ava 2  s  .  c  om
private void init(ImageCacheParams cacheParams) {
    mCacheParams = cacheParams;

    // Set up memory cache
    if (mCacheParams.memoryCacheEnabled) {
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "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).
        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) {

                // The removed entry is a standard BitmapDrawable

                // 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;
            }
        };
    }
}

From source file:com.intuit.qboecoui.feeds.util.ImageCache.java

/**
 * Initialize the cache, providing all parameters.
 *
 * @param cacheParams The cache parameters to initialize the cache
 *///  w ww  . ja v  a  2 s . co  m
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();
    }
}

From source file:com.opensource.bitmapfun.util.ImageCache.java

/**
 * Initialize the cache, providing all parameters.
 * /*from w w w.  ja  va2  s  .  c  o m*/
 * @param context The context to use
 * @param cacheParams The cache parameters to initialize the cache
 */
private void init(Context context, ImageCacheParams cacheParams) {
    mImageCacheParams = cacheParams;
    //get a cache floder
    final File diskCacheDir = DiskLruCache.getDiskCacheDir(context, cacheParams.cachePath,
            cacheParams.uniqueName);

    // Set up disk cache
    if (cacheParams.diskCacheEnabled) {
        mDiskCache = DiskLruCache.openCache(context, diskCacheDir, cacheParams.diskCacheSize);
        mDiskCache.setCompressParams(cacheParams.compressFormat, cacheParams.compressQuality);
        if (cacheParams.clearDiskCacheOnStart) {
            mDiskCache.clearCache();
        }
    }

    // Set up memory cache
    if (cacheParams.memoryCacheEnabled) {
        mMemoryCache = new LruCache<String, Bitmap>(cacheParams.memCacheSize) {
            /**
             * Measure item size in bytes rather than units which is more practical for a bitmap
             * cache
             */
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                return Utils.getBitmapSize(bitmap);
            }
        };
    }
}

From source file:net.okjsp.imageloader.ImageCache.java

/**
 * Initialize the cache, providing all parameters.
 *
 * @param context The context to use//from w  w w.  jav a  2  s  .co m
 * @param cacheParams The cache parameters to initialize the cache
 */
private void init(Context context, ImageCacheParams cacheParams) {
    final File diskCacheDir = DiskLruCache.getDiskCacheDir(context, cacheParams.uniqueName);

    if (DEBUG_LOG) {
        Log.d(TAG, "init(" + cacheParams.uniqueName + ")");
    }

    // Set up disk cache
    if (cacheParams.diskCacheEnabled) {
        mDiskCache = DiskLruCache.openCache(context, diskCacheDir, cacheParams.diskCacheSize);
        if (mDiskCache == null) {
            Log.e(TAG, "DiskLruCache.openCache returns NULL!!! " + diskCacheDir.getPath());
        } else {
            mDiskCache.setCompressParams(cacheParams.compressFormat, cacheParams.compressQuality);
            if (cacheParams.clearDiskCacheOnStart) {
                mDiskCache.clearCache();
            }
        }
    }

    // Set up memory cache
    if (cacheParams.memoryCacheEnabled) {
        mMemoryCache = new LruCache<String, Bitmap>(cacheParams.memCacheSize) {
            /**
             * Measure item size in bytes rather than units which is more practical for a bitmap
             * cache
             */
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                return ImageLoaderUtils.getBitmapSize(bitmap);
            }
        };
    }
}

From source file:fr.forexperts.ui.ArticleListFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Get max available VM memory, exceeding this amount will throw an
    // OutOfMemory exception. Stored in kilobytes as LruCache takes an
    // int in its constructor.
    final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);

    // Use 1/8th of the available memory for this memory cache.
    final int cacheSize = maxMemory / 8;

    mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
        @TargetApi(12)/*w ww . ja v a 2  s . c  om*/
        @Override
        protected int sizeOf(String key, Bitmap bitmap) {
            // The cache size will be measured in kilobytes rather than
            // number of items.
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB_MR1) {
                return bitmap.getByteCount() / 1024;
            } else {
                return bitmap.getRowBytes() * bitmap.getHeight() / 1024;
            }
        }
    };

    setHasOptionsMenu(true);
}

From source file:com.image.cache.util.ImageCache.java

/**
 * Initialize the cache, providing all parameters.
 *
 * @param cacheParams The cache parameters to initialize the cache
 *//*ww  w . j a  v a2s .  c  o  m*/
private void init(ImageCacheParams cacheParams) {
    mCacheParams = cacheParams;

    // Set up memory cache
    if (mCacheParams.memoryCacheEnabled) {
        if (CacheConfig.DEBUG) {

        }

        // If we're running on Honeycomb or newer, then
        if (Utils.hasHoneycomb()) {
            mReusableBitmaps = 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 SoftRefrence 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();
    }
}

From source file:com.abcs.sociax.gimgutil.ImageCache.java

/**
 * Initialize the cache, providing all parameters.
 * // w w w .ja  v a 2s  .  com
 * @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) {
            Log.d(TAG, "Memory cache created (size = " + mCacheParams.memCacheSize + ")");
        }
        mMemoryCache = new LruCache<String, Bitmap>(mCacheParams.memCacheSize) {
            /**
             * Measure item size in bytes rather than units which is more
             * practical for a bitmap cache
             */
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                return getBitmapSize(bitmap);
            }
        };
    }

    // 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();
    }
}

From source file:com.app.secnodhand.imageutil.ImageCache.java

/**
 * Initialize the cache, providing all parameters.
 * /*from  www . j av  a2  s .com*/
 * @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) {
            Log.d(TAG, "Memory cache created (size = " + mCacheParams.memCacheSize + ")");
        }

        // If we're running on Honeycomb or newer, then
        if (Utils.hasHoneycomb()) {
            mReusableBitmaps = 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 SoftRefrence 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();
    }
}

From source file:org.matrix.androidsdk.db.MXMediaWorkerTask.java

/**
 * Search a cached bitmap from an url.//from  w  ww  . j av a 2 s.  com
 * rotationAngle is set to Integer.MAX_VALUE when undefined : the EXIF metadata must be checked.
 *
 * @param baseFile the base file
 * @param url the media url
 * @param rotation the bitmap rotation
 * @param mimeType the mime type
 * @return the cached bitmap or null it does not exist
 */
public static Bitmap bitmapForURL(Context context, File baseFile, String url, int rotation, String mimeType) {
    Bitmap bitmap = null;

    // sanity check
    if (null != url) {

        if (null == sMemoryCache) {
            int lruSize = Math.min(20 * 1024 * 1024, (int) Runtime.getRuntime().maxMemory() / 8);

            Log.d(LOG_TAG, "bitmapForURL  lruSize : " + lruSize);

            sMemoryCache = new LruCache<String, Bitmap>(lruSize) {
                @Override
                protected int sizeOf(String key, Bitmap bitmap) {
                    return bitmap.getRowBytes() * bitmap.getHeight(); // size in bytes
                }
            };
        }

        // the image is downloading in background
        if (null != mediaWorkerTaskForUrl(url)) {
            return null;
        }

        synchronized (sMemoryCache) {
            bitmap = sMemoryCache.get(url);
        }

        if (null == bitmap) {
            // if some medias are not found
            // do not try to reload them until the next application launch.
            synchronized (mFileNotFoundUrlsList) {
                if (mFileNotFoundUrlsList.indexOf(url) >= 0) {
                    bitmap = BitmapFactory.decodeResource(context.getResources(),
                            android.R.drawable.ic_menu_gallery);
                }
            }
        }

        // check if the image has not been saved in file system
        if ((null == bitmap) && (null != baseFile)) {
            String filename = null;

            // the url is a file one
            if (url.startsWith("file:")) {
                // try to parse it
                try {
                    Uri uri = Uri.parse(url);
                    filename = uri.getPath();

                } catch (Exception e) {
                }

                // cannot extract the filename -> sorry
                if (null == filename) {
                    return null;
                }
            }

            // not a valid file name
            if (null == filename) {
                filename = buildFileName(url, mimeType);
            }

            try {
                File file = filename.startsWith(File.separator) ? new File(filename)
                        : new File(baseFile, filename);

                if (!file.exists()) {
                    Log.d(LOG_TAG, "bitmapForURL() : " + filename + " does not exist");
                    return null;
                }

                FileInputStream fis = new FileInputStream(file);

                // read the metadata
                if (Integer.MAX_VALUE == rotation) {
                    rotation = ImageUtils.getRotationAngleForBitmap(context, Uri.fromFile(file));
                }

                if (null != fis) {
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inPreferredConfig = Bitmap.Config.ARGB_8888;

                    try {
                        bitmap = BitmapFactory.decodeStream(fis, null, options);
                    } catch (OutOfMemoryError error) {
                        System.gc();
                        Log.e(LOG_TAG, "bitmapForURL() : Out of memory 1 " + error);
                    }

                    //  try again
                    if (null == bitmap) {
                        try {
                            bitmap = BitmapFactory.decodeStream(fis, null, options);
                        } catch (OutOfMemoryError error) {
                            Log.e(LOG_TAG, "bitmapForURL() Out of memory 2" + error);
                        }
                    }

                    if (null != bitmap) {
                        synchronized (sMemoryCache) {
                            if (0 != rotation) {
                                try {
                                    android.graphics.Matrix bitmapMatrix = new android.graphics.Matrix();
                                    bitmapMatrix.postRotate(rotation);

                                    Bitmap transformedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                                            bitmap.getWidth(), bitmap.getHeight(), bitmapMatrix, false);
                                    bitmap.recycle();
                                    bitmap = transformedBitmap;
                                } catch (OutOfMemoryError ex) {
                                }
                            }

                            // cache only small images
                            // caching large images does not make sense
                            // it would replace small ones.
                            // let assume that the application must be faster when showing the chat history.
                            if ((bitmap.getWidth() < 1000) && (bitmap.getHeight() < 1000)) {
                                sMemoryCache.put(url, bitmap);
                            }
                        }
                    }

                    fis.close();
                }

            } catch (FileNotFoundException e) {
                Log.d(LOG_TAG, "bitmapForURL() : " + filename + " does not exist");
            } catch (Exception e) {
                Log.e(LOG_TAG, "bitmapForURL() " + e);

            }
        }
    }

    return bitmap;
}