使用方法
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()) }
}