How to check if current thread is not main thread
Looper.myLooper() == Looper.getMainLooper()
if this returns true, then you're on the UI thread!
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.}
The best way is the clearest, most robust way: *
Thread.currentThread().equals( 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 synchronization (see the source). You might want to avoid the overhead by storing the return value and reusing it.
* credit greg7gkb and 2cupsOfTech