gpt4 book ai didi

android - 如何检测Android上的UI线程?

转载 作者:IT老高 更新时间:2023-10-28 13:02:03 24 4
gpt4 key购买 nike

是否有可靠的方法来检测 Thread.currentThread() 是否是应用程序中的 Android 系统 UI 线程?
我想在我的模型代码中添加一些断言,断言只有一个线程(例如 ui 线程)访问我的状态,以确保不需要任何同步。

最佳答案

确定 UI 线程身份的常见做法是通过 Looper#getMainLooper :

if (Looper.getMainLooper().getThread() == Thread.currentThread()) {
// On UI thread.
} else {
// Not on UI thread.
}

从 API 级别 23 起,使用新的辅助方法 isCurrentThread 有一种更易读的方法在主循环器上:

if (Looper.getMainLooper().isCurrentThread()) {
// On UI thread.
} else {
// Not on UI thread.
}

关于android - 如何检测Android上的UI线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2848575/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com