本文為單張圖片做二級(jí)緩存的實(shí)例
1坯约、LruCache工具類
/**
* 圖片的內(nèi)存緩存工具類
*/
class CacheUtils {
companion object{
lateinit var mMemoryCache : LruCache<String, Bitmap>
private var maxMemory by Delegates.notNull<Int>()
private var cacheSize by Delegates.notNull<Int>()
fun initCacheAbout(){
// 獲得虛擬機(jī)能提供的最大內(nèi)存熊咽,超過(guò)這個(gè)大小會(huì)拋出OutOfMemory的異常
maxMemory = (Runtime.getRuntime().maxMemory() / 1024).toInt()
cacheSize = maxMemory / 8
mMemoryCache = ImageCache(cacheSize)
}
fun addBitmapToMemoryCache(key: String?, bitmap: Bitmap?) {
if (getBitmapFromMemCache(key) == null) {
Log.d("Neo","addBitmapToMemoryCache(存之前),長(zhǎng)度="+mMemoryCache.size())
mMemoryCache.put(key, bitmap)
Log.d("Neo","addBitmapToMemoryCache(存完之后)闹丐,長(zhǎng)度="+mMemoryCache.size())
}
}
fun getBitmapFromMemCache(key: String?): Bitmap? {
Log.d("Neo","getBitmapFromMemCache() temp=$mMemoryCache")
Log.d("Neo","getBitmapFromMemCache() 長(zhǎng)度="+mMemoryCache.size())
Log.d("Neo","getBitmapFromMemCache() temp[key]="+mMemoryCache[key])
return mMemoryCache[key]
}
class ImageCache(cacheSize: Int) : LruCache<String, Bitmap>(cacheSize) {
override fun sizeOf(key: String?, value: Bitmap?): Int {
return value!!.byteCount / 1024
}
}
}
}
2横殴、DiskLruCache工具類
/**
* 圖片的磁盤緩存工具類
*/
class DiskLruCacheUtils {
companion object{
lateinit var mDiskLruCache: DiskLruCache
/**
* 初始化磁盤緩存
*/
fun initDisk(context : Context){
try {
val cacheDir = getDiskCacheDir(context, "bitmap")
if (!cacheDir.exists()) {
cacheDir.mkdirs()
}
mDiskLruCache = DiskLruCache.open(cacheDir, getAppVersion(context), 1, 10 * 1024 * 1024)
} catch (e: IOException) {
e.printStackTrace()
}
}
/**
* 獲取磁盤緩存路徑地址
*/
fun getDiskCacheDir(context: Context, uniqueName: String): File {
val cachePath: String = if (Environment.MEDIA_MOUNTED == Environment.getExternalStorageState()
|| !Environment.isExternalStorageRemovable()
) {
context.externalCacheDir!!.path
} else {
context.cacheDir.path
}
return File(cachePath + File.separator + uniqueName)
}
/**
* 獲取系統(tǒng)版本號(hào)
*/
private fun getAppVersion(context: Context): Int {
try {
val info = context.packageManager.getPackageInfo(context.packageName, 0)
return info.versionCode
} catch (e: PackageManager.NameNotFoundException) {
e.printStackTrace()
}
return 1
}
/**
* 將圖片地址進(jìn)行MD5編碼
*/
fun hashKeyForDisk(key: String): String? {
return try {
val mDigest: MessageDigest = MessageDigest.getInstance("MD5")
mDigest.update(key.toByteArray())
bytesToHexString(mDigest.digest())
} catch (e: NoSuchAlgorithmException) {
key.hashCode().toString()
}
}
private fun bytesToHexString(bytes: ByteArray): String? {
val sb = StringBuilder()
for (i in bytes.indices) {
val hex = Integer.toHexString(0xFF and bytes[i].toInt())
if (hex.length == 1) {
sb.append('0')
}
sb.append(hex)
}
return sb.toString()
}
/**
* 下載圖片并寫入磁盤緩存
*/
fun downloadUrlToStream(urlString: String, outputStream: OutputStream): Boolean {
var urlConnection: HttpURLConnection? = null
var out: BufferedOutputStream? = null
var `in`: BufferedInputStream? = null
try {
val url = URL(urlString)
urlConnection = url.openConnection() as HttpURLConnection
`in` = BufferedInputStream(urlConnection.inputStream, 8 * 1024)
out = BufferedOutputStream(outputStream, 8 * 1024)
var b: Int
while (`in`.read().also { b = it } != -1) {
out.write(b)
}
return true
} catch (e: IOException) {
e.printStackTrace()
} finally {
urlConnection?.disconnect()
try {
out?.close()
`in`?.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
return false
}
/**
* 把byte字節(jié)寫入緩存DiskLruCache
*/
@Throws(java.lang.Exception::class)
fun writeToDiskLruCache(url: String, buf: ByteArray) {
Log.d("TAG", "$url : 開(kāi)始寫入緩存...")
//DiskLruCache緩存需要一個(gè)key,我先把url轉(zhuǎn)換成md5字符串卿拴,
//然后以md5字符串作為key鍵
val key: String? = hashKeyForDisk(url)
val editor: DiskLruCache.Editor = mDiskLruCache.edit(key)
val os: OutputStream = editor.newOutputStream(0)
os.write(buf)
os.flush()
editor.commit()
mDiskLruCache.flush()
Log.d("TAG", "$url : 寫入緩存完成.")
}
}
}
3衫仑、單張圖片二級(jí)緩存的使用
- 首先查看內(nèi)存緩存中是否有此圖片,如果有直接顯示堕花;
- 如果內(nèi)存中沒(méi)有此圖文狱,則查看磁盤中是否有緩存,如果有則直接顯示缘挽,同時(shí)瞄崇,將內(nèi)存緩存的數(shù)據(jù)覆蓋;
- 如果磁盤緩存也沒(méi)有數(shù)據(jù)壕曼,則需要請(qǐng)求網(wǎng)絡(luò)苏研,下載成功后,調(diào)用第一步的方法腮郊,重新將圖片寫入二級(jí)緩存摹蘑,然后顯示出來(lái);
/**
* 單張圖片的 內(nèi)存緩存 + 磁盤緩存
*/
class SingleImageMemoryAndDiskCacheActivity : AppCompatActivity() {
lateinit var imageView : ImageView
private val oriUrl : String = "https://t7.baidu.com/it/u=2168645659,3174029352&fm=193&f=GIF"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_single_image_memory_and_disk_cache)
imageView = findViewById(R.id.image_id)
loadImage()
}
private fun loadImage(){
try {
//根據(jù)圖片地址拿到MD5之后的字符串
val key = DiskLruCacheUtils.hashKeyForDisk(oriUrl)
//先查看內(nèi)存緩存
val bitmap = CacheUtils.getBitmapFromMemCache(key)
//內(nèi)存緩存有數(shù)據(jù)轧飞,直接讀取并加載
if (bitmap != null) {
imageView.setImageBitmap(bitmap)
}
else { //內(nèi)存緩存無(wú)數(shù)據(jù)衅鹿,則查看磁盤緩存
val snapShot = DiskLruCacheUtils.mDiskLruCache[key]
//磁盤緩存有數(shù)據(jù),直接讀取并加載
if (snapShot != null) {
val `is` = snapShot.getInputStream(0)
val bitmapFromDiskCache = BitmapFactory.decodeStream(`is`)
//如果磁盤有數(shù)據(jù)踪少,則將內(nèi)存緩存的數(shù)據(jù)覆蓋
CacheUtils.addBitmapToMemoryCache(key, bitmapFromDiskCache)
imageView.setImageBitmap(bitmapFromDiskCache)
}
//磁盤緩存也沒(méi)有數(shù)據(jù)塘安,則需要請(qǐng)求網(wǎng)絡(luò)
else{
startDownload()
}
}
} catch (e: IOException) {
e.printStackTrace()
}
}
/**
* 下載網(wǎng)絡(luò)圖片并緩存到磁盤,完成后讀緩存
*/
private fun startDownload(){
Thread {
try {
val key = DiskLruCacheUtils.hashKeyForDisk(oriUrl)
val editor = DiskLruCacheUtils.mDiskLruCache.edit(key)
if (editor != null) {
val outputStream: OutputStream = editor.newOutputStream(0)
if (DiskLruCacheUtils.downloadUrlToStream(oriUrl, outputStream)) {
runOnUiThread {
loadImage()
}
editor.commit()
} else {
editor.abort()
}
}
DiskLruCacheUtils.mDiskLruCache.flush()
} catch (e: IOException) {
e.printStackTrace()
}
}.start()
}
}