Looper的目的是什么以及如何使用它? [英] What is the purpose of Looper and how to use it?

查看:32
本文介绍了Looper的目的是什么以及如何使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Android 新手.我想知道 Looper 类的作用以及如何使用它.我已经阅读了 Android Looper 类文档,但我无法完全理解它.我在很多地方见过它,但无法理解它的用途.任何人都可以通过定义 Looper 的目的并在可能的情况下给出一个简单的例子来帮助我吗?

I am new to Android. I want to know what the Looper class does and also how to use it. I have read the Android Looper class documentation but I am unable to completely understand it. I have seen it in a lot of places but unable to understand its purpose. Can anyone help me by defining the purpose of Looper and also by giving a simple example if possible?

推荐答案

Looper 是什么?

Looper 是一个类,用于执行队列中的消息(Runnables).普通线程没有这样的队列,例如简单线程没有任何队列.执行一次,方法执行完成后,线程不会再运行另一个Message(Runnable).

Looper is a class which is used to execute the Messages(Runnables) in a queue. Normal threads have no such queue, e.g. simple thread does not have any queue. It executes once and after method execution finishes, the thread will not run another Message(Runnable).

我们可以在哪里使用 Looper 类?

如果有人想要执行多条消息(Runnables),那么他应该使用负责在线程中创建队列的 Looper 类.例如,在编写从互联网下载文件的应用程序时,我们可以使用 Looper 类将要下载的文件放入队列中.

If someone wants to execute multiple messages(Runnables) then he should use the Looper class which is responsible for creating a queue in the thread. For example, while writing an application that downloads files from the internet, we can use Looper class to put files to be downloaded in the queue.

它是如何工作的?

prepare() 方法来准备 Looper.然后你可以使用 loop() 方法在当前线程中创建一个消息循环,现在你的 Looper 准备好执行队列中的请求,直到你退出循环.

There is prepare() method to prepare the Looper. Then you can use loop() method to create a message loop in the current thread and now your Looper is ready to execute the requests in the queue until you quit the loop.

这是您可以用来准备 Looper 的代码.

Here is the code by which you can prepare the Looper.

class LooperThread extends Thread {
      public Handler mHandler;

      @Override
      public void run() {
          Looper.prepare();

          mHandler = new Handler() {
              @Override
              public void handleMessage(Message msg) {
                  // process incoming messages here
              }
          };

          Looper.loop();
      }
  }

这篇关于Looper的目的是什么以及如何使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆