简体   繁体   中英

When should we use Looper in Android?

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

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);
        } 
    }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM