如何处理类在Android中工作 [英] How handler classes work in Android

查看:85
本文介绍了如何处理类在Android中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的Andr​​oid和正在读的官方Android网站上的演示应用程序。而我碰到处理程序命名为类postDelayed(Runnable的R,长毫秒)

I am new to android and was reading the demo applications on official android website. And I came across a method of Handler class named as postDelayed(Runnable r, long milliseconds).

有人能解释一下这是什么方法呢?

Can anybody please explain what this method does ?

推荐答案

您可以看到<一href="http://developer.android.com/reference/android/os/Handler.html#postDelayed%28java.lang.Runnable,%20long%29">documentation.

但要明白的文档,你应该先了解几个概念:消息,消息队列,处理程序和活套和他们的<一个href="http://stackoverflow.com/questions/12877944/what-is-the-relationship-between-looper-handler-and-message-queue">relationship.

But to understand the docs, you should first understand several concepts: Message, Message Queue, Handler and Looper, and their relationship.

下面说明活套是如何工作的,这表明了弯是一个线程本地对象及其与MessageQueue的关系:

The following illustrates how Looper works, it shows that the looper is a thread local object and its relationship with MessageQueue:

class Looper{
    public static final void prepare() {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper());
    }

    public static final void loop() {
        Looper me = myLooper();
        MessageQueue queue = me.mQueue;
        while (true) {
            Message msg = queue.next(); // might block
            if (msg != null) {
                if (msg.target == null) {
                    // No target is a magic identifier for the quit message.
                    return;
                }
                msg.target.dispatchMessage(msg);
                msg.recycle();
            }
        }
    }
}

的几点意见:

Several remarks:

尺蠖是一个线程局部对象,使得每个线程有一条环线。每圈结与消息队列关联。活套continously得到messagese(任务,命令或任何你喜欢给他们打电话)从队列中,并分发消息到它的目标,这是一个处理程序来处理messag(例如通过回调包含在一个Runnable该消息)。当没有留在队列中的消息,该线程阻塞,直到有新的消息。要停止活套,你必须调用退出()就可以了(这可能不会立即停止循环,而是设置一个从循环定期检查专用标志,标志着其停止)。

Looper is a thread local object such that every thread has one looper. Every looper is associated with a message queue. The looper continously get messagese("tasks", "commands" or whatever you like to call them) from the queue, and dispatch the message to its target, which is a handler to handle that messag(e.g. by calling back a Runnable contained in the message). When there are no messages left in the queue, the thread blocks until there are new messages. To stop a Looper, you have to call quit() on it (which probably does not stop the loop immediately, but rather sets a private flag that is checked periodically from the loop, signaling the it to stop).

Android框架提供了处理程序类,以简化的东西。当你创建一个处理程序实例,它是绑定到已经连接到当前线程的Looper(默认情况下)。 (该处理器知道什么活套附加到,因为我们叫prepare()早些时候,它存储在参考活套在一个ThreadLocal。)

Android framework provides the Handler class to simplify things. When you create a Handler instance, it is (by default) bound to the Looper already attached to the current thread. (The Handler knows what Looper to attach to because we called prepare() earlier, which stored a reference to the Looper in a ThreadLocal.)

通过一个处理程序,你可以调用后()把消息放入线程的消息队列(这么说)。该处理器将利用所有的IdleHandler回调的东西照顾,并确保您发布的Runnable执行。 (这也可能检查的时间是正确的已经,如果贴有一个延迟。)

With a Handler, you can just call post() to "put a message into the thread's message queue" (so to speak). The Handler will take care of all the IdleHandler callback stuff and make sure your posted Runnable is executed. (It might also check if the time is right already, if you posted with a delay.)

下面code显示了我们使用它们的典型方式。

The following code shows the typical ways we use them.

class LooperThread extends Thread {
  public Handler mHandler;

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

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

      Looper.loop();
  }

}

处理程序被广泛应用于机器人服务。支持Android应用程序间的通信。通常,当我们实现服务,这并不需要处理的多线程,我们实现了接收到来自客户端的每个呼叫的回调处理程序。然后创建一个信使对象(参照处理程序),这是一个活页夹对象,当它们结合该服务此对象返回到客户端。所以客户端可以使用此Messenger来发送消息(进入线程本地队列,发送到处理程序,通过活套)这项服务,并让他们在处理程序处理。 code样本附:

Handler is widely used in Android services. Android support inter application communication. Typically when we implement a service, which doesn't need to handle multithreading, we implements a Handler that receives a callback for each call from a client. Then create a Messenger object (reference to the Handler), which is a Binder object and return this object to clients when they bind this service. So the client can use this Messenger to send messages (into the thread-local queue, send to handler through Looper) to this service, and get them handled in the Handler. Code sample is attached:

public class MessengerService extends Service {
    /** Command to the service to display a message */
    static final int MSG_SAY_HELLO = 1;

    /**
     * Handler of incoming messages from clients.
     */
    class IncomingHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_SAY_HELLO:
                    Toast.makeText(getApplicationContext(), "hello!", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    }


    final Messenger mMessenger = new Messenger(new IncomingHandler());

    @Override
    public IBinder onBind(Intent intent) {
        Toast.makeText(getApplicationContext(), "binding", Toast.LENGTH_SHORT).show();
        return mMessenger.getBinder();
    }
}

这篇关于如何处理类在Android中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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