Complete cases of using L2 cache, asynchronous loading and batch loading of pictures in Android

1、 Problem description

Android applications often involve loading a large number of pictures from the network. In order to improve loading speed and efficiency and reduce network traffic, secondary cache and asynchronous loading mechanism will be adopted. The so-called secondary cache is obtained from memory, then from files, and finally access the network. Memory cache (Level 1) is essentially a map set that stores the URL and bitmap information of pictures in the form of key value pairs. Because memory cache will cause heap memory leakage and the management is relatively complex, third-party components can be used. For experienced components, they can write their own components, while file cache is relatively simple, and they can usually be encapsulated by themselves. Here is a case to see how to optimize network image loading.

2、 Case introduction

List pictures of case news

3、 Main core components

Let's take a look at the components written to implement L1 cache (memory) and L2 cache (disk file)

1、MemoryCache

Store pictures in memory (first level cache). A map is used to cache pictures. The code is as follows:

public class MemoryCache {
  // 最大的缓存数 
  private static final int MAX_CACHE_CAPACITY = 30;
  //用Map软引用的Bitmap对象,保证内存空间足够情况下不会被垃圾回收
    private HashMap<String,SoftReference<Bitmap>> mCacheMap = 
      new LinkedHashMap<String,SoftReference<Bitmap>>() {
      private static final long serialVersionUID = 1L;
//当缓存数量超过规定大小(返回true)会清除最早放入缓存的  
      protected boolean removeEldestEntry(
Map.Entry<String,SoftReference<Bitmap>> eldest){
        return size() > MAX_CACHE_CAPACITY;};
  };
  /**
   * 从缓存里取出图片
   * @param id
   * @return 如果缓存有,并且该图片没被释放,则返回该图片,否则返回null
   */
  public Bitmap get(String id){
    if(!mCacheMap.containsKey(id)) return null;
    SoftReference<Bitmap> ref = mCacheMap.get(id);
    return ref.get();
  }
  /**
   * 将图片加入缓存
   * @param id
   * @param bitmap
   */
  public void put(String id,Bitmap bitmap){
    mCacheMap.put(id,new SoftReference<Bitmap>(bitmap));
  }
  /**
   * 清除所有缓存
   */
  public void clear() {
  try {
      for(Map.Entry<String,SoftReference<Bitmap>>entry :mCacheMap.entrySet()) 
{  SoftReference<Bitmap> sr = entry.getValue();
      if(null != sr) {
        Bitmap bmp = sr.get();
        if(null != bmp) bmp.recycle();
      }
    }
    mCacheMap.clear();
  } catch (Exception e) {
      e.printStackTrace();}
  }
}

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>