自定义LruCache工具类

68 阅读1分钟

新建ImageCacheManager工具类

object ImageCacheManager {

    private const val DEFAULT_CACHE_SIZE_RATIO = 8
    private var bitmapCache: LruCache<String, Bitmap?>? = null

    fun initialize() {
        val maxMemory = (Runtime.getRuntime().maxMemory() / 1024).toInt()
        val cacheSize = maxMemory / DEFAULT_CACHE_SIZE_RATIO
        bitmapCache = object : LruCache<String, Bitmap?>(cacheSize) {
            override fun sizeOf(key: String, value: Bitmap): Int {
                return value.allocationByteCount / 1024
            }
        }
    }

    fun get(key: String): Bitmap? {
        return bitmapCache?.get(key)
    }

    fun put(key: String, bitmap: Bitmap) {
        bitmapCache?.put(key, bitmap)
    }

    fun trimMemory(level: Int) {
        when(level) {
            ComponentCallbacks2.TRIM_MEMORY_COMPLETE -> {
                dispose()
            }

            ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE -> {
                trimCache(50)
            }

            ComponentCallbacks2.TRIM_MEMORY_BACKGROUND -> {
                trimCache(20)
            }
        }
    }

    private fun trimCache(percent: Int) {
        bitmapCache?.apply {
            val targetSize = maxSize() * (100 - percent) / 100
            trimToSize(targetSize)
        }
    }

    fun dispose() {
        bitmapCache?.evictAll()
    }

}

在application类里面去初始化,并在应用状态发生变化时做相应的处理

@Override
public void onCreate() {
   super.onCreate();
   ImageCacheManager.INSTANCE.initialize();
}

@Override
public void onTerminate() {
    ImageCacheManager.INSTANCE.dispose();
    super.onTerminate();
}

@Override
public void onTrimMemory(int level) {
    super.onTrimMemory(level);
    ImageCacheManager.INSTANCE.trimMemory(level);
}

@Override
public void onLowMemory() {
    super.onLowMemory();
    ImageCacheManager.INSTANCE.dispose();
}