List of usage examples for android.support.v4.util LruCache LruCache
public LruCache(int maxSize)
From source file:com.wewe.android.util.video.ImageCache.java
/** * Initialize the cache, providing all parameters. * /*w ww . ja v a 2s . c o m*/ * @param cacheParams * The cache parameters to initialize the cache */ private void init(ImageCacheParams cacheParams) { mCacheParams = cacheParams; // BEGIN_INCLUDE(init_memory_cache) // 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). if (VersionUtil.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 (VersionUtil.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())); } } } /** * 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:org.onebusaway.android.map.googlemapsv2.VehicleOverlay.java
/** * Cache the core black template Bitmaps used for vehicle icons *//* w w w . j av a2 s .c o m*/ private static final void loadIcons() { // Initialize variables used for all marker icons Resources r = Application.get().getResources(); // Black vehicle icons if (vehicle_icons[0] == null) { vehicle_icons[0] = createVehicleIcon(NORTH); vehicle_icons[1] = createVehicleIcon(NORTH_EAST); vehicle_icons[2] = createVehicleIcon(EAST); vehicle_icons[3] = createVehicleIcon(SOUTH_EAST); vehicle_icons[4] = createVehicleIcon(SOUTH); vehicle_icons[5] = createVehicleIcon(SOUTH_WEST); vehicle_icons[6] = createVehicleIcon(WEST); vehicle_icons[7] = createVehicleIcon(NORTH_WEST); vehicle_icons[8] = createVehicleIcon(NO_DIRECTION); } /** * Cache for colored versions of the vehicle icons. Total possible number of entries is * 9 directions * 4 color types (early, ontime, delayed, scheduled) = 36. In a test, * the RouteMapController used around 15 bitmaps over a 30 min period for 4 vehicles on the * map at 10 sec refresh rate. This can be more depending on the route configuration (if * the route has lots of curves) and number of vehicles. To conserve memory, we'll set the * max cache size at 15. */ final int MAX_CACHE_SIZE = 15; if (mVehicleColoredIconCache == null) { mVehicleColoredIconCache = new LruCache<>(MAX_CACHE_SIZE); } }
From source file:so.contacts.hub.basefunction.imageloader.DataCache.java
/** * Initialize the cache, providing all parameters. ???? * /*from w w w. j av a 2 s. co m*/ * @param cacheParams The cache parameters to initialize the cache */ private void init(DataCacheParams cacheParams) { mCacheParams = cacheParams; // Set up memory cache // if (mCacheParams.memoryCacheEnabled) { mMemCache = new LruCache<String, Object>(mCacheParams.memCacheSize) { /** * Measure item size in bytes rather than units which is more * practical for a bitmap cache ??LruCache */ @Override protected int sizeOf(String key, Object obj) { if (obj instanceof Bitmap) { return getBitmapSize((Bitmap) obj); } return 0; } }; if (mCacheParams.diskCacheDir != null) { mDiskLruCache = DiskLruCache.openCache(mCacheParams.diskCacheDir, mCacheParams.diskCacheSize); } else { // ? mCacheParams.diskCacheDir = DiskLruCache.getDiskCacheDir(ContactsApp.getInstance(), HTTP_CACHE_DIR + mCacheParams.uniqueName); // ? mCacheParams.diskCacheSize = DEFAULT_DISK_CACHE_SIZE; mDiskLruCache = DiskLruCache.openCache(mCacheParams.diskCacheDir, mCacheParams.diskCacheSize); } } }
From source file:com.miaotu.imutil.video.ImageCache.java
/** * Initialize the cache, providing all parameters. * // ww w . ja v a2s. c om * @param cacheParams * The cache parameters to initialize the cache */ private void init(ImageCacheParams cacheParams) { mCacheParams = cacheParams; // BEGIN_INCLUDE(init_memory_cache) // 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). if (Util.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 (Util.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())); } } } /** * 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:it.gmariotti.cardslib.library.view.component.CardThumbnailView.java
/** * Init view//from w ww.j a va 2 s . co m */ protected void initView() { LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); mInternalOuterView = inflater.inflate(card_thumbnail_layout_resourceID, this, true); //Get ImageVIew mImageView = (ImageView) findViewById(R.id.card_thumbnail_image); // 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 = CacheUtil.getMemoryCache(); if (mMemoryCache == null) { mMemoryCache = new LruCache<String, Bitmap>(cacheSize) { @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; } } }; CacheUtil.putMemoryCache(mMemoryCache); } }
From source file:com.example.android.threadsample.PhotoManager.java
/** * Constructs the work queues and thread pools used to download and decode images. *///from w w w. j av a 2 s . co m private PhotoManager() { /* * Creates a work queue for the pool of Thread objects used for downloading, using a linked * list queue that blocks when the queue is empty. */ mDownloadWorkQueue = new LinkedBlockingQueue<Runnable>(); /* * Creates a work queue for the pool of Thread objects used for decoding, using a linked * list queue that blocks when the queue is empty. */ mDecodeWorkQueue = new LinkedBlockingQueue<Runnable>(); /* * Creates a work queue for the set of of task objects that control downloading and * decoding, using a linked list queue that blocks when the queue is empty. */ mPhotoTaskWorkQueue = new LinkedBlockingQueue<PhotoTask>(); /* * Creates a new pool of Thread objects for the download work queue */ mDownloadThreadPool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, mDownloadWorkQueue); /* * Creates a new pool of Thread objects for the decoding work queue */ mDecodeThreadPool = new ThreadPoolExecutor(NUMBER_OF_CORES, NUMBER_OF_CORES, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, mDecodeWorkQueue); // Instantiates a new cache based on the cache size estimate mPhotoCache = new LruCache<URL, byte[]>(IMAGE_CACHE_SIZE) { /* * This overrides the default sizeOf() implementation to return the * correct size of each cache entry. */ @Override protected int sizeOf(URL paramURL, byte[] paramArrayOfByte) { return paramArrayOfByte.length; } }; /* * Instantiates a new anonymous Handler object and defines its * handleMessage() method. The Handler *must* run on the UI thread, because it moves photo * Bitmaps from the PhotoTask object to the View object. * To force the Handler to run on the UI thread, it's defined as part of the PhotoManager * constructor. The constructor is invoked when the class is first referenced, and that * happens when the View invokes startDownload. Since the View runs on the UI Thread, so * does the constructor and the Handler. */ mHandler = new Handler(Looper.getMainLooper()) { /* * handleMessage() defines the operations to perform when the * Handler receives a new Message to process. */ @Override public void handleMessage(Message inputMessage) { // Gets the image task from the incoming Message object. PhotoTask photoTask = (PhotoTask) inputMessage.obj; // Sets an PhotoView that's a weak reference to the // input ImageView PhotoView localView = photoTask.getPhotoView(); // If this input view isn't null if (localView != null) { /* * Gets the URL of the *weak reference* to the input * ImageView. The weak reference won't have changed, even if * the input ImageView has. */ URL localURL = localView.getLocation(); /* * Compares the URL of the input ImageView to the URL of the * weak reference. Only updates the bitmap in the ImageView * if this particular Thread is supposed to be serving the * ImageView. */ if (photoTask.getImageURL() == localURL) /* * Chooses the action to take, based on the incoming message */ switch (inputMessage.what) { // If the download has started, sets background color to dark green case DOWNLOAD_STARTED: localView.setStatusResource(R.drawable.imagedownloading); break; /* * If the download is complete, but the decode is waiting, sets the * background color to golden yellow */ case DOWNLOAD_COMPLETE: // Sets background color to golden yellow localView.setStatusResource(R.drawable.decodequeued); break; // If the decode has started, sets background color to orange case DECODE_STARTED: localView.setStatusResource(R.drawable.decodedecoding); break; /* * The decoding is done, so this sets the * ImageView's bitmap to the bitmap in the * incoming message */ case TASK_COMPLETE: localView.setImageBitmap(photoTask.getImage()); recycleTask(photoTask); break; // The download failed, sets the background color to dark red case DOWNLOAD_FAILED: localView.setStatusResource(R.drawable.imagedownloadfailed); // Attempts to re-use the Task object recycleTask(photoTask); break; default: // Otherwise, calls the super method super.handleMessage(inputMessage); } } } }; }
From source file:com.intelerad.android.portal.ImageCache.java
/** * Initialize the cache, providing all parameters. * //from ww w . ja v a 2s .co m * @param context The context to use * @param cacheParams The cache parameters to initialize the cache */ private void init(Context context, ImageCacheParams cacheParams) { mCacheParams = cacheParams; final File diskCacheDir = getDiskCacheDir(context, cacheParams.uniqueName); if (cacheParams.diskCacheEnabled) { if (!diskCacheDir.exists()) { diskCacheDir.mkdir(); } if (getUsableSpace(diskCacheDir) > cacheParams.diskCacheSize) { try { mICSDiskCache = ICSDiskLruCache.open(diskCacheDir, 1, 1, cacheParams.diskCacheSize); } catch (final IOException e) { LOGE(TAG, "init - " + e); } } } // 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 getBitmapSize(bitmap); } }; } }
From source file:com.corebase.android.bitmap.util.ImageCache.java
/** * Initialize the cache, providing all parameters. * /*from w w w . j av a 2 s . c o m*/ * @param cacheParams * The cache parameters to initialize the cache */ private void init(ImageCacheParams cacheParams) { mCacheParams = cacheParams; // Set up memory cache if (mCacheParams.memoryCacheEnabled) { // If we're running on Honeycomb or newer, then if (Utils.hasHoneycomb()) { // mReusableBitmaps = new HashSet<SoftReference<Bitmap>>(); // mReusableBitmaps = Collections.synchronizedSet(new // HashSet<SoftReference<Bitmap>>()); mReusableBitmaps = new ConcurrentHashMap<String, 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())); mReusableBitmaps.put(key, 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 Logs.v(TAG, "init disk cache ..."); initDiskCache(); } }
From source file:com.example.hotnewsapp.imageutil.PhotoManager.java
/** * Constructs the work queues and thread pools used to download and decode * images.//from w w w.j ava 2 s.c om */ private PhotoManager() { /* * Creates a work queue for the pool of Thread objects used for * downloading, using a linked list queue that blocks when the queue is * empty. */ mDownloadWorkQueue = new LinkedBlockingQueue<Runnable>(); /* * Creates a work queue for the pool of Thread objects used for * decoding, using a linked list queue that blocks when the queue is * empty. */ mDecodeWorkQueue = new LinkedBlockingQueue<Runnable>(); /* * Creates a work queue for the set of of task objects that control * downloading and decoding, using a linked list queue that blocks when * the queue is empty. */ mPhotoTaskWorkQueue = new LinkedBlockingQueue<PhotoTask>(); /* * Creates a new pool of Thread objects for the download work queue */ mDownloadThreadPool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, mDownloadWorkQueue); /* * Creates a new pool of Thread objects for the decoding work queue */ mDecodeThreadPool = new ThreadPoolExecutor(NUMBER_OF_CORES, NUMBER_OF_CORES, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, mDecodeWorkQueue); // Instantiates a new cache based on the cache size estimate mPhotoCache = new LruCache<URL, byte[]>(IMAGE_CACHE_SIZE) { /* * This overrides the default sizeOf() implementation to return the * correct size of each cache entry. */ @Override protected int sizeOf(URL paramURL, byte[] paramArrayOfByte) { return paramArrayOfByte.length; } }; /* * Instantiates a new anonymous Handler object and defines its * handleMessage() method. The Handler *must* run on the UI thread, * because it moves photo Bitmaps from the PhotoTask object to the View * object. To force the Handler to run on the UI thread, it's defined as * part of the PhotoManager constructor. The constructor is invoked when * the class is first referenced, and that happens when the View invokes * startDownload. Since the View runs on the UI Thread, so does the * constructor and the Handler. */ mHandler = new Handler(Looper.getMainLooper()) { /* * handleMessage() defines the operations to perform when the * Handler receives a new Message to process. */ @Override public void handleMessage(Message inputMessage) { // Gets the image task from the incoming Message object. PhotoTask photoTask = (PhotoTask) inputMessage.obj; // Sets an PhotoView that's a weak reference to the // input ImageView PhotoView localView = photoTask.getPhotoView(); // If this input view isn't null if (localView != null) { /* * Gets the URL of the *weak reference* to the input * ImageView. The weak reference won't have changed, even if * the input ImageView has. */ URL localURL = localView.getLocation(); /* * Compares the URL of the input ImageView to the URL of the * weak reference. Only updates the bitmap in the ImageView * if this particular Thread is supposed to be serving the * ImageView. */ if (photoTask.getImageURL() == localURL) { /* * Chooses the action to take, based on the incoming * message */ switch (inputMessage.what) { // If the download has started, sets background color to // dark green case DOWNLOAD_STARTED: localView.setStatusResource(R.drawable.imagedownloading); break; /* * If the download is complete, but the decode is * waiting, sets the background color to golden yellow */ case DOWNLOAD_COMPLETE: // Sets background color to golden yellow localView.setStatusResource(R.drawable.decodequeued); break; // If the decode has started, sets background color to // orange case DECODE_STARTED: localView.setStatusResource(R.drawable.decodedecoding); break; /* * The decoding is done, so this sets the ImageView's * bitmap to the bitmap in the incoming message */ case TASK_COMPLETE: localView.setImageBitmap(photoTask.getImage()); recycleTask(photoTask); break; // The download failed, sets the background color to // dark red case DOWNLOAD_FAILED: localView.setStatusResource(R.drawable.imagedownloadfailed); // Attempts to re-use the Task object recycleTask(photoTask); break; default: // Otherwise, calls the super method super.handleMessage(inputMessage); } } } } }; }
From source file:tw.waterdrop.waterdrop.util.ImageCache.java
/** * Initialize the cache, providing all parameters. * * @param cacheParams The cache parameters to initialize the cache */// w ww . j a v a 2 s . c o m private void init(ImageCacheParams cacheParams) { mCacheParams = cacheParams; //BEGIN_INCLUDE(init_memory_cache) // Set up memory cache if (mCacheParams.memoryCacheEnabled) { // 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) { // 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())); } } /** * 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; } }; } //END_INCLUDE(init_memory_cache) // 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(); } }