我需要检查运行某段代码的线程是否是主(UI)线程。我怎样才能做到这一点呢?
当前回答
您可以尝试Thread.currentThread().isDaemon()
其他回答
请允许我先说: 我承认这篇文章有“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
}
有点尴尬,我在记得这个之前搜索过,但希望它能帮助其他人!
简单的Toast消息也可以作为快速检查。
总结解决方案,我认为这是最好的一个:
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
}
});
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将不同。
推荐文章
- 警告: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中的回调函数