How to check if current thread is not main thread

I need to check if the thread running a certain piece of code is the main (UI) thread or not. How can I achieve this?


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

如果这返回true,那么你在UI线程上!


you can use below code to know if current thread is UI/Main thread or not

if(Looper.myLooper() == Looper.getMainLooper()) {
   // Current Thread is Main Thread.
}

or you can also use this

if(Looper.getMainLooper().getThread() == Thread.currentThread()) {
   // Current Thread is Main Thread.
}

Here is similar question


The best way is the clearest way: *

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

Or, if the runtime platform is API level 23 (Marshmallow 6.0) or higher:

Looper.getMainLooper().isCurrentThread()

See the Looper API. Note that calling Looper.getMainLooper() involves synchonization (see the source). You might want to avoid the overhead by storing the return value and reusing it.

* credit greg7gkb

链接地址: http://www.djcxy.com/p/87914.html

上一篇: 在Android排球库中使用Cookie

下一篇: 如何检查当前线程是否不是主线程