Handler的sendEmptyMessageDelay()和sendEmptyMessage()的区别

Android 2018-01-19

基础

  • Handler:作用就是发送与处理信息,如果希望Handler正常工作,在当前线程中要有一个Looper对象
  • Message:Handler接收与处理的消息对象
  • MessageQueue:消息队列,先进先出管理Message,在初始化Looper对象时会创建一个与之关联的MessageQueue;
  • Looper:每个线程只能够有一个Looper,管理MessageQueue,不断地从中取出Message分发给对应的Handler处理!

  • sendEmptyMessageDelayed(int what,long delayMillis):指定延时多少毫秒后发送空信息

  • sendMessageDelayed(Message msg):指定延时多少毫秒后发送信息

两者都是android.os.Handler下的方法

public final boolean sendEmptyMessageDelayed(int what,long delayMillis)

Sends a Message containing only the what value, to be delivered after the specified amount of time elapses.

Returns:

Returns true if the message was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting.

sendEmptyMessageDelayed源码:

public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
        Message msg = Message.obtain();
        msg.what = what;
        return sendMessageDelayed(msg, delayMillis);
    }

其实是调用了sendMessageDelayed方法

sendMessageDelayed方法

public final boolean sendMessageDelayed(Message msg,long delayMillis)

Enqueue a message into the message queue after all pending messages before (current time + delayMillis). You will receive it in handleMessage, in the thread attached to this handler.

Returns:

Returns true if the message was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting. Note that a result of true does not mean the message will be processed -- if the looper is quit before the delivery time of the message occurs then the message will be dropped.

注意:

post方法中内部其实调用的也是sendMessageDelayed方法

public final boolean post(Runnable r)
    {
       return  sendMessageDelayed(getPostMessage(r), 0);
    }

参考:
http://blog.csdn.net/yingpaixiaochuan/article/details/50802752


本文由 方方無 创作,采用 知识共享署名 3.0,可自由转载、引用,但需署名作者且注明文章出处。

还不快抢沙发

添加新评论

shijiebei 365bet manbetx 188bet xinshui caipiao 95zz tongbaoyule beplay 88bifa 18luck betway bwin hg0088 aomenjinshayulecheng ca88 shenbotaiyangcheng vwin w88 weide