问题描述
我怎么能知道,如果运行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$c$c>类是通过比较 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:
- 赶android.view.ViewRoot $ CalledFromWrongThreadException
- <$c$c>post$c$c>一个
的Runnable
来一个观点,并检查Thread.currentThread()
- 使用
处理程序
以做同样的
- catch the android.view.ViewRoot$CalledFromWrongThreadException
post
aRunnable
to a view and checkThread.currentThread()
- 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线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!