java – How to know if this thread is a UI Thread-ThrowExceptions

Exception or error:

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 ?

How to solve:
  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.

###

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();

###

Hum actually due to Android architecture, all Activities run in the main thread, ie the UI thread. So when you are coding an activity, everything that is in your Activity is in the UI thread.
That is why in Honeycomb an error have been added when you are making network calls in the main thread : it totally blocks the UI.

So by default you are in fact always working in the UI thread.
Another thing : unless you explicitely ask it to be in another thread, a Service will operate on the same thread as the activities of its application.

So, what to do ?

  • When you have to do heavy calculation in your activity; one solution is to use an AsyncTask (a class designed to allow you to easily use another thread). The code in onExecute() is run in another thread (but be cautious postExecute runs in your main thread). Another one is to manually start a new thread when AsyncTask is not really adapted.
  • If you create a service that does costly background tasks, make it run in another thread with the android:process=”:my_process” attribute of the manifest. You will need to create an AIDL to communicate with this separated service, but it is not a complicated task.
  • Many objects, like for example the MediaPlayer, have Async variations of their methods. Try to to always use them.

###

Put a breakpoint where you want to check and, when it gets hit, check if you can interact with your UI (ie, if the UI is not frozen). If you can’t interact with the UI then you are in the UI Thread, otherwise you are in a background thread.

Leave a Reply

Your email address will not be published. Required fields are marked *