Android开发

Handler源码分析,不要死记硬背知识点,走一走试试

2017-12-01  本文已影响114人  浪浪许
网上关于Handler源码分析的文章一大把,写的也不错,我写文章不是为了达到什么目的,只是再走一波流程,然后让自己的思维更加清晰,对着源码来一波,学习一下思想,熟悉一下系统源码,而不是去查看别人的文章然后死记硬背知识点,死记硬背的东西还是容易忘记的,就像英语单词一样,额,,,扯远了,开干吧。
Handler一般用于 用于子线程发送消息,主线程更新UI,废话不多说,直接看用法(2步,做你想做),然后查看源码分析它
步骤1 主线程创建一个Handler 复写handleMessage(Message msg)方法,接收子线程发过来的消息,然后做你想做的操作即可。
private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 100:
                    //do something
                    break;
            }
        }
    };

步骤2 子线程创建发送的消息,携带数据
    //创建Message 方式1 new 方式直接创建对象
        Message message = new Message();
        message.obj = "";
        message.what = 100;

        //方式2 通过Handler.obtainMessage方式创建Message,这种方式好一些,可以复用
        //源码注释
      /*Returns a new {@link android.os.Message Message}
      from the global message pool. More efficient than
                * creating and allocating new instances.*/
        Message obtainMessage = mHandler.obtainMessage();
        obtainMessage.obj = "";
        obtainMessage.what = 101;

        mHandler.sendMessage(obtainMessage);
源码分析走起(搞一波)
先从 mHandler.sendMessage(obtainMessage)方法开始看,看里面做了什么操作。
  Handler

   public final boolean sendMessage(Message msg)
    {
        return sendMessageDelayed(msg, 0);
    }
Handler

  public final boolean sendMessageDelayed(Message msg, long delayMillis)
    {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }
Handler

public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
        MessageQueue queue = mQueue;//消息队列,创建Handler的时候源码创      建赋值的,
并且是从Looper里面获取的赋值的,用来存放发送的消息的 是链表结构的(方便断开插入,插入快) 

为什么用队列(先进先出),链表结构 (方便插队)
假设第一条消息发送执行的延时是1秒后执行,
第二条发送的是5秒后执行,
第三条发送的是3秒后执行,那么进入队列肯定需要根据时间排序放入队列的,方便Looper取出执行

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

 private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        //调用了MessageQueue里面里的enqueueMessage,继续,移步到MessageQueue
        return queue.enqueueMessage(msg, uptimeMillis);
    }
    MessageQueue
    //主要是把发送过来的消息按时间顺序加入到消息队列里面
    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;
    }
以上 Handler的发送消息部分的源码基本走完了
接下来是new Handler部分的源码
  Handler 

   public Handler() {//new Handler的Handler构造
        this(null, false);
    }

Handler 

    public Handler(Callback callback, boolean async) {
        if (FIND_POTENTIAL_LEAKS) {
            final Class<? extends Handler> klass = getClass();
            if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
                    (klass.getModifiers() & Modifier.STATIC) == 0) {
                Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
                    klass.getCanonicalName());
            }
        }

        mLooper = Looper.myLooper();//创建获取Looper 用来去MessageQueue里面死循环不断取消息用的
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;//获取消息队列
        mCallback = callback;//Handler 的内部的callBack
        mAsynchronous = async;
    }
Looper

  /**
     * Return the Looper object associated with the current thread.  Returns
     * null if the calling thread is not associated with a Looper.
     */
    public static @Nullable Looper myLooper() {
        return sThreadLocal.get();//获取Looper
    }
  ThreadLoocal

   public T get() {  //map集合获取对应的Looper 后面会讲解在什么地方put进去的
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null)
                return (T)e.value;
        }
        return setInitialValue();
    }
到这里,new Handler部分的源码基本就完了
接下来看复写的Handler的handleMessage(Message msg) 方法源码
 /**
     * Subclasses must implement this to receive messages.
     */
    public void handleMessage(Message msg) {
      //空的,什么操作都没有,注释说必须继承实现 然后用来接收消息
      //麻烦了,没办法往下看了,并没有看到是如何传递消息过来的
      //别着急,看这个方法在哪里被调用了
      //搜索一下,dispatchMessage这里被调用了
    }

   /**
     * Handle system messages here.
     */
    public void dispatchMessage(Message msg) {//分发消息
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            //调用了我们复写的方法,传递了msg过去了
           继续查看dispatchMessage 是哪里调用的,,然后,就发现,找不到
            handleMessage(msg);
        }
    }
到这里new Handler复写handleMessage方法就分析完了,知道是调用dispatchMessage(Message msg) 的时候分发的消息 但是,找不到这个方法是在哪里被调用的,,,那么就要涉及到Activity的启动流程相关知识了。

Activity启动流程之ActivityThread

我们都知道一个程序只有一个入口,Activity也是,它的入口就是ActivityThread 的main方法,来看看源码分析吧
  ActivityThread

  public static void main(String[] args) {
        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
        SamplingProfilerIntegration.start();

        // CloseGuard defaults to true and can be quite spammy.  We
        // disable it here, but selectively enable it later (via
        // StrictMode) on debug builds, but using DropBox, not logs.
        CloseGuard.setEnabled(false);

        Environment.initForCurrentUser();

        // Set the reporter for event logging in libcore
        EventLogger.setReporter(new EventLoggingReporter());

        // Make sure TrustedCertificateStore looks in the right place for CA certificates
        final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
        TrustedCertificateStore.setDefaultUserDirectory(configDir);

        Process.setArgV0("<pre-initialized>");

        Looper.prepareMainLooper();//Looper准备,程序开始运行,Activity通讯,消息基本上都是靠Looper去驱动的

        ActivityThread thread = new ActivityThread();//创建一个主线程
        thread.attach(false);

        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();//创建Activity的Handler
        }

        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }

        // End of event ActivityThreadMain.
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        Looper.loop();//Looper开始循环 取消息

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

     public static void prepareMainLooper() {
        prepare(false);//准备创建Looper
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }
 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));//创建一个Looper 设置给当前线程
    }
  Looper

    public void set(T value) {//用map存储Looper,对应前面的get方法去取Looper
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }
Looper 

 private Looper(boolean quitAllowed) {
        //创建消息队列
        mQueue = new MessageQueue(quitAllowed);  
        //设置当前线程   所以一个消息队列对应一个线程
        mThread = Thread.currentThread();
    }
到这里,创建Looper基本上就完成了,Looper里面有了消息队列,可以通过Handler把消息存储到MessageQueue里面了。
到这里还是没看到调用 dispatchMessage 方法,别着急,马上就来。
ActivityThead

  public static void main(String[] args) {

        ...

        Looper.loop(); //开始循环,看看loop方法做了什么

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

  /**
     * Run the message queue in this thread. Be sure to call
     * {@link #quit()} to end the loop.
     */
    public static void loop() {
        final Looper me = myLooper();//用get方法获取存储在集合中的Looper对象
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        final MessageQueue queue = me.mQueue;//获取Looper的消息队列

        // 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 (;;) {//关键代码   死循环  不断的去MessageQueue里面获取消息
            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 {
                //取到消息就调用target的dispatchMessage 方法,而这个target正式Handler对象  下面接着分析源码
                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();//移除消息 具体看源码,就是判断消息是否为空,然后对消息进行回收,置为空
        }
    }
  Message
    /*package*/ Handler target;//Message里面的target就是Handler

 /** Constructor (but the preferred way to get a Message is to call {@link #obtain() Message.obtain()}).
    */
    //这里也强调了,创建消息的方法首选obtain方式
    public Message() {
    }

//接着看target是在哪里赋值的

Handler 

  private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;//在这里给msg的target赋值的,赋的值是Handler 
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

到这里,Handler整个执行的流程就基本分析完了,最好亲自看一下源码,跟着代码走一遍,才会记得更加清晰,理解起来才会容易一些。
上一篇下一篇

猜你喜欢

热点阅读