天天看点

android-Handler源码解析

前言

Android跨进程通信常用Binder,同进程内线程切换使用handler,理解handler原理,有助于我们理解Android消息机制。

首先提出问题

  1. handler与loop的关系,一个线程能否创建多个handler
  2. loop一直循环为什么不会卡死
  3. handler的内存泄漏原因,继承handler不会发生内存泄漏

查看Handler的api我们可以看到,Handler主要为我提供了两个大体的作用

  1. post相关方法

    ,如post(Runnable) postAtTime(Runnable,long)等
  2. send相关方法

    ,如sendEmptyMessage(int) sendMessages(Message)等

第一个我们常用在App的启动页等待跳转上,第二个常用在子线程给主线程发送消息上。但这两个都与线程有关系,其实我们可以看出,handler。

那我想从

post(Runnable)

方法和

sendMessage(Message)

看看Handler是这么工作的。

首先我们看看我们常用的两个方法

new Handler().post(new Runnable() {
    @Override
    public void run() {
    }
});
           
Handler handler=new Handler(){
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
    }


};
handler.sendMessage(new Message());
           

现在我们开始跟踪

Hanler的源码

,看看怎么执行到

Runnable

的run方法,以及发送消息后怎么接收到消息的回调,以及涉及到的其他相关类和解释前面提到的问题,这里我使用的是

API 26: Android 8.0 (Oreo)

的源码进行查看。

首先看看

Handler的构造方法

。调用

Looper.myLooper()

得到

mLooper

,这里我们知道Handler是创建在主线程的,因为我们也没有开子线程去new Handler,并且Looper.myLooper()进入里面看也是有说到获取的是此线程的当前线程值,也就是mainThread的Looper,mainThread的Looper什么时候创建我们后面讲。

public Handler() {
    this(null, false);
}
           
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对象
    if (mLooper == null) {
        throw new RuntimeException(
            "Can't create handler inside thread that has not called Looper.prepare()");
    }
    mQueue = mLooper.mQueue;
    mCallback = callback; // 不设置 callback就为空 
    mAsynchronous = async;
}
           

首先点击

post()

方法,会进入到Handler类的354行,会看到post()方法又调用了

sendMessageDelayed()

方法,其中使用出传过来的参数Runnable调用了

getPostMessage()

方法返回一个

Message

对象,这里就涉及到了相关类Message类,接着我们继续看。

public final boolean post(Runnable r)
{
   return  sendMessageDelayed(getPostMessage(r), 0);
}
           
private static Message getPostMessage(Runnable r) {
    Message m = Message.obtain();
    m.callback = r;
    return m;
}

```java
方法`sendMessageDelayed()`后面又调用了`sendMessageAtTime()`,在sendMessageAtTime方法里面我们又看到了一个新的相关类`MessageQueue`类,并且已经存在一个对象`mQueue赋值给了MessageQueue`,最后调用了`enqueueMessage()`方法,使用`MessageQueue`的`enqueueMessage()`方法添加了一个`message`,那接下来我们就看看Message类和MessageQueue类都有些什么关键的点。

```java
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
    MessageQueue queue = mQueue;// 创建 Handler的时候就获取了messageQueue
    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);
}
           

Message类

下面是Message类的部分内容,首先我们看到

  1. Message类实现序列化Parcelable接口,也就是说

    Message可以在不同进程之间传递

  2. Message可以使用Bundle添加数据,可传递对象
  3. Message具有Handler的引用

    ,在前面Handler类的

    enqueueMessage()

    方法中,就会有

    msg.target=this

    ,将当前Handler赋值给要添加的Message,也就是为每一个Message添加一个Handler的引用,这个很重要,到最后每一个Message 是要分发到对应的Handler中的,就是靠Message所携带的对应HandlerRunnable
  4. Runnable

    其实是一个callback,这个也在

    Handler

    类的

    getPostMessage()中进行了赋值

    ,后面发送消息的时候也会用到根据判断Message的callback来判断调用哪一个回调方法。
  5. obtain其实是建议我们不要使用Message的构造方法去创建对象

    ,而是使用obtain得到一个message对象
public final class Message implements Parcelable {
Bundle data;// 103行
Handler target;//105行
Runnable callback;//107行
 Message next;//110行
	public static Message obtain() {
    synchronized (sPoolSync) {
        if (sPool != null) {
            Message m = sPool;
            sPool = m.next;
            m.next = null;
            m.flags = 0; // clear in-use flag
            sPoolSize--;
            return m;
        }
    }
    return new Message();
}
}
           

MessageQueue类

首先我们要知道

MessageQueue是一个容器

,用于

存放和取出Message

,那对于这个类我们也就重点看看存和取两个方法,下面这个方法就是在handler类中MessageQueue最后调用的

的方法。

boolean enqueueMessage(Message msg, long when) {
    if (msg.target == null) {    // 1首先 如果当前message没有对应的Handler,和下面已经在使用 就会异常
        throw new IllegalArgumentException("Message must have a target.");
    }
    if (msg.isInUse()) {
        throw new IllegalStateException(msg + " This message is already in use.");
    }

    synchronized (this) { // 2 添加消息的时候是一个同步方法
        if (mQuitting) {  // 3 如果已经退出,再加入就异常
            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();  // 4  标记为正在被使用
        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.  5  当为空的时候读取消息是阻塞的, 添加新消息,并唤醒
            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.
            //6  msg.isAsynchronous() 如果是异步的就返回true   mBlocked为true则有屏障,  如果是异步并且有屏障,就唤醒。关于
 
            needWake = mBlocked && p.target == null && msg.isAsynchronous();
            Message prev;
            for (;;) {  //
         //7这个时候p 是不为空的,这里可以看出Message类是一个单向链表,而MessageQueue则引用了这个链表,并且在这个链表里面出面做插入和取出等操作
                prev = p;  
                p = p.next;
                if (p == null || when < p.when) { // 8加入链表的时候按时间顺序从小到大排序
                    break;
                }
                if (needWake && p.isAsynchronous()) { //9 然后判读是否需要唤醒
                    needWake = false;
                }
            }
            msg.next = p; // invariant: p == prev.next
            prev.next = msg;
        }

        // We can assume mPtr != 0 because mQuitting is false.
        if (needWake) {  // 10 唤醒之前等待的线程
            nativeWake(mPtr);
        }
    }
    return true;
}
           

接下来就是

的时候,获取

Messag由另一个类叫Loop类

完成,后面在流程再往后走的时候再介绍。

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;  //1 mMessages 是链表的头结点
            if (msg != null && msg.target == null) {  //2 如果Messages 不为空,并且target为空, 说明它是一个屏障,需要一直往后遍历找到第一个异步的消息  
                // 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) { // 3 如果这个消息还没有到时间,就设置一个时间再处理 
                    // 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) {  //4 获取消息,将链表头结点后移一位
                        prevMsg.next = msg.next;
                    } else {
                        mMessages = msg.next;   
                    }
                    msg.next = null;
                    if (DEBUG) Log.v(TAG, "Returning message: " + msg);
                    msg.markInUse();  // 5 标记为在使用 
                    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.
        //将空闲处理程序计数重置为0,不会再次运行   
        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;
    }
}
           

再回到前面讲到的

Handler

调用的

enqueueMessage()

,到这里算是知道,

Message是添加到了MessageQueue的消息队列

,那什么时候又回调到Handler的,那就要涉及到另一个类Loop类,在源码MessageQueue的上面我们可以看到说明,可以使用

Looper.myQueue()

来检索

MessageQueue

那就先看看Looper类。

下面是Looper类的部分源码

public final class Looper {

	static final ThreadLocal<Looper> sThreadLocal = new 		ThreadLocal<Looper>();
	private static Looper sMainLooper;  // guarded by Looper.class
	final MessageQueue mQueue;
	
	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 
	}


	private Looper(boolean quitAllowed) {
    mQueue = new MessageQueue(quitAllowed);
    mThread = Thread.currentThread();  // 返回对当前正在执行的线程对象的引用,也就是 mainThread 主线程 
	}
	
	public static void prepareMainLooper() {
    prepare(false);
    synchronized (Looper.class) {
        if (sMainLooper != null) {
            throw new IllegalStateException("The main Looper has already been prepared.");
        }
        sMainLooper = myLooper();
   	 }
	}

}

	public static void loop() {
    final Looper me = myLooper(); // 1 从ThreadLocal中获取到当前 Looper 
    if (me == null) {
        throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
    }
    final MessageQueue queue = me.mQueue;// 2. 从Looper 中获取MessageQueue

    // 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(); // 3 这里就是我们之前分析的从messageQueue中得到一个Message 
        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 slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;

        final long traceTag = me.mTraceTag;
        if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
            Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
        }
        final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
        final long end;
        try {
            msg.target.dispatchMessage(msg);// 4 到这里可以看到 调用了message对于的target的dispatchMessage方法,就是Handler回调的方法
            end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
        } finally {
            if (traceTag != 0) {
                Trace.traceEnd(traceTag);
            }
        }
        if (slowDispatchThresholdMs > 0) {
            final long time = end - start;
            if (time > slowDispatchThresholdMs) {
                Slog.w(TAG, "Dispatch took " + time + "ms on "
                        + Thread.currentThread().getName() + ", h=" +
                        msg.target + " cb=" + msg.callback + " msg=" + msg.what);
            }
        }

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

上面loop()方法讲的只是Looper的一个循环方法,那我们并没有看到Looper在哪里调用了这个方法。这里就要说到

android的主线程ActivityThread,在主线程的入口方法main

中,可以看到这样的代码

public static void main(String[] args) {
...
Looper.prepareMainLooper();

...
Looper.loop();
 }
           

看到这里是个不是很熟悉,我们看到了在

ActivityThread

中调用了

Looper

prepareMainLooper()

loop

方法,

prepareMainLooper

接着调用了

prepare()

,接着创建一个

Looper

,并且Looper的构造方法中创建了

MessageQueue

保存在当前MessageQueue中, 并且返回,当前正在执行的线程对象的引用,也就是主线程mainThread.

在这里可以知道,

Looper 对象是在主线程ActivityThread 中创建的

,并且同时在

构造函数中创建了MessageQueue并与当前创建Looper对象的线程相绑定

,也就是说

每一个主线程都有一个Looper对象,每一个looper对象都有一个MessageQueue

;

我们回去看Looper对象的

loop()

方法,在loop()方法的循环中,我们看到得到的

message调用了对应的handler的dispatchMessage() ,message的handler是在 handler类的enqueueMessage()

方法中设置的,那我们继续看handler的

dispatchMessage()

public void dispatchMessage(Message msg) {
    if (msg.callback != null) {  
        handleCallback(msg); // 调用 callback的run方法,callback就是 Handler类中getPostMessage()方法设置的Runnable对象,
    } else {
        if (mCallback != null) {
            if (mCallback.handleMessage(msg)) {  //创建handler时候 设置了就调用设置的了,没有就直接调用handleMessage()方法
                return;
            }
        }
        handleMessage(msg);
    }
}
           
private static void handleCallback(Message message) {
    message.callback.run();
}
           
public void handleMessage(Message msg) {
}
           

到这里从消息的发送到接收我们都走了一遍,下面再简单梳理一下

  • 在主线程中使用的Looper是在MainThread中创建的

  • 在主线程中创建handler的时候就获取了早已创建好的Looper,并且根据Looper获取了对应的MessageQueue
  • Message 的

    target

    Handler 是在

    enqueueMessage()

    方法中设置的
  • MessageQueue是在创建

    Looper的时候构造方法

    中创建的
  • Looper的消息循环是一个死循环,但是并不会特别消耗CPU资源,这里涉及到Linux 的

    pipe/epoll

    机制,就是在主线的MessageQueue没有消息的时候,便会阻塞在loop的queue.next的nativePollOnce方法里,此时主线程会释放cup资源进入休眠状态。

当进入休眠状态后,还能跟新UI?

这里要知道,

ActivityThread中

有一个继承

Hanle

r的类

H

,就在ActivityThread中,并且

ActivityThread并不是一个正在的线程,真正的主线程是 ApplicationThread

, 具体去看ApplicationThread中的

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

在 t

hread.attach(false)

;方法中会引用到

mAppThread

,就是

ApplicationThread

的实例化对象

ApplicationThread

中有很多

sendMessage()

方法, 发送消息后Looper循环,然后ApplicationThread.H根据收到的消息处理不同任务,比如调用Activity的生命周期方法

接下来说说最开始提到的几个问题

  1. Handler 与looper的关系,这里要说到当前线程,Hansler的创建都是在

    线程

    中完成的,不管是主线程还是子线程,平常我们在UI线程中创建Handler,然后发送消息,那我们可以创建几个Handler ?我们是

    可以创建多个handler

    的,UI线程并没有在多创建的时候报错,

    创建的多个handler的时候获取的是当前线程的Looper

    ,并且当创建Handler 获取的当前线程的Looper为空的时候 会报错:Can’t create handler inside thread that has not called Looper.prepare() ,可以看到创建Handler的时候必须先调用 Looper.prepare()方法,并且要在

    handler 创建完成后调用Looper.loop()方法来完成消息循环

    。所以

    一个线程是可以创建多个Handler的,但只能创建一个Lopper, handler与Looper是多对一的关系

  2. Looper一直循环为什么不会卡死
  3. 关于handler的内存泄漏,

这个Handler的分析到这里就结束了,其实里面还有几个知识点需要去理解

  • Activity的启动过程
  • Binder 这个是我一直不敢去看的,总觉得太复杂
  • ThreadLocal

handler的详细分析

https://blog.csdn.net/qian520ao/article/details/78262289

关于内存泄漏

https://www.cnblogs.com/xujian2014/p/5025650.html

android 源码

https://www.androidos.net.cn/sourcecode

https://blog.csdn.net/andywuchuanlong/article/details/48179165

MessageQueue 的本地方法详解

https://www.sohu.com/a/145311556_675634

Handler的详细分析

https://blog.csdn.net/u010983881/article/details/76682169

https://blog.csdn.net/c10wtiybq1ye3/article/details/80809708

继续阅读