0

Can someone please tell me when we should use Looper in Handlers? I have a codebase in which there are multiple threads and handlers. But Looper.prepare() and Looper.loop() is not called for all of them.

My doubt is do we need looper to continously process messages in the handleMessage method? Even if we do not have looper, won't handleMessage() be called when a message is sent to the handler? What additional purpose is Looper serving here?

Thanks, Shamy

Shamy
  • 379
  • 3
  • 15

2 Answers2

3

Class used to run a message loop for a thread. Threads by default do not have a message loop associated with them; to create one, call prepare() in the thread that is to run the loop, and then loop() to have it process messages until the loop is stopped.

Most interaction with a message loop is through the Handler class.

Below there is a run method of thread

@Override
    public void run() {
        try {
            // preparing a looper on current thread         
            // the current thread is being detected implicitly
            Looper.prepare();

            Log.i(TAG, "DownloadThread entering the loop");

            // now, the handler will automatically bind to the
            // Looper that is attached to the current thread
            // You don't need to specify the Looper explicitly
            handler = new Handler();

            // After the following line the thread will start
            // running the message loop and will not normally
            // exit the loop unless a problem happens or you
            // quit() the looper (see below)
            Looper.loop();

            Log.i(TAG, "DownloadThread exiting gracefully");
        } catch (Throwable t) {
            Log.e(TAG, "DownloadThread halted due to an error", t);
        } 
    }
jeet.chanchawat
  • 5,842
  • 5
  • 38
  • 59
0

Android Looper is a Java class within the Android user interface that together with the Handler class to process UI events such as button clicks, screen redraws and orientation switches. They may also be used to upload content to an HTTP service, resize images and execute remote requests.

http://developer.android.com/reference/android/os/Looper.html

Abhinai
  • 1,082
  • 2
  • 13
  • 20