利用LruCache實(shí)現(xiàn)雙緩存加載圖片

雙緩存實(shí)例

  • 下載DiskLruCache.java
    google認(rèn)證的第三方
    https://android.googlesource.com/platform/libcore/+/android-4.1.1_r1/luni/src/main/java/libcore/io/DiskLruCache.java

  • 新建LruCacheUtils進(jìn)行操作
    該類設(shè)計(jì)為單例模式。

      public class LruCacheUtils {
      private static LruCacheUtils lruCacheUtils;
    
      private DiskLruCache diskLruCache; //LRU磁盤緩存
      private LruCache<String, Bitmap> lruCache; //LRU內(nèi)存緩存
      private Context context;
    
      private LruCacheUtils() {
      }
    
      public static LruCacheUtils getInstance() {
          if (lruCacheUtils == null) {
              lruCacheUtils = new LruCacheUtils();
          }
          return lruCacheUtils;
      }
    }```
    
    
  • 首先需要獲得采樣比例

    //獲得采樣比例
     public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
         //獲取位圖的圓寬高
         int width = options.outWidth;
         int height = options.outHeight;
         System.out.println("outWidth=" + width + "outHeight" + height);
         int inSampleSize = 1;
         if (width > reqWidth || height > reqHeight) {
             //判斷原圖的寬高,再進(jìn)行匹配,按照小的來求采樣比例
             if (width > height) {
                 inSampleSize = Math.round((float) height / (float) reqHeight);
             } else {
                 inSampleSize = Math.round((float) width / (float) reqWidth);
             }
         }
         System.out.println("inSampleSize" + inSampleSize);
         return inSampleSize;
     }
    
  • 再實(shí)現(xiàn)一個(gè)方法,通過字節(jié)轉(zhuǎn)換成位圖

    public Bitmap decodeSampleBitmapFromStream(byte[] bytes, int reqWidth, int reqHeight) {
    
         BitmapFactory.Options options = new BitmapFactory.Options();
         options.inJustDecodeBounds = true;
         BitmapFactory.decodeByteArray(bytes,0,bytes.length,options);
         options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
         options.inJustDecodeBounds = false;
         return BitmapFactory.decodeByteArray(bytes,0,bytes.length,options);
     }
    
  • 還需要兩個(gè)方法,獲取AppVersion以及緩存目錄

    //在清單文件中定義的versionCode
      private int getAppVersion() {
    
          try {
              return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
          } catch (PackageManager.NameNotFoundException e) {
              e.printStackTrace();
          }
          return 1;
      }
      //獲取緩存目錄
      private File getCacheDir(String name) {
          //判斷是不是SD卡  或者外部存儲(chǔ)已經(jīng)被刪掉   前面一個(gè)是有SD卡(mnt/sdcard/Android/data/包名/cache)   后面一個(gè)沒有SD卡(緩存在私有目錄下data/data/包名/cache)
          String cachePath = Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED || !Environment.isExternalStorageRemovable()
                  ? context.getExternalCacheDir().getPath() : context.getCacheDir().getPath();
          return new File(cachePath + File.separator + name);
    
      }
    
  • 下面是兩個(gè)方法,計(jì)算MD5的字符串摘要

    //計(jì)算MD5的字符串摘要
    public String hashKeyForDisk(String key) {
      String cacheKey;
      try {
          final MessageDigest mDigest = MessageDigest.getInstance("MD5");
          mDigest.update(key.getBytes());
          cacheKey = bytesToHexString(mDigest.digest());
      } catch (NoSuchAlgorithmException e) {
          cacheKey = String.valueOf(key.hashCode());
      }
      return cacheKey;
    

}
public String bytesToHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(0xFF & bytes[i]);
if (hex.length() == 1) {
sb.append('0');

    }
    sb.append(hex);
}
return sb.toString();

}

* 然后是兩個(gè)添加和刪除內(nèi)存緩存的方法

//添加緩存
public void addBitmapToCache(String url, Bitmap bitmap) {
String key = hashKeyForDisk(url);
if (getBitmapFromCache(key) == null) {
System.out.println("key=====" + key);
System.out.println("bitmap====" + bitmap);
lruCache.put(key, bitmap);
}
}
//讀取緩存
public Bitmap getBitmapFromCache(String url) {
String key = hashKeyForDisk(url);
return lruCache.get(key);
}

* 還需要打開緩存的方法

public void open(Context context, String disk_cache_subdir, int disk_cache_size) {
this.context = context;
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
int memoryClass = am.getMemoryClass();
final int cacheSize = memoryClass / 8 * 1024 * 1024; //單位大小為字節(jié) 八分之一的內(nèi)存作為緩存大小
lruCache = new LruCache<>(cacheSize);
try {
diskLruCache = DiskLruCache.open(getCacheDir(disk_cache_subdir), getAppVersion(), 1, disk_cache_size);
} catch (IOException e) {
e.printStackTrace();
}
}


* 下面是最重要的部分,加入緩存,這里用到了AsyncTask,而且還需要定義一個(gè)回調(diào)接口來做出完成的響應(yīng)

public void putCache(final String url, final CallBack callBack) {
new AsyncTask<String, Void, Bitmap>() {
@Override
protected Bitmap doInBackground(String... params) {
String key = hashKeyForDisk(params[0]);
System.out.println("key=" + key);
DiskLruCache.Editor editor = null;
Bitmap bitmap = null;
try {
URL url = new URL(params[0]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(1000 * 30);
conn.setConnectTimeout(1000 * 30);
ByteArrayOutputStream baos = null;
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
baos = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int len = -1;
while ((len = bis.read(bytes)) != -1) {
baos.write(bytes, 0, len);
}
bis.close();
baos.close();
conn.disconnect();
}
if (baos != null) {
bitmap = decodeSampleBitmapFromStream(baos.toByteArray(), 100, 100);
//加入緩存
addBitmapToCache(params[0], bitmap);
//加入磁盤緩存
editor = diskLruCache.edit(key);
System.out.println(url.getFile());
//位圖壓縮后輸出(參數(shù):壓縮格式,質(zhì)量(100表示不壓縮,30表示壓縮70%),輸出流)
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, editor.newOutputStream(0));
editor.commit();
}

           } catch (IOException e) {
               try {
                   editor.abort();  //放棄寫入
               } catch (IOException e1) {
                   e1.printStackTrace();
               }
               e.printStackTrace();
           }
           return bitmap;
       }
       @Override
       protected void onPostExecute(Bitmap bitmap) {
           super.onPostExecute(bitmap);
           callBack.response(bitmap);
       }
   }.execute(url);

}
//回調(diào)接口
public interface CallBack<T> {
public void response(T entity);
}


* 最后還需要實(shí)現(xiàn)獲取磁盤緩存,關(guān)閉磁盤緩存以及刷新磁盤緩存三個(gè)方法

//獲取磁盤緩存
public InputStream getDiskCache(String url) {
String key = hashKeyForDisk(url);
System.out.println("getDiskCache=" + key);
try {
//快照
DiskLruCache.Snapshot snapshot = diskLruCache.get(key);
System.out.println(snapshot);
if (snapshot != null) {
return snapshot.getInputStream(0);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//關(guān)閉磁盤緩存
public void close() {
if (diskLruCache != null && !diskLruCache.isClosed()) {
try {
diskLruCache.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//刷新磁盤緩存
public void flush() {
if (diskLruCache != null) {
try {
diskLruCache.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}


* 上面都是我們?cè)贚ruCacheUtils.java的工具類中完成的方法,下面我們看看在MainActivity中的內(nèi)容

private DiskLruCacheUtils diskLruCacheUtils;
private static final String DISK_CACHE_SUBDIR = "temp";//目錄名
private static final int DISK_CACHE_SIZE = 1024 * 1024 * 10; //定義磁盤緩存大小,10MB

點(diǎn)擊按鈕時(shí)我們開始實(shí)現(xiàn)雙緩存加載圖片

public void show2Click(View view) {
String url = "http://p3.image.hiapk.com/uploads/allimg/141124/7730-141124100258.jpg";
loadBitmap(url, iv2);
}

* 我們需要在onResume方法中打開磁盤緩存,在onPause時(shí)刷新緩存,并在onStop時(shí)關(guān)閉緩存

@Override
protected void onResume() {
super.onResume();
lruCacheUtils = LruCacheUtils.getInstance();
lruCacheUtils.open(this, DISK_CACHE_SUBDIR, DISK_CACHE_SIZE);
}
//刷新把緩存寫好
@Override
protected void onPause() {
super.onPause();
lruCacheUtils.flush();
}
@Override
protected void onStop() {
super.onStop();
lruCacheUtils.close();
}


* 最后我們需要實(shí)現(xiàn)loadBitmap方法,加載圖片

public void loadBitmap(String url, final ImageView imageView) {
//從內(nèi)存緩存中取圖片
Bitmap bitmap = lruCacheUtils.getBitmapFromCache(url);
if (bitmap == null) {
//再?gòu)拇疟P緩存中取
InputStream in = lruCacheUtils.getDiskCache(url);
if (in == null) {
//去網(wǎng)上取
lruCacheUtils.putCache(url, new LruCacheUtils.CallBack<Bitmap>() {
@Override
public void response(Bitmap entity) {
System.out.println("http load");
imageView.setImageBitmap(entity);
}
});
} else {
System.out.println("disk cache");
bitmap = BitmapFactory.decodeStream(in);
//取完添加到內(nèi)存緩存中
lruCacheUtils.addBitmapToCache(url, bitmap);
imageView.setImageBitmap(bitmap);
}
} else {
System.out.println("memory cache");
imageView.setImageBitmap(bitmap);
}
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容