我需要检查运行某段代码的线程是否是主(UI)线程。我怎样才能做到这一点呢?
当前回答
Looper.myLooper() == Looper.getMainLooper()
如果返回true,那么你在UI线程上!
其他回答
你可以检查一下
if(Looper.myLooper() == Looper.getMainLooper()) {
// You are on mainThread
}else{
// you are on non-ui thread
}
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.
}
这里有一个类似的问题
你可以在android DDMS logcat中验证它,其中进程id将是相同的,但线程id将不同。
您可以尝试Thread.currentThread().isDaemon()
推荐文章
- 我如何告诉Spring Boot哪个主类用于可执行jar?
- 如何将Java8流的元素添加到现有的列表中
- 在Java 8中是否可以转换流?
- 我如何在一个片段中访问getSupportFragmentManager() ?
- 并发HashSet<T>在。net框架?
- 调试在哪里。Android Studio中的密钥存储库
- 从资产中读取文件
- 不区分大小写的字符串作为HashMap键
- 在不活动的地方调用getLayoutInflater()
- 什么是maven中的“pom”打包?
- 设置Android布局元素的背景颜色
- 在Java中创建一个自定义事件
- 错误:'keytool'不能被识别为内部或外部命令、可操作程序或批处理文件
- 创建正则表达式匹配数组
- 我如何在Java中初始化一个全零的数组列表?