j2emanue j2emanue - 1 year ago 234
Android Question

Android - myLooper() vs getMainLooper()

Just clarifying but in an Android activity on MAIN Thread if i call Looper.myLooper() vs Looper.getMainLooper() the return the same reference, right ? they are the same thing ? I know i would never have to call these usually as android takes care of this but i'd like to know how they differ when being called from the main thread ?

if from the main thread i call

// or

They both give the same runtime exception so im assuming they are the same reference:

Caused by: java.lang.RuntimeException: Main thread not allowed to quit.

can anyone confirm ?

Answer Source

You have it described in the docs:


Returns the application's main looper, which lives in the main thread of the application.


Return the Looper object associated with the current thread. Returns null if the calling thread is not associated with a Looper.

As for whether getMainLooper() is of any use, I can assure you it really is. If you do some code on a background thread and want to execute code on the UI thread, e.g. update UI, use the following code:

new Handler(Looper.getMainLooper()).post(new Runnable() {
  // execute code that must be run on UI thread

Of course, there are other ways of achieving that.

Another use is, if you want to check if the currently executed code is running on the UI thread, e.g. you want to throw / assert:

boolean isUiThread = Looper.getMainLooper().getThread() == Thread.currentThread();


boolean isUiThread = Looper.getMainLooper().isCurrentThread();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download