您的位置:首页 > 移动开发 > Android开发

Handler笔记

2016-06-30 15:08 351 查看
1 client通过sendMessage将message,提交给messageQueue,

2 messageQueue通过when顺序对message进行排序(链表)

3 Looper通过for循环机制不停的从messageQueue中获取message,并且通过Handler的dispatchMessage方法将message分发给client

4 其中1-3部分循环在具体的Thread中。

当client为一个Activity时,Thread则为该Activity的UI线程(主线程)

查看Activit源码可知,在该线程中已实现Looper.prepare()和Looper.loop(),因此不需要在创建Handler时额外增加Looper.prepare()和Looper.loop()

而在自己创建的Thread线程中则需要使用Looper.prepare()和Looper.loop()包裹new Handler

那为啥要使用Looper.prepare()和Looper.loop()包裹new Handler呢?

下面是源码,通过源码分析下:

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

}

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

        }

}

其中这里面用到了这个static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

sThreadLocal是一个static and final的对象。

if (sThreadLocal.get() != null) {

            throw new RuntimeException("Only one Looper may be created per thread");

}

我们看这段话,get()如果不为空,就抛出一个异常,这里就产生了一个疑问?

作为一个静态的变量sThreadLocal在每次执行prepare()方法时都会去set(),那get()方法岂不是只要执行过一次set()就会报错嘛?

查了下相关资料,线程本地存储功能的封装???不是很清楚,大概意思就是每个Thread独有一个Looper,线程间的Looper并不会相互影响。这里其实也是为什么一个Thread只能有一个Looper了。可以把它看着一个Thread的变量,如果有两个Looper就重名了。

然后接着看Looper.loop(),

private Looper(boolean quitAllowed) {

        mQueue = new MessageQueue(quitAllowed);

        mThread = Thread.currentThread();

}

myLooper()其实就是获取prepare()时创建的创建的Looper对象,

final MessageQueue queue = me.mQueue;获取消息队列,然后其实就是for (;;) {进行死循环去读消息队列的过程,

那什么时候退出这个循环呢? 我们看下这个for循环,

Message msg = queue.next(); // might block

if (msg == null) {

        // No message indicates that the message queue is quitting.

        return;

}

当取出下一个msg的时候,这个msg==null时,就退出循环了。

那这个时候问题就来了,我们一般都是事先写好loop(),然后再通过Handler的sendMessage去发送消息,加入消息队列,那这里一开始就退出循环了,怎么从队列中获取消息,然后分发出去呢?难道尤其他的地方执行分发工作?

我们再看看Looper这个类,好像也没有其他地方做分发工作了,那到底是怎么回事呢?

那要怎么解决退出这个问题?queue.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 {

                        // 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;

        }

}

这里面明显会返回为空的地方是这一句:

// Process the quit message now that all pending messages have been handled.

                if (mQuitting) {

                    dispose();

                    return null;

}

但是我们发现这个是mQuitting=true的是否才执行,也就是说这是一个正常退出的机制!所以这里不是。

那好,那我们就必须研究下这个队列回不回返回为空?当然了这里面基本上都是Java层的代码,然后有这么一句它是调用了nativePollOnce C++的代码?

这个是干嘛用的呢????

假设我们现在队列里面没有message,也不去管nativePollOnce这个方法,我们试着走走这个流程!

一开始mMessages=null,所以else分支// No more messages. nextPollTimeoutMillis = -1;,然后继续往下走:

我们能够发现一个有趣的现象:下面没有return和blank了,这说明,除了正常退出的情况或者返回一个不为空的message之外,程序将一直在这个死循环里面执行,恩,问题解决了。

这也解释了为什么,loop()方法后的程序会不被执行,因为loop()是个死循环,只有退出这个循环后loop()后的方法才会被执行!

那nativePollOnce到底是什么呢?我也不清楚,在查查资料再说。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android handler