Android FrameWork之旅 --- Handler

基于Anroid7.0源码 个人笔记
Handler—线程切换,post消息 平时开发最常用两个功能
涉及到的源码:

/frameworks/base/core/java/android/os/Handler.java
/frameworks/base/core/java/android/os/MessageQueue.java
/frameworks/base/core/java/android/os/Message.java
/frameworks/base/core/java/android/os/Looper.java
ThreadLocal.java

一、关于线程切换,先看下伪代码:

new Thread(){
            @Override
            public void run() {
                super.run();
                //1.1
                Looper.prepare();
                //1.2
                mHandler = new Handler(){
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        //省略
                    }
                };
                //1.4
                Looper.loop();

            }
        }.start();
//1.3
mHandler.sendEmptyMessage(MSG);

很简单,逐一看下这些方法都做了些什么呗。
1.1Looper.prepare(),显然是一个静态方法:

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

调用了带参的prepare方法,先判断了一下sThreadLocal.get() != null是否成立,看下sThreadLocal是在哪里声明的:

 // sThreadLocal.get() will return null unless you've called prepare().
    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

原来是一个ThreadLocal泛型为Looper的对象,先了解下ThreadLocal是什么东东?
摘自网络:
当使用ThreadLocal维护变量时,ThreadLocal为每个使用该变量的线程提供独立的变量副本,所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本。
再看参数是:new Looper(quitAllowed)

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

做了两件事:
-1 创建了一个MessageQueue对象
-2 给成员变量mThread 赋值为当前的线程
MessageQueue.java这个类,顾名思义就是消息队列

—–唯美的分割线—–
在Handler的使用场景就是可以把Looper和对应的线程进行绑定,逐一对应。
关于ThreadLocal本文需要了解的两个方法:

void set(Object value) --- 设置当前线程维护的线程局部变量。
public Object get() --- 返回当前线程维护的线程局部变量。

继续往下走:

sThreadLocal.set(new Looper(quitAllowed));
设置当前线程的局部变量的值为new Looper(quitAllowed)

1.2创建Handler
看下Handler的构造方法:

//1
public Handler() {
    this(null, false);
}
//2
public Handler(Callback callback) {
    this(callback, false);
}
//3
public Handler(Looper looper) {
    this(looper, null, false);
}
public Handler(Looper looper, Callback callback) {
    this(looper, callback, false);
}
public Handler(boolean async) {
     this(null, async);
}
public Handler(Callback callback, boolean async) {
}

主要看下前面三种:
1.第一种是我们示例中用到的,是无参的构造方法,它调用了2中的方法,也就是callback为null,这里callback是什么呢?

 public interface Callback {
     public boolean handleMessage(Message msg);
 }

这里先不急着知道,等看到后面自然就知道了。
看下两个参数的构造具体做了什么?

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

-1首先获取了一个Looper对象,然后把传递过来callback赋值给成员变量mCallback,那么继续看下Looper.myLooper()。

 public static @Nullable Looper myLooper() {
     return sThreadLocal.get();
 }

拿到Looper.prepare()这里set的ThreadLocal绑定的Looper对象。

1.3mHandler.sendEmptyMessage(MSG);

public final boolean sendEmptyMessage(int what){
    return sendEmptyMessageDelayed(what, 0);
}

public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
    Message msg = Message.obtain();
    msg.what = what;
    return sendMessageDelayed(msg, delayMillis);
}

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

可以看到不管我们调用什么方法最终都会执行到这个方法:sendMessageAtTime
这个方法又会调用到enqueueMessage方法

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

-1msg.target = this,这里this也就是Handler
-2queue.enqueueMessage(msg, uptimeMillis)
继续看enqueueMessage,queue是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;
}

首先是各种判断和赋值,然后一个死循环不停的取消息。

1.4Looper.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;
        //***
        for (;;) {
       //1.4.1 从MessageQueue里取消息
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }
            //***
            try {
            1.4.2
                msg.target.dispatchMessage(msg);
                end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            //***

    }

1.4.1 从MessageQueue里取消息,可能会阻塞
1.4.2 msg.target.dispatchMessage(msg),在1.3中知道了msg.target是Handler对象,所以会调用到Handler的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;
                }
            }
            handleMessage(msg);
        }
    }

-1判断msg.callback是否为null,如果不为null,则执行handleCallback方法

private static void handleCallback(Message message) {
        message.callback.run();
}

-2如果msg.callback == null,并且mCallback != null,那么执行mCallback.handleMessage(msg),记得我们前面也有讲到mCallback但是不知道这是个什么东东,这里需要介绍Handler的另一个方法:post()

public final boolean post(Runnable r) {
   return  sendMessageDelayed(getPostMessage(r), 0);
}

再看getPostMessage方法:

 private static Message getPostMessage(Runnable r) {
        Message m = Message.obtain();
        m.callback = r;
        return m;
}

看一个很熟悉的代码:

mHandler.post(new Runnable() {
      @Override
      public void run() {
      //***
    }
});

前面创建Handler的时候: mCallback = callback,所以是把post的Runnable赋值给了mCallback。

-3 handleMessage(msg),它其实是个空实现:

/**
  * Subclasses must implement this to receive messages.
   */
public void handleMessage(Message msg) {
}

需要开发者自己去重写,所以最终都会走到我们重写的handleMessage方法去处理。

总结下:
1、Message :消息
2、MessageQueue : 消息队列
3、Looper:滚动消息队列的东西
4、Handler: 放入消息和取走消息
5、mCallback,也就是Runnable: 处理消息的动力

猜你喜欢

转载自blog.csdn.net/lj527409/article/details/78397726