圖片三級緩存的流程


 圖片三級緩存的流程
三級緩存的內容:
    1. 從內存中獲取圖片,有,加載顯示
    2. 如果內存中沒有,從本地獲取圖片,有加載顯示,並且將圖片緩存到內存,為下一次顯示准備
    3. 如果本地也沒有,從網絡下載圖片,下載完成,顯示圖片,通過緩存到內存,保存到本地文件中,為下一次顯示准備
在內存中獲取圖片有兩種方式
    第一種:軟引用的方式(不太常用了)
        強引用: user = new UserInfo(), 不會輕易被系統回收
        軟引用: SoftReference<Bitmap>, 當內存不足的時候,系統會回收軟引用
        弱引用: WeakReference<Bitmap>, 當內存不足的時候,系統會回收弱引用,如果軟引用和弱引用同時存在,先回收弱引用
        虛引用: PhantomReference<Bitmap>, 當內存不足的時候,系統會回收弱引用,優先級低於弱引用
    第二種:LruCache方式
        判斷最新一段時間內的圖片引用的次數,判斷是否需要緩存,將使用頻率比較高的音樂緩存到內存中去
        1、創建LruCache對象
        public MyCacheBitmapUtils(){
            //map = new HashMap<String, SoftReference<Bitmap>>();
            //maxSize :  緩存空間大小,一般是總內存的 8 分之一
            int maxSize = (int) (Runtime.getRuntime().totalMemory()/8);
            lruCache = new LruCache<String, Bitmap>(maxSize){
                // 獲取緩存圖片的 大小
                @Override
                protected int sizeOf(String key, Bitmap value) {
                    //value.getRowBytes() :  獲取圖片一行占用的字節數
                    return value.getRowBytes() * value.getHeight();
                }
            };
        }
        2、緩存圖片
        public void saveBitmap(String url,Bitmap bitmap){
            //SoftReference<Bitmap> softReference = new SoftReference<Bitmap>(bitmap);// 使用軟引用修改 bitmap 引用
            //map.put(url, softReference);
            lruCache.put(url, bitmap);
        }
        3、獲取緩存圖片
        public Bitmap getBitmap(String url){
            /*SoftReference<Bitmap> softReference = map.get(url);
            // 確認軟引用沒有被回收
            if (softReference != null) {
            Bitmap bitmap = softReference.get();
                return bitmap;
            }*/
            Bitmap bitmap = lruCache.get(url);
            return bitmap;
        }
        4、將上面三步放到一個工具類中 通過工具類調用
本地緩存
    通過IO流操作 保存和讀取文件
    1、保存圖片
    File file = new File(dr, MD5Util.Md5(url).substring(0, 10));
    FileOutputStream stream = new FileOutputStream(file);
    // 設置圖片類型質量,將圖片保存本地文件中
    // 參數 1 :圖片格式
    // 參數 2 :圖片的質量
    // 參數 3 :寫入流
    bitmap.compress(CompressFormat.JPEG, 100, stream);
    2、獲取圖片
    File file = new File(PATH, MD5Util.Md5(url).substring(0, 10));
    Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
    return bitmap;
網絡獲取
    URL mUrl = new URL(url);
    HttpURLConnection con = (HttpURLConnection) mUrl.openConnection();
    con.setConnectTimeout(5000);// 設置鏈接超時時間
    con.setReadTimeout(5000);// 設置讀取超時時間
    con.connect();// 鏈接網絡操作
    int code = con.getResponseCode();// 獲取服務器響應碼
    if (code == 200) {
        // 獲取服務器數據,以流的形式返回
        InputStream stream = con.getInputStream();
        Bitmap bitmap = BitmapFactory.decodeStream(stream);
        return bitmap;
    }
    此處采用HttpURLConnection進行網絡操作


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM