Android - MyLooper() Vs GetMainLooper()


Answer :

You have it described in the docs:

getMainLooper()

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

myLooper()

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

or

boolean isUiThread = Looper.getMainLooper().isCurrentThread(); 

Looper.getMainLooper() is convenience API to get looper which is attached to the main thread of the activity.It is usefull when you want to excute some code on main thread from a background thread.

It is usually used as follows:

new Handler(Looper.getMainLooper()).post(task); 

Looper.myLooper() is api to get looper attached to current thread


If you call these two methods in the main thread, they are the same object! You can find answers in the source code of ActivityThread.java, Looper.java and ThreadLocal.java.


Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable