How to Check/Detect Whether Current Thread is UI/Main Thread or Not in Android

Checking whether the current thread is the UI/Main thread or some other background thread is very easy. Here’s the code for it:

if (Looper.myLooper() == Looper.getMainLooper()) {
    // Current thread is the UI/Main thread
}        

// Another approach

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

Bonus: If you’re in a thread other than the UI Thread and you want to execute a piece of code in the UI thread then you can make use of the runOnUiThread() method.

What's the one thing every developer wants? More screens! Enhance your coding experience with an external monitor to increase screen real estate.

// Sample code from one of my Android applications

runOnUiThread(new Runnable(){
    public void run() {
        mChatMessages.clear();
        mChatMessages.addAll(chatMessages);
        mChatLogAdapter.notifyDataSetChanged();
    }
});

Hope that helps!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Author: Rishabh

Rishabh is a full stack web and mobile developer from India. Follow me on Twitter.

Leave a Reply

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