為什么要使用三級緩存
什么是三級緩存
三級緩存原理
具體實現(xiàn)及代碼
1. 自定義的圖片緩存工具類(MyBitmapUtils)
 /**  * 自定義的BitmapUtils,實現(xiàn)三級緩存  */ public class MyBitmapUtils {  private NetCacheUtils mNetCacheUtils;  private LocalCacheUtils mLocalCacheUtils;  private MemoryCacheUtils mMemoryCacheUtils;  public MyBitmapUtils(){   mMemoryCacheUtils=new MemoryCacheUtils();   mLocalCacheUtils=new LocalCacheUtils();   mNetCacheUtils=new NetCacheUtils(mLocalCacheUtils,mMemoryCacheUtils);  }  public void disPlay(ImageView ivPic, String url) {   ivPic.setImageResource(R.mipmap.pic_item_list_default);   Bitmap bitmap;   //內(nèi)存緩存   bitmap=mMemoryCacheUtils.getBitmapFromMemory(url);   if (bitmap!=null){    ivPic.setImageBitmap(bitmap);    System.out.println("從內(nèi)存獲取圖片啦.....");    return;   }   //本地緩存   bitmap = mLocalCacheUtils.getBitmapFromLocal(url);   if(bitmap !=null){    ivPic.setImageBitmap(bitmap);    System.out.println("從本地獲取圖片啦.....");    //從本地獲取圖片后,保存至內(nèi)存中    mMemoryCacheUtils.setBitmapToMemory(url,bitmap);    return;   }   //網(wǎng)絡(luò)緩存   mNetCacheUtils.getBitmapFromNet(ivPic,url);  } }2. 網(wǎng)絡(luò)緩存(NetCacheUtils)
 /**  * 三級緩存之網(wǎng)絡(luò)緩存  */ public class NetCacheUtils {  private LocalCacheUtils mLocalCacheUtils;  private MemoryCacheUtils mMemoryCacheUtils;  public NetCacheUtils(LocalCacheUtils localCacheUtils, MemoryCacheUtils memoryCacheUtils) {   mLocalCacheUtils = localCacheUtils;   mMemoryCacheUtils = memoryCacheUtils;  }  /**   * 從網(wǎng)絡(luò)下載圖片   * @param ivPic 顯示圖片的imageview   * @param url 下載圖片的網(wǎng)絡(luò)地址   */  public void getBitmapFromNet(ImageView ivPic, String url) {   new BitmapTask().execute(ivPic, url);//啟動AsyncTask  }  /**   * AsyncTask就是對handler和線程池的封裝   * 第一個泛型:參數(shù)類型   * 第二個泛型:更新進度的泛型   * 第三個泛型:onPostExecute的返回結(jié)果   */  class BitmapTask extends AsyncTask<Object, Void, Bitmap> {   private ImageView ivPic;   private String url;   /**    * 后臺耗時操作,存在于子線程中    * @param params    * @return    */   @Override   protected Bitmap doInBackground(Object[] params) {    ivPic = (ImageView) params[0];    url = (String) params[1];    return downLoadBitmap(url);   }   /**    * 更新進度,在主線程中    * @param values    */   @Override   protected void onProgressUpdate(Void[] values) {    super.onProgressUpdate(values);   }   /**    * 耗時方法結(jié)束后執(zhí)行該方法,主線程中    * @param result    */   @Override   protected void onPostExecute(Bitmap result) {    if (result != null) {     ivPic.setImageBitmap(result);     System.out.println("從網(wǎng)絡(luò)緩存圖片啦.....");     //從網(wǎng)絡(luò)獲取圖片后,保存至本地緩存     mLocalCacheUtils.setBitmapToLocal(url, result);     //保存至內(nèi)存中     mMemoryCacheUtils.setBitmapToMemory(url, result);    }   }  }  /**   * 網(wǎng)絡(luò)下載圖片   * @param url   * @return   */  private Bitmap downLoadBitmap(String url) {   HttpURLConnection conn = null;   try {    conn = (HttpURLConnection) new URL(url).openConnection();    conn.setConnectTimeout(5000);    conn.setReadTimeout(5000);    conn.setRequestMethod("GET");    int responseCode = conn.getResponseCode();    if (responseCode == 200) {     //圖片壓縮     BitmapFactory.Options options = new BitmapFactory.Options();     options.inSampleSize=2;//寬高壓縮為原來的1/2     options.inPreferredConfig=Bitmap.Config.ARGB_4444;     Bitmap bitmap = BitmapFactory.decodeStream(conn.getInputStream(),null,options);     return bitmap;    }   } catch (IOException e) {    e.printStackTrace();   } finally {    conn.disconnect();   }   return null;  } }3. 本地緩存(LocalCacheUtils)
 /**  * 三級緩存之本地緩存  */ public class LocalCacheUtils {  private static final String CACHE_PATH= Environment.getExternalStorageDirectory().getAbsolutePath()+"/WerbNews";  /**   * 從本地讀取圖片   * @param url   */  public Bitmap getBitmapFromLocal(String url){   String fileName = null;//把圖片的url當做文件名,并進行MD5加密   try {    fileName = MD5Encoder.encode(url);    File file=new File(CACHE_PATH,fileName);    Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(file));    return bitmap;   } catch (Exception e) {    e.printStackTrace();   }   return null;  }  /**   * 從網(wǎng)絡(luò)獲取圖片后,保存至本地緩存   * @param url   * @param bitmap   */  public void setBitmapToLocal(String url,Bitmap bitmap){   try {    String fileName = MD5Encoder.encode(url);//把圖片的url當做文件名,并進行MD5加密    File file=new File(CACHE_PATH,fileName);    //通過得到文件的父文件,判斷父文件是否存在    File parentFile = file.getParentFile();    if (!parentFile.exists()){     parentFile.mkdirs();    }    //把圖片保存至本地    bitmap.compress(Bitmap.CompressFormat.JPEG,100,new FileOutputStream(file));   } catch (Exception e) {    e.printStackTrace();   }  } }4. 內(nèi)存緩存(MemoryCacheUtils)
這是本文中最重要且需要重點介紹的部分
進行內(nèi)存緩存,就一定要注意一個問題,那就是內(nèi)存溢出(OutOfMemory)
為什么會造成內(nèi)存溢出?
實現(xiàn)方法:
會將內(nèi)存控制在一定的大小內(nèi), 超出最大值時會自動回收, 這個最大值開發(fā)者自己定
 /**  * 三級緩存之內(nèi)存緩存  */ public class MemoryCacheUtils {  // private HashMap<String,Bitmap> mMemoryCache=new HashMap<>();//1.因為強引用,容易造成內(nèi)存溢出,所以考慮使用下面弱引用的方法  // private HashMap<String, SoftReference<Bitmap>> mMemoryCache = new HashMap<>();//2.因為在Android2.3+后,系統(tǒng)會優(yōu)先考慮回收弱引用對象,官方提出使用LruCache  private LruCache<String,Bitmap> mMemoryCache;  public MemoryCacheUtils(){   long maxMemory = Runtime.getRuntime().maxMemory()/8;//得到手機最大允許內(nèi)存的1/8,即超過指定內(nèi)存,則開始回收   //需要傳入允許的內(nèi)存最大值,虛擬機默認內(nèi)存16M,真機不一定相同   mMemoryCache=new LruCache<String,Bitmap>((int) maxMemory){    //用于計算每個條目的大小    @Override    protected int sizeOf(String key, Bitmap value) {     int byteCount = value.getByteCount();     return byteCount;    }   };  }  /**   * 從內(nèi)存中讀圖片   * @param url   */  public Bitmap getBitmapFromMemory(String url) {   //Bitmap bitmap = mMemoryCache.get(url);//1.強引用方法   /*2.弱引用方法   SoftReference<Bitmap> bitmapSoftReference = mMemoryCache.get(url);   if (bitmapSoftReference != null) {    Bitmap bitmap = bitmapSoftReference.get();    return bitmap;   }   */   Bitmap bitmap = mMemoryCache.get(url);   return bitmap;  }  /**   * 往內(nèi)存中寫圖片   * @param url   * @param bitmap   */  public void setBitmapToMemory(String url, Bitmap bitmap) {   //mMemoryCache.put(url, bitmap);//1.強引用方法   /*2.弱引用方法   mMemoryCache.put(url, new SoftReference<>(bitmap));   */   mMemoryCache.put(url,bitmap);  } }以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持VEVB武林網(wǎng)。
新聞熱點
疑難解答
圖片精選