我需要检查运行某段代码的线程是否是主(UI)线程。我怎样才能做到这一点呢?
当前回答
除了之前所有的答案
inline fun <T> ensureNotOnMainThread(block: () -> T): T {
check(Thread.currentThread() != Looper.getMainLooper().thread) { "This function cannot be called on main thread" }
return block()
}
允许用它包装任何方法,示例如下:
fun isInDataBase(id: String) = ensureNotOnMainThread { db.contains(id) }
其他回答
只需记录这一行,它应该打印“main”。
Thread.currentThread () . name
最好的方法是最清晰、最健壮的方法:*
Thread.currentThread().equals( Looper.getMainLooper().getThread() )
或者,如果运行时平台是API级别23 (Marshmallow 6.0)或更高:
Looper.getMainLooper().isCurrentThread()
参见Looper API。注意,调用loop . getmainlooper()涉及同步(请参阅源代码)。您可能希望通过存储返回值并重用它来避免开销。
* greg7gkb和2cupsOfTech
Xamarin的。Android端口:(c#)
public bool IsMainThread => Build.VERSION.SdkInt >= BuildVersionCodes.M
? Looper.MainLooper.IsCurrentThread
: Looper.MyLooper() == Looper.MainLooper;
用法:
if (IsMainThread) {
// you are on UI/Main thread
}
你可以在android DDMS logcat中验证它,其中进程id将是相同的,但线程id将不同。
一种基于协程的、与android无关的方法:
val 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
}
推荐文章
- 如何在java中格式化持续时间?(如格式H:MM:SS)
- urlencoder .encode(字符串)已弃用,我应该使用什么代替?
- javax.transaction.Transactional vs . org.springframework.transaction.annotation.Transactional
- Java 8接口方法中不允许“同步”的原因是什么?
- 如何找到Java堆大小和内存使用(Linux)?
- 改变开关的“开”色
- 以编程方式将EditText的输入类型从PASSWORD更改为NORMAL,反之亦然
- 如何在隐藏和查看密码之间切换
- 在Android上调整一个大的位图文件到缩放输出文件
- 使用Enum实现单例(Java)
- 如何更改Android版本和代码版本号?
- Android Studio突然无法解析符号
- 应用程序重新启动而不是恢复
- RabbitMQ与通道和连接之间的关系
- 跨线程操作无效:控件“textBox1”从创建它的线程以外的线程访问