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

2023-09-12 01:35:39 作者:如果没有如果

我怎么能知道,如果运行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中的方法。该检查是在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:

赶android.view.ViewRoot $ CalledFromWrongThreadException post一个的Runnable 来一个观点,并检查 Thread.currentThread() 使用 处理程序 以做同样的 catch the android.view.ViewRoot$CalledFromWrongThreadException post a Runnable to a view and check Thread.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.).