欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Handler Looper 源码分析

程序员文章站 2022-07-14 15:17:35
...

1.Hander sendMessage 分析(MessageQueue 消息队列)

Handler sendMessage之后的流程

Hander.sendMessage(msg) —>Hander.sendMessageDelayed—>Hander.sendMessageAtTime —> Hander.enqueueMessage —> MessageQueue.enqueueMessage

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) {
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked;
            } else {
                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;
            }

            if (needWake) {
                nativeWake(mPtr);
            }
        }
        return true;
    }

目前为止我们没有看到 handler 去调用 handleMessage() 方法 ,目前也只是看到了 MessageQueue , 把消息给了 mMessage

总结:handler.sendMessage其实只是把我们的Message加入了消息队列,队列采用的是链表的方式,按照时间排序,然后再也没干其他。

2.Loop 消息循环

子线程中使用 Handler 必须先调用 Looper.prepare(); 不然会报错,我们在主线程中并没有调用过 Looper.prepare(),为什么就不报错?

因为在我们应用启动的时候,ActivityThread 的入口函数 main() 方法中已经写了

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

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

Looper.prepareMainLooper();
进入源码查看主要调用 sThreadLocal.set(new Looper(quitAllowed));

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

sThreadLocal.set(new Looper(quitAllowed));

public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

总结:其实就是创建一个 Looper ,并且保证一个 Thread 线程中,只有一个 Looper 对象

Looper.loop(); 循环执行MessageQueue里的message

 public static void loop() {        
	 // 获取线程的 Looper 对象        
	 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 (;;) {            
		 // 死循环不断的获取 消息队列中的消息            
		 Message msg = queue.next(); // might block            
		 if (msg == null) {                
			 // No message indicates that the message queue is quitting.               
			 return;            
		 }            
		 try {                
			 // 通过 handler 去执行 Message 这个时候就调用了 handleMessage 方法                
			 msg.target.dispatchMessage(msg);            
		 } finally {                
			 if (traceTag != 0) {                    
			 Trace.traceEnd(traceTag);                
		 }            
		}           
		 // 回收消息            
		 msg.recycleUnchecked();        
	}    
 }

额外知识

msg.recycleUnchecked(); 回收信息
Message 用到 Message 消息池,最大50个,回收消息之后,消息池空闲Message +1

private static Message sPool;
private static int sPoolSize = 0;
private static final int MAX_POOL_SIZE = 50;
void recycleUnchecked() {
        flags = FLAG_IN_USE;
        what = 0;
        arg1 = 0;
        arg2 = 0;
        obj = null;
        replyTo = null;
        sendingUid = -1;
        when = 0;
        target = null;
        callback = null;
        data = null;
        synchronized (sPoolSync) {
            if (sPoolSize < MAX_POOL_SIZE) {
                next = sPool;
                sPool = this;
                sPoolSize++;
            }
        }
    }

Message msg = Message.obtin()Message msg1 = new Message() 区别

Message.obtin() 源码,先去消息池获取message(sPool),如果没有sPool 再重新new Message(); 综合利用空闲的Message 。

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