How do you use Looper.prepare() and Looper.loop()?

The Looper.prepare() method is used to initialize the Looper object for the current thread, and should be called before using a Handler or MessageQueue for the current thread.

The core method of the Looper class is Looper.loop(), which initiates an infinite loop that continuously retrieves messages from the MessageQueue of the current thread for processing. This method will block the current thread until Looper.quit() is called to stop the loop.

Here is a simple example demonstrating how to use the Looper.prepare() and Looper.loop() methods.

public class MyThread extends Thread {
    public Handler mHandler;

    @Override
    public void run() {
        // 初始化 Looper
        Looper.prepare();

        // 创建 Handler
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                // 处理消息
                // ...
            }
        };

        // 启动循环
        Looper.loop();
    }
}

In the example above, we created a thread class MyThread, called Looper.prepare() in the run() method to initialize the Looper object, and created a Handler object. Then we called Looper.loop() to start the loop.

In a loop, messages can be sent by calling mHandler.sendMessage() and then handled in the handleMessage() method.

It is important to note that the Looper.loop() method will continuously block the current thread, so make sure to call the Looper.quit() method at the appropriate time to stop the loop, otherwise it may cause issues with the thread being unable to exit.

bannerAds