Android Kotlin 代码笔记,全局的UI线程回调函数(

2020-08-26  本文已影响0人  水天滑稽天照八野滑稽石

使用方法

postUI{
      //需要跑在UI线程的代码块
}

代码实现

fun <T> T.postUI(action: () -> Unit) {

    // Fragment
    if (this is Fragment) {
        val fragment = this
        if (!fragment.isAdded) return

        val activity = fragment.activity ?: return
        if (activity.isFinishing) return

        activity.runOnUiThread(action)
        return
    }

    // Activity
    if (this is Activity) {
        if (this.isFinishing) return

        this.runOnUiThread(action)
        return
    }

    // 主线程
    if (Looper.getMainLooper() === Looper.myLooper()) {
        action()
        return
    }

    // 子线程,使用handler
    KitUtil.handler.post { action() }
}

object KitUtil{
     val handler: Handler by lazy {  Handler(Looper.getMainLooper()) }
}
上一篇下一篇

猜你喜欢

热点阅读