如何检查是否在运行Android UI线程? [英] How to check if running on UI thread in Android?

查看:290
本文介绍了如何检查是否在运行Android UI线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么能知道,如果运行code是主线程(UI线程)上执行?
随着秋千我用的是 isEventDispatchThread 方法...

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

推荐答案

看起来不像有该SDK中的方法。该检查是在<一个href="http://android.git.kernel.org/?p=platform/frameworks/base.git;a=blob;f=core/java/android/view/ViewRoot.java;h=bef3e580a0c5ad037a0b495979ecf567c5a80995;hb=HEAD#l2681"><$c$c>ViewRoot类是通过比较 Thread.currentThread()来被分配在构造函数中,但不会暴露类成员完成的。

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

如果你真的需要这个检查可以有多种选择来实现它:

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

  1. 赶android.view.ViewRoot $ CalledFromWrongThreadException
  2. <一个href="http://developer.android.com/reference/android/view/View.html#post%28java.lang.Runnable%29"><$c$c>post一个的Runnable 来一个观点,并检查 Thread.currentThread()
  3. 使用 处理程序 以做同样的
  1. catch the android.view.ViewRoot$CalledFromWrongThreadException
  2. post a Runnable to a view and check Thread.currentThread()
  3. use a Handler to do the same

在一般我想代替的检查的,无论你是在正确的线程,你应该只的确定的的code总是执行在UI线程(使用2或3)。

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

这篇关于如何检查是否在运行Android UI线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆