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

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

问题描述

我是新来的Andr​​oid。我想知道是什么尺蠖类做以及如何使用它。我已经阅读了Android 尺蠖类文档但我不能完全理解它。 我已经看到它在很多地方,但无法理解它的目的。谁能帮我定义的目的尺蠖,并给予一个简单的例子,如果可能的话?

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?

推荐答案

什么是活套?

卢珀是它用于在队列中执行的消息(的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).

在这里我们可以用尺蠖类?

如果有人想执行多个消息(的Runnable)那么他应该使用它负责在线程创建队列的活套类。 例如,在写这从互联网上下载文件的应用程序,我们可以用尺蠖类来把文件放入队列中进行下载。

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()方法prepare的活套。然后你可以使用循环()方法在当前线程创建一个消息循环,现在你的活套已准备好执行的请求队列中直到退出循环。

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.

下面是code,通过它可以prepare的活套。

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

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

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