Back to project page Resonos-Android-Framework.
The source code is released under:
Apache License
If you think the Android project Resonos-Android-Framework listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.
package com.resonos.apps.library.media; //from w ww . j a v a 2 s .c o m import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import android.graphics.Bitmap; import com.resonos.apps.library.util.M; /** * Class that implements an in memory cache of bitmaps. * From LazyList at https://github.com/thest1/LazyList/ */ public class BitmapMemoryCache { private static final String TAG = "MemoryCache"; private Map<String, Bitmap> cache = Collections // Last argument true for LRU ordering .synchronizedMap(new LinkedHashMap<String, Bitmap>(10, 1.5f, true)); private long size = 0;// current allocated size private long limit = 1000000;// max memory in bytes public BitmapMemoryCache() { // use 25% of available heap size setLimit(Runtime.getRuntime().maxMemory() / 4); } public void setLimit(long new_limit) { limit = new_limit; M.log(TAG, "MemoryCache will use up to " + limit / 1024. / 1024. + "MB"); } public Bitmap get(String id) { if (!cache.containsKey(id)) return null; return cache.get(id); } public void put(String id, Bitmap bitmap) { try { if (cache.containsKey(id)) size -= getSizeInBytes(cache.get(id)); cache.put(id, bitmap); size += getSizeInBytes(bitmap); checkSize(); } catch (Throwable th) { th.printStackTrace(); } } private void checkSize() { M.log(TAG, "cache size=" + size + " length=" + cache.size()); if (size > limit) { // least recently accessed item will be the first one iterated Iterator<Entry<String, Bitmap>> iter = cache.entrySet().iterator(); while (iter.hasNext()) { Entry<String, Bitmap> entry = iter.next(); size -= getSizeInBytes(entry.getValue()); iter.remove(); if (size <= limit) break; } M.log(TAG, "Clean cache. New size " + cache.size()); } } public void clear() { cache.clear(); } long getSizeInBytes(Bitmap bitmap) { if (bitmap == null) return 0; return bitmap.getRowBytes() * bitmap.getHeight(); } }