代码如下:
主要思路就是利用它打印的位置,然后计算两次打印的时间,然后控制打印的评率。
class IntervalLogUtil {
companion object {
val time = 2000 // 间隔时间为2秒
val map = mutableMapOf<String, Long>()
fun e(tag: String, msg: String) {
val currentTime = System.currentTimeMillis()
if (currentTime - (map[getLocation()] ?: 0) > time) {
Log.e(tag, msg)
map[getLocation()] = currentTime
}
}
/**
* 输出日志的位置
* @return
*/
private fun getLocation(): String {
var result = ""
try {
val stackTraceElement = Exception().stackTrace[2]
val position = stackTraceElement.toString()
val lineNumber = (stackTraceElement.lineNumber.toString() + "").length
result =
position.substring(position.length - (stackTraceElement.fileName.length + lineNumber + 2 + 1))
} catch (e: Exception) {
}
return result
}
}
}