How to know if this thread is a UI Thread

user1730789 picture user1730789 · Oct 12, 2012 · Viewed 13.9k times · Source

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 ?

Answer

Fenix Voltres picture Fenix Voltres · Oct 12, 2012
  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.