硬碟快取技術(DiskLruCache)
阿新 • • 發佈:2019-01-30
Glide新增依賴包那句程式碼裡面封裝有了DiskLruCache這個類,所以Android Studio的使用者不用刻意去下載DiskLruCache類,而是直接新增Glide依賴包即可用DiskLruCache了。
compile 'com.github.bumptech.glide:glide:3.7.0'
注意:
(1)在推薦文章寫入操作程式碼中
new Thread(new Runnable() {
@Override
public void run() {
try {
String imageUrl = "http://img.my.csdn.net/uploads/201309/01/1378037235_7476.jpg" ;
String key = hashKeyForDisk(imageUrl);
DiskLruCache.Editor editor = mDiskLruCache.edit(key);
if (editor != null) {
OutputStream outputStream = editor.newOutputStream(0);
if (downloadUrlToStream(imageUrl, outputStream)) {
editor.commit();
} else {
editor.abort();
}
}
mDiskLruCache.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
其中,
OutputStream outputStream = editor.newOutputStream(0)
要修改為
OutputStream outputStream = new FileOutputStream(editor.getFile(0))
因為Glide依賴庫中的DiskLruCache類中的Editor內部類裡沒有newOutputStream(int index)方法,只有getFile(int index)方法,具體可以去原始碼中檢視。
(2)讀取快取,並將圖片載入到介面上的程式碼中
try {
String imageUrl = "http://img.my.csdn.net/uploads/201309/01/1378037235_7476.jpg";
String key = hashKeyForDisk(imageUrl);
DiskLruCache.Snapshot snapShot = mDiskLruCache.get(key);
if (snapShot != null) {
InputStream is = snapShot.getInputStream(0);
Bitmap bitmap = BitmapFactory.decodeStream(is);
mImage.setImageBitmap(bitmap);
}
} catch (IOException e) {
e.printStackTrace();
}
其中,
DiskLruCache.Snapshot snapShot = mDiskLruCache.get(key);
InputStream is = snapShot.getInputStream(0);
要修改為
DiskLruCache.Value snapShot = mDiskLruCache.get(key);
InputStream is = new FileInputStream(snapShot.getFile(0));
原因同(1)相似,感興趣可以去原始碼檢視。