vikas kumar
vikas kumar

Reputation: 11018

Why loop() in Looper class gets called multiple times

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.

enter image description here

the control of execution then shifts to View class and calls performClick() enter image description here

after then it goes to Handler class and calls dispatchMessage(Message msg) enter image description here and at last, it calls loop() of Looper class a number of times before coming back to normal flow. enter image description here 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

Answers (1)

martinomburajr
martinomburajr

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,

  1. 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.
  2. 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!

Upvotes: 2

Related Questions