如何检查是否在Android的UI线程上运行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1845678/
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 03:42:22  来源:igfitidea点击:

How to check if running on UI thread in Android?

androidmultithreading

提问by Arutha

How can I know if the running code is executed on the main thread (UI thread)?
With Swing I use the isEventDispatchThreadmethod...

如何知道正在运行的代码是否在主线程(UI 线程)上执行?
随着 Swing 我使用的isEventDispatchThread方法......

采纳答案by Josef Pfleger

Doesn't look like there is a method for that in the SDK. The check is in the ViewRootclass and is done by comparing Thread.currentThread()to a class member which is assigned in the constructor but never exposed.

看起来 SDK 中没有这种方法。检查在ViewRoot类中,通过与Thread.currentThread()在构造函数中分配但从未公开的类成员进行比较来完成。

If you really need this check you have several options to implement it:

如果你真的需要这个检查,你有几个选项来实现它:

  1. catch the android.view.ViewRoot$CalledFromWrongThreadException
  2. posta Runnableto a view and check Thread.currentThread()
  3. use a Handlerto do the same
  1. 抓住 android.view.ViewRoot$CalledFromWrongThreadException
  2. postRunnable对的图,检查Thread.currentThread()
  3. 使用 aHandler做同样的事情

In general I think instead of checkingwhether you're on the correct thread, you should just make surethe code is always executed on the UI thread (using 2. or 3.).

一般来说,我认为与其检查您是否在正确的线程上,您应该确保代码始终在 UI 线程上执行(使用 2. 或 3.)。

回答by Dan Syrstad

Use Looper.getMainLooper().getThread() to get the UI thread. You can check if it is the current thread using the following expression:

使用 Looper.getMainLooper().getThread() 获取 UI 线程。您可以使用以下表达式检查它是否是当前线程:

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

回答by balazsbalazs

It is UI thread if:

它是 UI 线程,如果:

Looper.myLooper() == Looper.getMainLooper()

Source AOSP source code: ManagedEGLContext.java#L100, SharedPreferencesImpl.java#L470, Instrumentation.java#L1650and so on.

来源AOSP源代码:ManagedEGLContext.java#L100SharedPreferencesImpl.java#L470Instrumentation.java#L1650

回答by michael

You may also use runOnUiThread, it only requires a runnable that will be run in the ui thread

您也可以使用runOnUiThread,它只需要一个将在 ui 线程中运行的可运行对象

回答by cesar

If you want to know if you are in the main thread, you could maybe try:

如果你想知道你是否在主线程中,你可以尝试:

Context c = **Get a Context**;
Thread.currentThread() == c.getMainLooper().getThread();

Of course, I could be wrong, and this could totally blow your app up.

当然,我可能是错的,这可能会彻底炸毁你的应用程序。