2012年7月26日木曜日

difference between getMainLooper() and Looper.myLooper()

I'm now trying to resurrect one project. There was an exception on getMainLooper()...

I thought that may be there's a problem with MainLooper initialization and added Looper.prepareMainLoop() before that.

Exception telling me that there's already a looper for that object was thrown...

Then I tried to replace getMainLooper() with Looper.myLooper() and it worked...

But I didn't understand why=)

In fact I don't get the difference between this two things. I think that on the place where getMainLooper() was used in my project it's the best place for the true main looper of the application but I got what I got..

Please explain.

Thank you for your attention

 
 

The difference is that Looper.preapreMainLooper() prepares looper in main UI thread. Android applications normally do not call this function. As main thread has its looper prepared long before first activity, service, provider or broadcast receiver is started.

But Looper.prepareLooper() prepares Looper in current thread. After this function is called, thread can call Looper.loop() to start processing messages with Handlers.

So, in your case you had two threads - X and Y. The X thread is the main UI thread that has its looper already prepared by Android. When you are in Y thread and you're callingLooper.prepareMainLooper() you're trying to prepare looper in X thread (main thread). This fails because X's looper is laredy prepared. But when you call Looper.prepareLooper() in Y thread, you're actually preparing looper in Y thread and therefore ready to call Looper.loop()

0 件のコメント:

コメントを投稿