本文以单张图片为素材,实现OkHttp + DiskLruCache的使用
1、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)
}
/**
* 获取系统版本号
*/
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
}
/**
* 将图片地址进行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字节写入缓存DiskLruCache
*/
@Throws(java.lang.Exception::class)
fun writeToDiskLruCache(url: String, buf: ByteArray) {
Log.d("TAG", "$url : 开始写入缓存...")
//DiskLruCache缓存需要一个key,我先把url转换成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 : 写入缓存完成.")
}
}
}
2、OkHttp + DiskLruCache的使用
- 首先读磁盘,如果有缓存则直接显示;
- 如果磁盘中没有缓存,则需要通过OkHttp 下载图片,下载成功后将图片缓存进磁盘,同时完成图片的显示;
/**
* OkHttp + DiskLruCache
*/
class OkhttpDiskLruCacheActivity : 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_okhttp_disk_lru_cache)
imageView = findViewById(R.id.image_id)
loadImage()
}
private fun loadImage(){
//先读取磁盘缓存
try {
val key = DiskLruCacheUtils.hashKeyForDisk(oriUrl)
val snapShot = mDiskLruCache[key]
if (snapShot != null) {
val `is` = snapShot.getInputStream(0)
val bitmap = BitmapFactory.decodeStream(`is`)
imageView.setImageBitmap(bitmap)
}
else{
downloadBitmapFromNetwork(imageView,oriUrl)
}
} catch (e: IOException) {
e.printStackTrace()
}
}
private fun downloadBitmapFromNetwork(image: ImageView, image_url: String) {
Log.d("TAG", "从网络中加载图片资源 ... @ $image_url")
//初始化OkHttpClient
val client = OkHttpClient()
//创建OkHttpClient针对某个url的数据请求
val request: Request = Request.Builder().url(image_url).build()
val call: Call = client.newCall(request)
//请求加入队列
call.enqueue(object : Callback {
override fun onFailure(call: Call?, e: IOException?) {
//此处处理请求失败的业务逻辑
}
@Throws(IOException::class)
override fun onResponse(call: Call?, response: Response) {
//如果response响应成功则继续,否则返回
if (!response.isSuccessful()) return
//我写的这个例子是请求一个图片
//response的body是图片的byte字节
val bytes: ByteArray = response.body()!!.bytes()
//已经获得图片数据,记到要写入硬盘缓存
//出于性能考虑,此处可以放到后台或者放到一个线程里面处理
//简单期间,我就在这儿直接写缓存了。
try {
DiskLruCacheUtils.writeToDiskLruCache(image_url, bytes)
} catch (e: Exception) {
e.printStackTrace()
}
//把byte字节组装成图片
val bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
//回调是运行在非ui主线程,
//数据请求成功后,在主线程中更新
runOnUiThread { //网络图片请求成功,更新到主线程的ImageView
image.setImageBitmap(bmp)
}
}
})
}
}
3、第2步可以改为以下方式
/**
* OkHttp + DiskLruCache
*/
class OkhttpCacheActivity : AppCompatActivity() {
lateinit var mOkHttpClient : OkHttpClient
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_okhttp_cache)
val image: ImageView = findViewById(R.id.image_id)
val mCache = Cache(DiskLruCacheUtils.getDiskCacheDir(this,"Neo"), 8 * 1024 * 1024)
val mBuilder = OkHttpClient.Builder()
mOkHttpClient = mBuilder
.connectTimeout(10, TimeUnit.SECONDS) //连接超时阈值
.writeTimeout(10, TimeUnit.SECONDS) //写超时阈值
.readTimeout(10, TimeUnit.SECONDS) //读超时阈值
.retryOnConnectionFailure(true) //当失败后重试
.cache(mCache)
.build()
val mRequest: Request = Request.Builder().url(oriUrl).build()
mOkHttpClient.newCall(mRequest).enqueue(object : Callback {
override fun onFailure(call: Call?, e: IOException?) {}
@Throws(IOException::class)
override fun onResponse(call: Call?, response: Response) {
if (response.isSuccessful) {
val bytes: ByteArray? = response.body()?.bytes()
val bmp = bytes?.let { BitmapFactory.decodeByteArray(bytes, 0, it.size) }
runOnUiThread { image.setImageBitmap(bmp) }
}
}
})
}
override fun onDestroy() {
super.onDestroy()
//取消所有Okhttp的网络请求
mOkHttpClient.dispatcher().cancelAll();
}
}