Reputation: 11018
I have a simple piece of code which starts an intent but when I debug it passes through various classes and often makes me wonder why these classes get called every time and what tasks are they performing before coming back to normal execution.
the control of execution then shifts to View class and calls performClick()
after then it goes to Handler class and calls dispatchMessage(Message msg)
and at last, it calls
loop()
of Looper class a number of times before coming back to normal flow.
so can someone help me here understand what is happening under the hood and why this loop() gets called multiple times?
Upvotes: 0
Views: 712
Reputation: 1265
The loop()
is part of the Looper
class. Deep in your android app when your process initializes the application, the first thing the JVM looks for is an entry point, which in all Java applications is the main method. The android main method exists in a class called ActivityThread
(check the AOSP for the activity thread).
The beauty of this class is that it does a few things,
ActivityThread
's main method calls the prepareMainLooper()
method. This. initializes the current thread as the application's main looper. i.e this is where your main thread receives its mainthread designation, that differs it from all other threads at runtime. What makes android different than most desktop/console like java applications is the Looper class. This class has a Looper.loop()
method that is called within the ActivityThread
's main method, and it runs an infinite loop thanks to a for(;;){}
(the double semicolon indicates infinite loop). This loop will continue to run indefinitely as unless the quit()
is called externally. The loop method calls message.next()
each time it has completed with a message, to retrieve a new message.
In short, without this infinite looping method, it would be difficult for android to have a basic way to process incoming messages asynchronously, which is at the core of Android's event driven nature. The loop is eagerly seeking new messages to process or pass to the handler.
Checkout the AOSP for a deeper dive if you're interested!
Upvotes: 2