You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

75 lines
2.4 KiB

package com.gyf.csams
import android.app.Application
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap
import coil.ImageLoader
import coil.ImageLoaderFactory
import coil.imageLoader
import coil.memory.MemoryCache
import coil.request.ImageRequest
import coil.util.CoilUtils
import com.gyf.csams.uikit.BackgroundImage
import com.gyf.csams.util.ImageUtil
import com.orhanobut.logger.AndroidLogAdapter
import com.orhanobut.logger.DiskLogAdapter
import com.orhanobut.logger.Logger
import okhttp3.OkHttpClient
class APP : Application(), ImageLoaderFactory {
private val backgroundImage = mutableMapOf<BackgroundImage, MemoryCache.Key?>()
suspend fun getImage(image: BackgroundImage): ImageBitmap? {
val key = backgroundImage[image]
if (key != null) {
return applicationContext.imageLoader.memoryCache[key]?.asImageBitmap()
?: ImageUtil.getImage(applicationContext, image.id)
} else {
throw IllegalArgumentException("无法从${key}获取背景图!")
}
}
override fun newImageLoader(): ImageLoader {
return ImageLoader.Builder(applicationContext)
.crossfade(true)
.okHttpClient {
OkHttpClient.Builder()
.cache(CoilUtils.createDefaultCache(applicationContext))
.build()
}
.build()
}
/**
* 预加载背景图
*
*/
private fun preloadImage() {
BackgroundImage.values().forEach {
Logger.i("预加载背景图:${it.name}")
val request = ImageRequest.Builder(applicationContext)
.data(it.id)
// Optional, but setting a ViewSizeResolver will conserve memory by limiting the size the image should be preloaded into memory at.
.size(800, 600)
.listener { _, metadata ->
Logger.i("metadata.memoryCacheKey=${metadata.memoryCacheKey}")
backgroundImage[it] = metadata.memoryCacheKey
}
.build()
applicationContext.imageLoader.enqueue(request = request)
}
}
override fun onCreate() {
super.onCreate()
//初始化日志
Logger.addLogAdapter(AndroidLogAdapter())
Logger.addLogAdapter(DiskLogAdapter())
Logger.i("${BuildConfig.foreground_app_name}启动")
preloadImage()
}
}