Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if this thread is a UI Thread

Tags:

Is there any way on Android to know, if the thread running my code, is the UI Thread or not ? In swing there was SwingUtilities.isEventDispatchThread() to tell me if i am on the UI Thread, or not. Is there any function in the Android SDK that lets me know this ?

like image 468
user1730789 Avatar asked Oct 12 '12 09:10

user1730789


People also ask

How can you tell if a thread is main thread?

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

What is an UI thread?

The UIThread is the main thread of execution for your application. This is where most of your application code is run. All of your application components (Activities, Services, ContentProviders, BroadcastReceivers) are created in this thread, and any system calls to those components are performed in this thread.

What is difference between UI thread and main thread?

In Android the main thread and the UI thread are one and the same. You can use them interchangeably. In Android each app gets a dedicated process to run. Thus the process will be having a main thread.

Is the main thread the UI thread?

It is also almost always the thread in which your application interacts with components from the Android UI toolkit (components from the android. widget and android. view packages). As such, the main thread is also sometimes called the UI thread.


2 Answers

  1. Answer borrowed from here: How to check if current thread is not main thread

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

  2. Any Android app has only one UI thread, so you could somewhere in the Activity callback like onCreate() check and store its ID and later just compare that thread's ID to the stored one.

    mMainThreadId = Thread.currentThread().getId();

  3. Anyway, you can omit checking if you want to do something on the UI thread and have any reference to Activity by using

    mActivity.runOnUiThread( new Runnable() {     @Override      public void run() {     ...     } }); 

which is guaranteed to run on current thread, if it's UI, or queued in UI thread.

like image 87
Fenix Voltres Avatar answered Sep 26 '22 06:09

Fenix Voltres


Yes, there is a way. Check the current thread object against main lopper's thread object. Main looper is always in the UI thread.

boolean isOnUiThread = Thread.currentThread() == Looper.getMainLooper().getThread(); 
like image 33
Cleosson Avatar answered Sep 26 '22 06:09

Cleosson