package com.iflytek.autofly.mediax
import android.os.Debug
import android.os.Looper
import android.os.SystemClock
import android.text.TextUtils
import android.util.Log
import android.util.Printer
import android.util.StringBuilderPrinter
// watch all runnable which post in main thread
class MainLooperWatcher : Printer {
private val TAG ="MainLooperWatcher"
? ? private var mLastMillis: Long =0
? ? fun mainThreadWatcher() {
Looper.getMainLooper().setMessageLogging(this)
}
override fun println(msg: String?) {
// ignore system task
? ? ? ? if (msg ==null
? ? ? ? ? ? ? ? || TextUtils.isEmpty(msg)
||msg.contains("Choreographer")
||msg.contains("ActivityThread\$H")
)return
? ? ? ? if (msg.startsWith(">>>>> Dispatching")) {
mLastMillis = SystemClock.elapsedRealtime()
}else if (msg.startsWith("<<<<< Finished")) {
val now = SystemClock.elapsedRealtime()
val usedMillis = now -mLastMillis
? ? ? ? ? ? if (usedMillis <16L) {
return
? ? ? ? ? ? }
if (usedMillis <100L) {
Log.w(TAG, " $usedMillis ms used for $msg")
return
? ? ? ? ? ? }
if (usedMillis >=100L) {
report(msg, usedMillis)
}
}
}
private fun report(msg: String, usedMillis: Long) {
val sb = StringBuilder()
Looper.getMainLooper().dump(StringBuilderPrinter(sb), "")
Log.e(TAG, "$usedMillis ms used for $msg, $sb")
val exp ="[Block Runnable] ${usedMillis}ms used for ${msg}"
? ? ? ? Log.e(TAG, exp)
if (Debug.isDebuggerConnected() || Debug.waitingForDebugger()){
return
? ? ? ? }
if (BuildConfig.DEBUG && usedMillis >2000) {
throw RuntimeException(exp)
}
}
}