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?
if(Looper. getMainLooper(). getThread() == Thread. currentThread()) { // Current Thread is Main Thread. }
A thread can be created by implementing the Runnable interface and overriding the run() method. The current thread is the currently executing thread object in Java. The method currentThread() of the Thread class can be used to obtain the current thread.
currentThread. Returns a reference to the currently executing thread object. Returns: the currently executing thread.
currentThread() , you will obtain the reference to the currently executing thread object (reference to the thread, in which, this method is invoked).
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. }
Here is similar question
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With