Android实现机制分析(一)——消息机制

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zpf8861/article/details/52058943

Android是消息驱动的,我们经常遇到属于消息机制的名字包括Handler、Looper、MessageQueue和Message。
- 载体:Message
- 队列:MessageQueue
- 调度:Looper
- 处理:Handler

其中在应用开发中,Handler和Message是我们经常用到的,而Looper偶尔会用到,MessageQueue则基本不会见到了,这是因为Android为用户封装的很好,可以最大程度的封装。
Android的消息机制是不同线程通信的关键,内部实现不局限于Java层,还通过JNI调用了Native的方法。
下面将按照消息机制顺序流程依次介绍几个关键流程。

消息队列的初始化

在Android中消息队列需要被消息循环所调度,也就是Looper,在一个线程中必须有一Looper实例,才能调度消息队列,如下代码:

public void run() {
    mTid = Process.myTid();
    Looper.prepare();
    synchronized (this) {
        mLooper = Looper.myLooper();
        notifyAll();
    }
    Process.setThreadPriority(mPriority);
    onLooperPrepared();
    Looper.loop();
    mTid = -1;
}

这是HandlerThread中的一段代码,其中Looper.prepare();就是在初始化消息队列和Looper,然后Looper就可以接管这个线程的消息队列。

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

quitAllowed默认为true,表示不能从消息循环中quit。sThreadLocal.set(new Looper(quitAllowed));会实例一个Looper加入到TreadLocal中。

UI线程默认有一个Looper,它的quitAllowed为不可退出,说明主线程是不能被quit的。

private Looper(boolean quitAllowed) {   
       mQueue = new MessageQueue(quitAllowed);    
       mThread = Thread.currentThread();
}

构造方法主要是实例化了一个消息队列MessageQueue,再看一下MessageQueue的构造方法。

MessageQueue(boolean quitAllowed) {
    mQuitAllowed = quitAllowed;
    nativeInit();
}

这个时候看到一个方法,nativeInit()看名字像是一个Native方法,进去一看果然是。Native方法这里就不具体说了,但是从代码来看,在Native方法中也有一套MessageQueue和Looper的机制,

总结

消息队列初始化首先通过Looper.prepare();,实例化了Looper类,Looper类又实例化了MessageQueue,而实例化MessageQueue的时候调用了Native方法中单消息机制,也就是说,Android的消息机制不仅有java层实现,还用到了Native内核层的实现。

发送消息

Looper.prepare();初始化之后,就可以通过Looper.loop();进入消息循环了。
首先要看一下一个消息是怎么添加到消息队列中的。
上面介绍了消息的载体是Message类,因此需要获得一个消息对象,通常我们用Message.obtain()来获得一个实例,而不是直接new一个Message对象,这是因为在队列池里的Message对象可以复用,从而避免不必要的开销。

public static Message obtain() {
        synchronized (sPoolSync) {
            if (sPool != null) {
                Message m = sPool;
                sPool = m.next;
                m.next = null;
                sPoolSize--;
                return m;
            }
        }
        return new Message();
}

Message内部维护了一个缓存链表,可以将存在的Message返回给上层。

有了Message对象后,发送消息在应用开发中就经常用到了,比如Handler的各种post、send方法,查看源码,都是调用了sendMessageAtTime方法,如下:

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

通过这个方法获取到消息后,在调用enqueueMessage方法插入这条消息,我们看MessageQueue queue = mQueue;这个队列是获取的当前线程的消息队列。

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

插入消息的时候,首先会将Message的target设置为当前的Handler,然后调用MessageQueue的enqueueMessage,

final boolean enqueueMessage(Message msg, long when) {
        if (msg.isInUse()) {
            throw new AndroidRuntimeException(msg + " This message is already in use.");
        }
        if (msg.target == null) {
            throw new AndroidRuntimeException("Message must have a target.");
        }

        boolean needWake;
        synchronized (this) {
            if (mQuiting) {
                RuntimeException e = new RuntimeException(
                        msg.target + " sending message to a Handler on a dead thread");
                Log.w("MessageQueue", e.getMessage(), e);
                return false;
            }

            msg.when = when;
            Message p = mMessages;
            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;
            }
        }
        if (needWake) {
            nativeWake(mPtr);
        }
        return true;
    }

当msg.target为null时是直接抛异常的。在enqueueMessage中首先判断,如果当前的消息队列为空,或者新添加的消息的执行时间when是0,或者新添加的消息的执行时间比消息队列头的消息的执行时间还早,就把消息添加到消息队列头(消息队列按时间排序),否则就要找到合适的位置将当前消息添加到消息队列。

消息循环

有了消息队列,也发送了消息,下面就是要知道如何通过循环消息队列去处理消息了。首先看一下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
            Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }

            msg.target.dispatchMessage(msg);

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

Looper循环过程会依次取到队列的Message,调用msg.target.dispatchMessage(msg)方法交由Handler处理,而这个target就是在插入消息是被绑定的那个发消息的Handler,消息被处理之后会被回收,当next为null时就会退出循环,这样整个一个完整的流程就结束了,当然读取消息的过程也是很复杂的,而且用到了native方法,这里就不深入描述了。

猜你喜欢

转载自blog.csdn.net/zpf8861/article/details/52058943