我需要检查运行特定代码的线程是否为主线程(UI线程)。如何实现?
我需要检查运行特定代码的线程是否为主线程(UI线程)。如何实现?
C#
)public bool IsMainThread => Build.VERSION.SdkInt >= BuildVersionCodes.M
? Looper.MainLooper.IsCurrentThread
: Looper.MyLooper() == Looper.MainLooper;
使用方法:
if (IsMainThread) {
// you are on UI/Main thread
}
所以又一个答案加入公司,用于某些扩展文件的Kotlin:
import android.os.Looper.getMainLooper
import java.lang.Thread.currentThread
val Thread.isMain get() = getMainLooper().thread == this
val isThreadMain get() = getMainLooper().thread == currentThread()
一个简单的Toast消息也可以作为快速检查。
Toast.makeText(activity, "Hello main thread", Toast.LENGTH_LONG).show();
- Stefan Irndorferval onMainThread: Boolean
get() = Thread.currentThread() === try {
runBlocking(Dispatchers.Main.immediate) {
Thread.currentThread()
}
} catch (e: IllegalStateException) {
// No main dispatcher has been registered; not in an Android context?
null
}