Handler源码分析,带你轻松入门

Handler使用简答,功能强大,我们主要用他来做线程之间的通信,也可以用来更新UI界面等。

Handler是什么?

Handler是Android SDK中处理异步类消息的核心类,它的作用就是让子线程通过Handler机制与UI通信来更新UI界面

为什么会有Handler?

在线程中,主线程用于更新UI,而子线程又不能进行耗时操作,所有,就有了Handler,Handler可以在主线程和子线程之间传递信息,从而达到想要的效果

Handler怎么用?

步骤1
主线程创建一个Handler复写handlerMessage(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);

Handler源码分析

首先介绍一下主要用到的几个类
Handler,looper,Message,MessageQueue。
Handler:消息操作类,handler起到了处理消息的作用(只处理自己发出的消息),主要功能就是把消息Message添加到MessageQueue里,处理Looper发送过来的Message。
Looper:Looper是每个线程中的MessageQueue管家,调用Looper的loop()方法后,就会进入到一个无线循环中,然后每当发现MessageQueue中存在一条消息,就会把它取出来,并传递给Handler的HandlerMessage()方法中。每个线程只有一个Loope对象。
Message:Message是在线程之间传递消息,它可以在内部携带少量的信息,用于在不同线程之间交换数据。
MessageQueue:MessageQueue是消息队列的意思,它主要用于存放所有Handler发发送的消息,这个部分消息会一直存在于消息队列中,等待被处理,每个线程中只有一个MessageQueue对象。

简单流程为
当一个应用启动时,会初始化一个UI线程,UI线程中又初始化了Looper,创建Looper的时候又创建了MessageQueue。当Handler把Message发送到MessageQueue里,然后Looper循环的取出发给Handler。由Handler处理这个信息。

这里我是先贴源码再说意思,fear你不看源码
Handler构造方法
Handler.java

public Handler() {    
        this(null, false);
      }
      public Handler(Callback callback, boolean async) {
        if (FIND_POTENTIAL_LEAKS) {
            final Class 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();
        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;
    }

上面代码比较简单,主要就是Handler的构造方法,你会发现刚进来是上面第一个构造方法,它调用的是下面这个构造方法,接下来把第二个构造方法分开详解

  if (FIND_POTENTIAL_LEAKS) {
            final Class 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();
if (mLooper == null) {
            throw new RuntimeException(
                    "Can't create handler inside thread that has not called Looper.prepare()");
        }

判断当前线程的Looper是否为空,如果为空就抛出异常。

mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;

完成了对Looper的检验后,Handler就获取了当前线程mLooper.mQueue的引用。同时包含一个可有可无的callback和是否同步的标志位。

sendMessage
Handler.java

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


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

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

所有的sendMessage发送消息方法最终都会调用下面这个方法

enqueueMessage(queue, msg, uptimeMillis);

这个方法的三个参数分别mLooper.mQueue(当前线程的消息队列)、将要send的Message和sendMessage的事件戳。
接着看enqueueMessage里面肝了什么

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对象。最终调用queue的enqueueMessage方法。enqueueMessage顾名思义,就是带着Message去排队,我们接下来看看Message是如何去排队。

MessageQueue:
MessageQueue.java

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

上面代码有点长,我们一点一点的看

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

这个就是对target进行判空,判断代发Message是否已经在使用

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;

判断消息队列是否弃用(通常因为线程已死),将待发Message标记已用,获取消息时间戳,Message p 持有当前Message

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

如果当前Message为空,或待发Message需要立即执行,或待发Message的时间戳已小于当前Message的时间戳,将当前Message放至待发Message后面(从这里我们也可以看到MessageQueue中的Message其实是链式储存的,方便插队)

if (needWake) {
                nativeWake(mPtr);
            }

如果待发Message还需要等待,则将待发Message放至队尾
到这里,我们就将需要发送的Message放入到对垒中,接下来我们看看它是怎么被发送的

Looper
Looper.java

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

还是有点多,我们还分开看

final Looper me = myLooper();
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }

获取当前线程的Looper对象进行判空

 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.target.dispatchMessage(msg)
之后线程身份有没有发生改变

 msg.recycleUnchecked();

回收Meesage对象
我们之前在Handler代码中有读到过

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

这一段代码比较简单,根据初始化时是否有设置Callback决定谁来调用handleMessage(Message 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("");

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

到这里还是没看到调用 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的整个执行流程就基本分析完了,建议大家多去看看源码,多点进去看看,可以结合源码一起看,加深印象,这样理解起来更快。

你可能感兴趣的:(Handler源码分析,带你轻松入门)