2018-09-20 Android清除缓存(Kotlin)

2018-09-20  本文已影响0人  肉某人

获取文件或文件夹大小

fun File.size(): Long {
    var size = 0L
    try {
        if (isFile) {
            size += length()
        }
        if (isDirectory) {
            listFiles().forEach {
                size += it.size()
            }
        }
    } catch (e: Exception) {
        e.printStackTrace()
    }
    return size
}

删除文件或文件夹

fun File.suicide() {
    if (isFile) delete()
    if (isDirectory) listFiles().forEach { it.suicide() }
}

获取缓存大小

private fun getCacheSize(context: Context): Long {
        val cacheSize = (context as SettingsAct).cacheDir.size()
        val fileSize = context.filesDir.size()
        return cacheSize + fileSize
    }

清除一般操作

    fun clearCache(context: Context) {
        val cacheSize = getCacheSize(context)
        if (cacheSize > 0) {
            context.alert("清除所有缓存?", "清除", "取消") {
                (context as SettingsAct).cacheDir.suicide()
                context.filesDir.suicide()
                message.value = "成功清除${cacheSize.formatMemorySize()}缓存"
                this.cacheSize.set("0K")
            }
        } else message.value = "无需清理"
    }
//show alert dialog
fun Context.alert(message: String, confirmText: String, cancelText: String, onConfirm: () -> Unit) {
    AlertDialog.Builder(this)
            .setMessage(message)
            .setNegativeButton(cancelText) { dialog, _ -> dialog.dismiss() }
            .setPositiveButton(confirmText) { dialog, _ ->
                dialog.dismiss()
                onConfirm()
            }.show()
}
fun Long.formatMemorySize(): String {
    val kiloByte = this / 1024.toDouble()

    val megaByte = kiloByte / 1024
    if (megaByte < 1) {
        return kiloByte.toBigDecimal().setScale(2, BigDecimal.ROUND_HALF_UP).toString() + "K"
    }

    val gigaByte = megaByte / 1024
    if (gigaByte < 1) {
        return megaByte.toBigDecimal().setScale(2, BigDecimal.ROUND_HALF_UP).toString() + "M"
    }

    val teraBytes = megaByte / 1024
    if (teraBytes < 1) {
        return megaByte.toBigDecimal().setScale(2, BigDecimal.ROUND_HALF_UP).toString() + "G"
    }

    return teraBytes.toBigDecimal().setScale(2, BigDecimal.ROUND_HALF_UP).toString() + "T"
}
上一篇下一篇

猜你喜欢

热点阅读