Handler在Android中的主要作用是解决跨线程通信的问题.
它的实现需要以下三个类一起完成Message(消息载体),MessageQueue
(消息队列)以及Looper

以下我们从常用的sendEmptyMessage方法开始分析它的实现流程.

 public final boolean sendEmptyMessage(int what)    {        return sendEmptyMessageDelayed(what, 0);    }

最终会调到如下方法

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

其中uptimeMillis是消息需要处理的绝对时间,是基于SystemClock.uptimeMillis()这个时间来计算的。

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {        msg.target = this;        if (mAsynchronous) {            msg.setAsynchronous(true);        }        return queue.enqueueMessage(msg, uptimeMillis);    }

其中mAsynchronous这个参数只能通过构造Handler对象是传入,默认是false.

接着我们进入MessageQueue的enqueueMessage方法

 boolean enqueueMessage(Message msg, long when) {        if (msg.target == null) {            throw new IllegalArgumentException("Message must have a target.");        }        if (msg.isInUse()) {            throw new IllegalStateException(msg + " This message is already in use.");        }        synchronized (this) {            if (mQuitting) {                IllegalStateException e = new IllegalStateException(                        msg.target + " sending message to a Handler on a dead thread");                Log.w(TAG, e.getMessage(), e);                msg.recycle();                return false;            }            msg.markInUse();            msg.when = when;            Message p = mMessages;            boolean needWake;            if (p == null || when == 0 || when < p.when) {                // New head, wake up the event queue if blocked.                msg.next = p;                mMessages = msg;                needWake = mBlocked;            } else {                // Inserted within the middle of the queue.  Usually we don't have to wake                // up the event queue unless there is a barrier at the head of the queue                // and the message is the earliest asynchronous message in the queue.                needWake = mBlocked && p.target == null && msg.isAsynchronous();                Message prev;                for (;;) {                    prev = p;                    p = p.next;                    if (p == null || when < p.when) {                        break;                    }                    if (needWake && p.isAsynchronous()) {                        needWake = false;                    }                }                msg.next = p; // invariant: p == prev.next                prev.next = msg;            }            // We can assume mPtr != 0 because mQuitting is false.            if (needWake) {                nativeWake(mPtr);            }        }        return true;    }

这个方法主要做了如下工作:
1,如果消息队列正在退出,就主动抛出IllegalStateException这个异常,并且回收即将被添加进入队列的消息对象;
2,将新加入的消息按照指定规则排序;

消息的正常发送流程,也就是将消息加入到消息队列中的流程到此就分析结束了。接下来我们分析取消息流程。

我们知道系统在APP启动的时候会默认的创建主线程的Looper即Looper.getMainLooper()对象,这个是在ActivityThread中创建的,代码如下

 public static void main(String[] args) {        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");        SamplingProfilerIntegration.start();        ........        Process.setArgV0("");        Looper.prepareMainLooper();        ActivityThread thread = new ActivityThread();        thread.attach(false);        if (sMainThreadHandler == null) {            sMainThreadHandler = thread.getHandler();        }        if (false) {            Looper.myLooper().setMessageLogging(new                    LogPrinter(Log.DEBUG, "ActivityThread"));        }        // End of event ActivityThreadMain.        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);        Looper.loop();        throw new RuntimeException("Main thread loop unexpectedly exited");    }

通过代码我们知道消息循环的开启是通过Looper.loop();方法来启动的,我们进入Looper的loop方法

public static void loop() {        final Looper me = myLooper();        if (me == null) {            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");        }        final MessageQueue queue = me.mQueue;        // Make sure the identity of this thread is that of the local process,        // and keep track of what that identity token actually is.        Binder.clearCallingIdentity();        final long ident = Binder.clearCallingIdentity();        for (;;) {            Message msg = queue.next(); // might block            if (msg == null) {                // No message indicates that the message queue is quitting.                return;            }            // This must be in a local variable, in case a UI event sets the logger            final Printer logging = me.mLogging;            if (logging != null) {                logging.println(">>>>> Dispatching to " + msg.target + " " +                        msg.callback + ": " + msg.what);            }            final long traceTag = me.mTraceTag;            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));            }            try {                msg.target.dispatchMessage(msg);            } finally {                if (traceTag != 0) {                    Trace.traceEnd(traceTag);                }            }            if (logging != null) {                logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);            }            // Make sure that during the course of dispatching the            // identity of the thread wasn't corrupted.            final long newIdent = Binder.clearCallingIdentity();            if (ident != newIdent) {                Log.wtf(TAG, "Thread identity changed from 0x"                        + Long.toHexString(ident) + " to 0x"                        + Long.toHexString(newIdent) + " while dispatching to "                        + msg.target.getClass().getName() + " "                        + msg.callback + " what=" + msg.what);            }            msg.recycleUnchecked();        }    }

这里面主要做了如下工作;
1,通过ThreadLocal获取当前线程的Looper对象;
2,通过调用 MessageQueue的next()这个方法获取消息队列的下一条消息,
如果有就执行msg.target.dispatchMessage(msg);即Handler中的dispatchMessage方法,这个方法会优先执行Message的callback方法,
如果Message的callback回调为空,再如果Handler的callback不为null,就调用Handler的Callback的handlerMessage方法,如果返回为false就调用Handler的handlerMessage方法,否则就直接返回;
3,回收处理完毕后的Message消息对象;

这其中主要的地方就是MessageQueue的next()方法,接下来我们看看是怎么去消息队列中去下一条消息的

 Message next() {        // Return here if the message loop has already quit and been disposed.        // This can happen if the application tries to restart a looper after quit        // which is not supported.        final long ptr = mPtr;        if (ptr == 0) {            return null;        }        int pendingIdleHandlerCount = -1; // -1 only during first iteration        int nextPollTimeoutMillis = 0;        for (;;) {            if (nextPollTimeoutMillis != 0) {                Binder.flushPendingCommands();            }            //            nativePollOnce(ptr, nextPollTimeoutMillis);            synchronized (this) {                // Try to retrieve the next message.  Return if found.                final long now = SystemClock.uptimeMillis();                Message prevMsg = null;                Message msg = mMessages;//如果开启了同步障碍消息,就不停的循环直到找到异步消息为止                if (msg != null && msg.target == null) {                    // Stalled by a barrier.  Find the next asynchronous message in the queue.                    do {                        prevMsg = msg;                        msg = msg.next;                    } while (msg != null && !msg.isAsynchronous());                }                if (msg != null) {//如果最近的一条消息没有达到执行时间,就计算出还需要执行任务的剩余时间                    if (now < msg.when) {                        // Next message is not ready.  Set a timeout to wake up when it is ready.                        nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);                    } else {                    //否则将消息指定为mMessage并且将其标致为正在使用状态                        // Got a message.                        mBlocked = false;                        if (prevMsg != null) {                            prevMsg.next = msg.next;                        } else {                            mMessages = msg.next;                        }                        msg.next = null;                        if (DEBUG) Log.v(TAG, "Returning message: " + msg);                        msg.markInUse();                        return msg;                    }                } else {                    // No more messages.                    //                    nextPollTimeoutMillis = -1;                }                // Process the quit message now that all pending messages have been handled.                if (mQuitting) {                    dispose();                    return null;                }                // If first time idle, then get the number of idlers to run.                // Idle handles only run if the queue is empty or if the first message                // in the queue (possibly a barrier) is due to be handled in the future.                if (pendingIdleHandlerCount < 0                        && (mMessages == null || now < mMessages.when)) {                    pendingIdleHandlerCount = mIdleHandlers.size();                }                if (pendingIdleHandlerCount <= 0) {                    // No idle handlers to run.  Loop and wait some more.                    mBlocked = true;                    continue;                }                if (mPendingIdleHandlers == null) {                    mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];                }                mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);            }            // Run the idle handlers.            // We only ever reach this code block during the first iteration.            //执行闲时任务            for (int i = 0; i < pendingIdleHandlerCount; i++) {                final IdleHandler idler = mPendingIdleHandlers[i];                mPendingIdleHandlers[i] = null; // release the reference to the handler                boolean keep = false;                try {                    keep = idler.queueIdle();                } catch (Throwable t) {                    Log.wtf(TAG, "IdleHandler threw exception", t);                }                if (!keep) {                    synchronized (this) {                        mIdleHandlers.remove(idler);                    }                }            }            // Reset the idle handler count to 0 so we do not run them again.            pendingIdleHandlerCount = 0;            // While calling an idle handler, a new message could have been delivered            // so go back and look again for a pending message without waiting.            nextPollTimeoutMillis = 0;        }    }

取下一条消息的流程大致如下:
1,判断如果C++层消息队列对象分配的内存已经被释放了,就返回null;
2,执行linux的epoll休眠;
3,如果发现有消息不为null并且它的target为null(Handler的同步障碍),就循环遍历直到找到有消息不为null并且是异步的时候就终止循环;
4,如果说最近要执行任务的消息时间还未到就延迟时间差值,否则返回当前查找到的消息对象;
5,如果消息队列正在退出获取已经退出就主动释放资源并且返回null;
6,如果消息列表为空或者需要执行的消息的时间还未到就执行闲时消息;

至此Handler的消息处理机制就分析完成了;

上面涉及到的
1,Handler的闲时任务,使用方法是通过MessageQueue的addIdleHandler方法来添加,如果queueIdle()这个方法返回false,在闲时任务执行完成之后系统会自动移除该闲时任务,否则系统不会主动移除闲时任务;

2,Handler的同步障碍,它实现效果是如果添加同步障碍,在这之后执行的消息会暂停执行,直到显示调用移除同步障碍方法为止.添加同步障碍的方法为MessageQueue.postSyncBarrier()方法,该方法返回值为int(token),移除同步障碍的方法为MessageQeue.removeSyncBarrier(int token) 方法,该token参数即时postSyncBarrier方法的返回值;

更多相关文章

  1. Android消息机制
  2. eclipse 开发 android 快捷键!
  3. Android监听来电和去电的实现方法
  4. Android(安卓)JsBridge 源码解析
  5. Android(安卓)中文 API (22) ―― MultiAutoCompleteTextView
  6. Mapbox Android学习笔记(1)简介
  7. Android(安卓)中 ListView Adapter getView 被多次调用问题 解决
  8. 浅谈Java中Collections.sort对List排序的两种方法
  9. Python list sort方法的具体使用

随机推荐

  1. Ubuntu 及windows 环境下android(Launcher
  2. How to start a new process for Android
  3. Android Camera HAL浅析
  4. Android Neon 优化方式讲解
  5. android 对话框集合
  6. Android:从Eclipse到Android Studio迁移工
  7. Android AutoCompleteTextView示例教程
  8. android jni系列教程
  9. Android(安卓)6.0 Launcher3隐藏小部件与
  10. android 计算器(2)