如何在Android上检测UI线程?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2848575/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 07:36:30  来源:igfitidea点击:

How to detect UI thread on Android?

android

提问by ParDroid

Is there a robust way to detect if Thread.currentThread()is the Android system UI thread in an application?
I would like to put some asserts in my model code that asserts that only one thread (egthe ui thread) accesses my state, to assure that no kind of synchronization is necessary.

是否有一种可靠的方法来检测Thread.currentThread()应用程序中是否存在Android 系统 UI 线程?
我想在我的模型代码中放置一些断言,断言只有一个线程(例如ui 线程)访问我的状态,以确保不需要任何类型的同步。

回答by mik3y

Common practice to determine the UI Thread's identity is via Looper#getMainLooper:

确定 UI 线程身份的常见做法是通过Looper#getMainLooper

if (Looper.getMainLooper().getThread() == Thread.currentThread()) {
  // On UI thread.
} else {
  // Not on UI thread.
}

From API level 23 and up, there's a slightly more readable approach using new helper method isCurrentThreadon the main looper:

从 API 级别 23 开始,在主循环程序上使用新的辅助方法isCurrentThread有一种更具可读性的方法:

if (Looper.getMainLooper().isCurrentThread()) {
  // On UI thread.
} else {
  // Not on UI thread.
}

回答by ATom

I think that best way is this:

我认为最好的方法是这样的:

 if (Looper.getMainLooper().equals(Looper.myLooper())) {
     // UI thread
 } else {
     // Non UI thread
 }

回答by stan0

As of API level 23 the Looperhas a nice helper method isCurrentThread. You could get the mainLooperand see if it's the one for the current thread this way:

从 API 级别 23 开始,它Looper有一个很好的辅助方法isCurrentThread。您可以通过mainLooper这种方式获取并查看它是否是当前线程的那个:

Looper.getMainLooper().isCurrentThread()

It's practically the same as:

它实际上与以下相同:

Looper.getMainLooper().getThread() == Thread.currentThread()

but it could be a bit more readable and easier to remember.

但它可能更具可读性,更容易记住。

回答by cmicat

public boolean onUIThread() {
    return Looper.getMainLooper().isCurrentThread();

}

But it requires API level 23

但它需要 API 级别 23

回答by yushulx

Besides checking looper, if you ever tried to logoutthread id in onCreate(), you could find the UI thread(main thread)id always equals to 1. Therefore

除了检查looper,如果你曾经尝试注销线程 id in onCreate(),你会发现UI 线程(主线程)id 总是等于 1。因此

if (Thread.currentThread().getId() == 1) {
    // UI thread
}
else {
    // other thread
}

回答by yushulx

Couldn't you use the runOnUiThreadmethod in the Activityclass?See..

你不能runOnUiThreadActivity课堂上使用这个方法吗?看..

http://developer.android.com/reference/android/app/Activity.html#runOnUiThread%28java.lang.Runnable%29

http://developer.android.com/reference/android/app/Activity.html#runOnUiThread%28java.lang.Runnable%29