Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 375
Charlie-Blake Avatar asked Jul 10 '12 10:07

Charlie-Blake


People also ask

How can you tell if a thread is main thread?

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

How do you find the current 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.

What does thread currentThread () return?

currentThread. Returns a reference to the currently executing thread object. Returns: the currently executing thread.

Which method is always called on current thread?

currentThread() , you will obtain the reference to the currently executing thread object (reference to the thread, in which, this method is invoked).


2 Answers

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

if this returns true, then you're on the UI thread!

like image 101
Carnal Avatar answered Sep 20 '22 09:09

Carnal


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

like image 45
AAnkit Avatar answered Sep 23 '22 09:09

AAnkit