一:用MemoryCache
在占用宝贵的应用程序内存的成本前提下,Memory cache 提供快速访问的位图。LruCache类特别适合于高速缓存位图的任务,能够保持最近引用的对象一个强有力的引用LinkedHashMap的和逐出最近最少使用的构件缓存超过其指定大小之前。
LruCache用法:
首先要为LruCache分配内存 分配内存要考虑的因素有:
①:你的Activity和/或application的其他部分如何内存密集型的?
②:一次加载位图的数量,接下来要加载位图的数量
③:该手机的屏幕大小和屏幕密度
④:位图的尺寸和配置,每一个位图所占用的内存
⑤:位图被访问的频率,
⑥:权衡数量与质量之间的平衡。有时也可以是更加有用以存储低质量位图较大数量,潜在地装入更高质量版本在另一个后台任务。
LruCache运用的例子
private LruCache<String, Bitmap> mMemoryCache; @Override protected void onCreate(Bundle 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) { @Override protected int sizeOf(String key, Bitmap bitmap) { // The cache size will be measured in kilobytes rather than // number of items. return bitmap.getByteCount() / 1024; } }; ... } public void addBitmapToMemoryCache(String key, Bitmap bitmap) { if (getBitmapFromMemCache(key) == null) { mMemoryCache.put(key, bitmap); } } public Bitmap getBitmapFromMemCache(String key) { return mMemoryCache.get(key); }加载图片时的代码:
public void loadBitmap(int resId, ImageView imageView) { final String imageKey = String.valueOf(resId); final Bitmap bitmap = getBitmapFromMemCache(imageKey); if (bitmap != null) { mImageView.setImageBitmap(bitmap); } else { mImageView.setImageResource(R.drawable.image_placeholder); BitmapWorkerTask task = new BitmapWorkerTask(mImageView); task.execute(resId); } }BitmapWorkTask类
class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> { ... // Decode image in background. @Override protected Bitmap doInBackground(Integer... params) { final Bitmap bitmap = decodeBitmap();//该方法用来加载图片的具体方法,要看你加载图片资源的来源 addBitmapToMemoryCache(String.valueOf(params[0]), bitmap); return bitmap; } }