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,
- The Looper in the
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.
- Also in the main method, a handler is responsible for managing a MessageQueue where messages from your app are received and handled. It is important to note a [Messages] can be executed by the MessageQueue as a Runnable or other executable object.
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!