我需要检查运行某段代码的线程是否是主(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().equals( Looper.getMainLooper().getThread() )
或者,如果运行时平台是API级别23 (Marshmallow 6.0)或更高:
Looper.getMainLooper().isCurrentThread()
参见Looper API。注意,调用loop . getmainlooper()涉及同步(请参阅源代码)。您可能希望通过存储返回值并重用它来避免开销。
* greg7gkb和2cupsOfTech
总结解决方案,我认为这是最好的一个:
boolean isUiThread = VERSION.SDK_INT >= VERSION_CODES.M
? Looper.getMainLooper().isCurrentThread()
: Thread.currentThread() == Looper.getMainLooper().getThread();
并且,如果你想在UI线程上运行一些东西,你可以使用这个:
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
//this runs on the UI thread
}
});
你可以检查一下
if(Looper.myLooper() == Looper.getMainLooper()) {
// You are on mainThread
}else{
// you are on non-ui thread
}
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”标签,然而,我的搜索与“Android”无关,这是我的头号结果。为此,对于登陆这里的非android SO Java用户,不要忘记:
public static void main(String[] args{
Thread.currentThread().setName("SomeNameIChoose");
/*...the rest of main...*/
}
在你的代码的其他地方设置了这个之后,你可以很容易地检查你是否要在主线程上执行:
if(Thread.currentThread().getName().equals("SomeNameIChoose"))
{
//do something on main thread
}
有点尴尬,我在记得这个之前搜索过,但希望它能帮助其他人!
首先检查是否是主线程
在Kotlin
fun isRunningOnMainThread(): Boolean {
return Thread.currentThread() == Looper.getMainLooper().thread
}
在Java中
static boolean isRunningOnMainThread() {
return Thread.currentThread().equals(Looper.getMainLooper().getThread());
}
除了之前所有的答案
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) }
一种基于协程的、与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
}
推荐文章
- 我如何告诉Spring Boot哪个主类用于可执行jar?
- 如何将Java8流的元素添加到现有的列表中
- 在Java 8中是否可以转换流?
- 我如何在一个片段中访问getSupportFragmentManager() ?
- 并发HashSet<T>在。net框架?
- 调试在哪里。Android Studio中的密钥存储库
- 从资产中读取文件
- 不区分大小写的字符串作为HashMap键
- 在不活动的地方调用getLayoutInflater()
- 什么是maven中的“pom”打包?
- 设置Android布局元素的背景颜色
- 在Java中创建一个自定义事件
- 错误:'keytool'不能被识别为内部或外部命令、可操作程序或批处理文件
- 创建正则表达式匹配数组
- 我如何在Java中初始化一个全零的数组列表?