本文為單張圖片的內(nèi)存緩存的示例
1形病、首先創(chuàng)建LruCache緩存工具類(lèi), 拿出最大可用內(nèi)存的八分之一,作為圖片緩存的大小霞幅。
/**
* 圖片的內(nèi)存緩存工具類(lè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途乃、創(chuàng)建圖片下載工具類(lèi)
public class BitmapUtil {
/**
* HttpURLConnection下載圖片并轉(zhuǎn)化為bitmap
* @param imgUrl
* @return
*/
public static Bitmap getBitmapFromNet(String imgUrl) {
try {
//生成url
URL url = new URL(imgUrl);
//建立連接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//設(shè)置超時(shí) 5s
connection.setConnectTimeout(5000);
//設(shè)置請(qǐng)求方法
connection.setRequestMethod("GET");
//連接成功
if (connection.getResponseCode()==200){
//獲取輸入流
InputStream in=connection.getInputStream();
//將流轉(zhuǎn)化為bitmap
return BitmapFactory.decodeStream(in);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
3、使用LruCache扔傅。
- 首先判斷內(nèi)存里是否有圖片緩存耍共,如果有直接顯示;
- 如果沒(méi)有猎塞,則需要通過(guò)HttpURLConnection下載试读,如果下載成功則將圖片存入緩存,下載失敗則存入一張默認(rèn)圖片荠耽;
- 然后讀取緩存钩骇,將圖片顯示出來(lái);
/**
* 【單張圖片內(nèi)存緩存】
*
* 殺進(jìn)程或者清空APP緩存, 緩存數(shù)據(jù)就不存在了
*/
class SingleImageMemoryCacheActivity : 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_cache)
imageView = findViewById(R.id.image_id)
loadBitmap(oriUrl,imageView)
}
private fun loadBitmap(resId: String?, imageView: ImageView?) {
// 查看下內(nèi)存緩存中是否緩存了這張圖片
val bitmap = CacheUtils.getBitmapFromMemCache(resId)
if (bitmap != null) {
Log.d("Neo","取到指定圖片的緩存了铝量,直接展示")
imageView?.setImageBitmap(bitmap)
} else {
Log.d("Neo","沒(méi)有取到指定圖片的緩存倘屹,進(jìn)行下一步")
imageView?.setImageResource(R.drawable.ic_launcher_background)
val task = BitmapWorkerTask(this@SingleImageMemoryCacheActivity)
task.execute(resId)
}
}
companion object {
class BitmapWorkerTask internal constructor(context : SingleImageMemoryCacheActivity) : AsyncTask<String,String,Bitmap>(){
private val activityReference: WeakReference<SingleImageMemoryCacheActivity> = WeakReference(context)
private lateinit var thisUrl : String
override fun doInBackground(vararg params: String?): Bitmap {
val thisActivity = activityReference.get()
//網(wǎng)絡(luò)圖片請(qǐng)求失敗,則加載本地的默認(rèn)圖片慢叨,同時(shí)緩存這張默認(rèn)圖片
return if(BitmapUtil.getBitmapFromNet(params[0]) == null){
Log.d("Neo","網(wǎng)圖獲取失敗纽匙,提供一張本地圖片")
thisUrl = "LOCAL_IMAGE_RESOURCE"
BitmapFactory.decodeResource(thisActivity?.resources, R.mipmap.icon6)
}else{
Log.d("Neo","網(wǎng)圖獲取成功并返回")
thisUrl = params[0].toString()
BitmapUtil.getBitmapFromNet(params[0])
}
}
override fun onPostExecute(result: Bitmap?) {
val thisActivity = activityReference.get()
Log.d("Neo","展示圖片,并將圖片保存到內(nèi)存緩存中")
thisActivity?.imageView?.setImageBitmap(result)
CacheUtils.addBitmapToMemoryCache(thisUrl, result)
}
}
}
}
4插爹、布局文件
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activitys.SingleImageMemoryCacheActivity">
<ImageView
android:id="@+id/image_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>