I need to check if the thread running a certain piece of code is the main (UI) thread or not. How can I achieve this?
10 Answers
The best way is the clearest, most robust way: *
Thread.currentThread().equals( Looper.getMainLooper().getThread() )
Or, if the runtime platform is API level 23 (Marshmallow 6.0) or higher:
Looper.getMainLooper().isCurrentThread()
See the Looper API. Note that calling Looper.getMainLooper()
involves synchronization (see the source). You might want to avoid the overhead by storing the return value and reusing it.
* credit greg7gkb and 2cupsOfTech
Summarizing the solutions, I think that's the best one:
boolean isUiThread = VERSION.SDK_INT >= VERSION_CODES.M
? Looper.getMainLooper().isCurrentThread()
: Thread.currentThread() == Looper.getMainLooper().getThread();
And, if you wish to run something on the UI thread, you can use this:
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
//this runs on the UI thread
}
});
Allow me to preface this with: I acknowledged this post has the 'Android' tag, however, my search had nothing to do with 'Android' and this was my top result. To that end, for the non-Android SO Java users landing here, don't forget about:
public static void main(String[] args{
Thread.currentThread().setName("SomeNameIChoose");
/*...the rest of main...*/
}
After setting this, elsewhere in your code, you can easily check if you're about to execute on the main thread with:
if(Thread.currentThread().getName().equals("SomeNameIChoose"))
{
//do something on main thread
}
A bit embarrassed I had searched before remembering this, but hopefully it will help someone else!