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?
This question is related to
java
android
multithreading
A simple Toast message works also as a quick check.
You can try Thread.currentThread().isDaemon()
Xamarin.Android
port: (C#
)
public bool IsMainThread => Build.VERSION.SdkInt >= BuildVersionCodes.M
? Looper.MainLooper.IsCurrentThread
: Looper.MyLooper() == Looper.MainLooper;
Usage:
if (IsMainThread) {
// you are on UI/Main 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!
you can use below code to know if current thread is UI/Main thread or not
if(Looper.myLooper() == Looper.getMainLooper()) {
// Current Thread is Main Thread.
}
or you can also use this
if(Looper.getMainLooper().getThread() == Thread.currentThread()) {
// Current Thread is Main Thread.
}
you can verify it in android ddms logcat where process id will be same but thread id will be different.
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
}
});
You can check
if(Looper.myLooper() == Looper.getMainLooper()) {
// You are on mainThread
}else{
// you are on non-ui thread
}
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
Source: Stackoverflow.com