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 ?
if(Looper. getMainLooper(). getThread() == Thread. currentThread()) { // Current Thread is Main 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.
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.
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.
Answer borrowed from here: How to check if current thread is not main thread
Looper.myLooper() == Looper.getMainLooper()
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();
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.
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();
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