Android 开发技术交流Android开发进阶Android知识

Handler源码分析

2017-05-07  本文已影响426人  草丛伦

关于线程之间发送消息,有很多种方法,如RunonUiThread,handler的post方法,AsyncTask ,view的post方法等等。大部分场景,都是可以通过handler传递一个message来实现的,现在我们具体看一下它是如何实现的。
这方面,其实涉及到Looper,Handler,MessageQueue.
我们如果在主线程去使用一个handler的话,只需要简单的创建一个handler对象就可以了,并且做好防止内存泄漏的准备。

//这么写是没有注意内存泄漏的哦 只是为了方便这么写
    private  Handler handler = new Handler(Looper.myLooper()){
        @Override
        public void dispatchMessage(Message msg) {
            // todo
        }
    };

之后,只需要在你想要发送信息的地方,调用handler的方法就可以了,post或者sendMessage都可以,本质上都是发送一个message,另外它自身维持了一个message池,所以用Message.obtain()获取一个message比new一个message来的更为合适一点。

//所谓的post了一个runnable过去,源码中也是从message池中拿到一个message,让这个runnable对象跟他的callback绑定而已,
//所以本质上跟sendMessage没两样,不过优先级还是这个callback更加高一点哦。     
mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                  //
                }
            }, 0);

在主线程中创建handler是如此的简单,是因为ActivityThread中已经默认为我们调用了Looper的相关方法:

   public static void main(String[] args) {
        //去除无关代码

        Looper.prepareMainLooper();//在这里 调用了prepare方法

        ActivityThread thread = new ActivityThread();
        thread.attach(false);

        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }

        Looper.loop(); //在这里 调用了loop方法 ,让messagequene开始无限循环

        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

抽取关键代码,即源码中为我们展示的demo:

  *  class LooperThread extends Thread {
  *      public Handler mHandler;
  *
  *      public void run() {
  *          Looper.prepare();
  *
  *          mHandler = new Handler() {
  *              public void handleMessage(Message msg) {
  *                  // process incoming messages here
  *              }
  *          };
  *
  *          Looper.loop();
  *      }

查看源代码,看看他们究竟做了什么?

   public static void prepare() {
        prepare(true);
    }
//ThreadLocal可以先简单的认为是一种工具类,我们发现,prepare每个线程只能调用一次,再次调用直接跑出异常
//如果第一次调用,那么将创建一个Looper对象,
    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));
    }

而Looper的构造方法中 会创建一个messageQuene。

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

这就是prepare方法的所有作用,在当前线程中创建一个与之绑定的Looper,Looper中创建一个messagequeue,也与之绑定。
再看handler的构造方法:

public Handler(Callback callback, boolean async) {
      
//他会做判断,判断当前的looper是否存在,不存在直接抛出异常,
//所以在子线程创建handler的话,必须调用prepare方法,因为他不会默认为我们调用这个方法。
//如果looper已经被创建,他会将looper和messagequeue与自身绑定。
        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

接着看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;
            }
            final long traceTag = me.mTraceTag;
            if (traceTag != 0) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            try {
                msg.target.dispatchMessage(msg);
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }

            // Make sure that during the course of dispatching the
            // identity of the thread wasn't corrupted.
            final long newIdent = Binder.clearCallingIdentity();
            msg.recycleUnchecked();
        }
    }

说重点,就是开始对messagequeue做无限循环,从队列当中拿出message,这个queue.next涉及到native的一些方法,并不是简单的直接拿下一个message,他必定能拿到一个next,它会判断message里面when属性去判断是否需要阻塞一下,当拿出来后,通过它的target,也就是handler,调用他的dispatchMessage方法,这个方法源代码中是空实现,所以一般需要我们去实现。那么如果队列当中不存在message了,那么他将会阻塞,直到有消息被放到队列中,再次开启以下循环。
我们来看一下next方法:

  Message next() {
        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;
        }
    }

nativePollOnce是个native方法,他根据传入的nextPollTimeoutMillis ,去判断要阻塞的时间,第一次传入0,所以一定不会阻塞,之后通过message的next方法,去拿到最远端的一个next,然后根据他的msg.when去判断需要阻塞的时间,在当前阻塞等待的时候,还需要去判断IdleHandler是否为空,不为空的话处理一下。当然,如果nextPollTimeoutMillis 为-1的情况下表示一直睡眠,直到有人唤醒。

最后我们看一下post方法,不管是post还是postdelay还是sendmessage什么的,最后都是调用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);
    }


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

重点就在enqueueMessage方法中,它将msg放入到队列中

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

mMessages其实代表消息队列的头部,如果mMessages为空,说明还没有消息,如果当前插入的消息不需要延时,或者说延时比mMessages头消息的延时要小,那么当前要插入的消息就需要放在头部,如果不是,则开始循环判断当前的这个msg要插入的位置,插入进去,最后判断是否需要唤醒Loop线程,通过nativeWake唤醒。

总结:
创建Looper,Looper当中创建MessageQueue,接着可以创建Handler对象,再调用loop方法让队列开始无限循环。之后通过handler的方法,将需要发送的msg放置到messagequeue当中,它会根据他的target属性找到对应的handler,执行dispatchMessage方法,他会判断是调用msg的callback方法还是执行handlermessage方法,如此消费一个msg。

参考:
http://blog.csdn.net/guolin_blog/article/details/9991569?utm_source=tuicool&utm_medium=referral
https://juejin.im/post/59083d7fda2f60005d14efdb

上一篇下一篇

猜你喜欢

热点阅读