Handler工作原理
Posted coconna
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Handler工作原理相关的知识,希望对你有一定的参考价值。
Handler是消息机制的面板类,我们通过Handler.send或者post消息然后在handleMessage()中去处理消息.
发送消息
public final boolean sendMessage(Message msg) { return sendMessageDelayed(msg, 0); } public final boolean sendMessageDelayed(Message msg, long delayMillis) { if (delayMillis < 0) { delayMillis = 0; } return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis); } public boolean sendMessageAtTime(Message msg, long uptimeMillis) { MessageQueue queue = mQueue; if (queue == null) { RuntimeException e = new RuntimeException( this + " sendMessageAtTime() called with no mQueue"); Log.w("Looper", e.getMessage(), e); return false; } return enqueueMessage(queue, msg, uptimeMillis); } private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) { msg.target = this; if (mAsynchronous) { msg.setAsynchronous(true); } return queue.enqueueMessage(msg, uptimeMillis); }
sendMessage操作都只是对Message做了一个入队的操作.Looper无限循环从MessageQueue中取出Message然后调用Handler的dispatchMessage来处理消息
处理消息
public void dispatchMessage(Message msg) { if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); } }
msg的callback是一个Runnable,handlecallback(msg)就是调用了Runnable的run方法.
callable接口
第五行的mCallback是一个接口,定义如下
/** * Callback interface you can use when instantiating a Handler to avoid * having to implement your own subclass of Handler. */ public interface Callback { /** * @param msg A {@link android.os.Message Message} object * @return True if no further handling is desired */ public boolean handleMessage(Message msg); }
可以通过Handler handler = new Handler(new CallBack(){})来使用,作用就是避免创建Handler的子类.
以上是关于Handler工作原理的主要内容,如果未能解决你的问题,请参考以下文章
Handler类和Handler,Loop,MessageQueue的工作原理
Handler类和Handler,Loop,MessageQueue的工作原理
Handler类和Handler,Loop,MessageQueue的工作原理