我需要检查运行某段代码的线程是否是主(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) }
其他回答
Looper.myLooper() == Looper.getMainLooper()
如果返回true,那么你在UI线程上!
你可以使用下面的代码来知道当前线程是否是UI/主线程
if(Looper.myLooper() == Looper.getMainLooper()) {
// Current Thread is Main Thread.
}
或者你也可以用这个
if(Looper.getMainLooper().getThread() == Thread.currentThread()) {
// Current Thread is Main Thread.
}
这里有一个类似的问题
您可以尝试Thread.currentThread().isDaemon()
除了之前所有的答案
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) }
简单的Toast消息也可以作为快速检查。
推荐文章
- 警告:API ' variable . getjavacompile()'已过时,已被' variable . getjavacompileprovider()'取代
- 安装APK时出现错误
- 在流中使用Java 8 foreach循环移动到下一项
- 访问限制:'Application'类型不是API(必需库rt.jar的限制)
- 用Java计算两个日期之间的天数
- 碎片中的onCreateOptionsMenu
- 如何配置slf4j-simple
- 在Jar文件中运行类
- 带参数的可运行?
- TextView粗体通过XML文件?
- 如何使线性布局的孩子之间的空间?
- 自动化invokerrequired代码模式
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数