0

有人可以告诉我什么时候应该在处理程序中使用 Looper 吗?我有一个代码库,其中有多个线程和处理程序。但是Looper.prepare()Looper.loop()没有要求所有这些。

我的疑问是我们是否需要 looper 来持续处理 handleMessage 方法中的消息?即使我们没有looper,当消息发送到处理程序时,不会调用handleMessage()吗?Looper 在这里还有什么额外的用途?

谢谢, 沙米

4

2 回答 2

3

用于为线程运行消息循环的类。默认情况下,线程没有与之关联的消息循环;要创建一个,请在要运行循环的线程中调用 prepare(),然后 loop() 让它处理消息,直到循环停止。

大多数与消息循环的交互都是通过 Handler 类进行的。

下面有一个线程的run方法

@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);
        } 
    }
于 2012-06-05T09:39:32.593 回答
0

Android Looper 是 Android 用户界面中的一个 Java 类,它与 Handler 类一起处理 UI 事件,例如按钮单击、屏幕重绘和方向切换。它们还可用于将内容上传到 HTTP 服务、调整图像大小和执行远程请求。

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

于 2012-06-05T09:44:47.977 回答