Android进阶之Handler源码全解析(Handler,MessageQueue,Looper)

一、Handler基本用法

首先看一下handler的基本用法,通常用于异步请求回来后更新ui,发送延迟消息等。

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
        //处理消息
            switch (msg.what) {
                case 0:
                     //TODO
                    break;
            }
        }
    };
    //发送消息
   mHandler.sendEmptyMessage(0);

从代码中可以看到 实例化 handler后只需要重写handleMessage方法就能够接受
sendMessage等方法传输过来的message类型的消息了。
那么在mHandler.sendEmptyMessage(0)方法调用后是怎么调用到我们重写的方法handleMessage从而实现我们想要接受到的消息呢?

二、开始看handler源码

我们点进sendEmptyMessage 方法中

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

调用了sendEmptyMessageDelayed,我们一步步跟着源码走 最终所有发送消息的方法都走到了sendMessageAtTime

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

这里我们看到了MessageQueue,它是一个维护发送出去的message的一个消息队列,我们通过Handler发送的消息都会进入到这个队列中我们看一下这个enqueueMessage方法,这个方法接受三个参数 一个是当前queue message和uptimeMillis这个是消息出发的时间戳。
当前的queue是哪来的呢 我们看一下Handler的构造方法代码

    public Handler(Callback callback, boolean async) {
    	//省略部分代码
        mLooper = Looper.myLooper();
        //检查mLooper是否为null
         if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread " + Thread.currentThread()
                        + " that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
    	//省略部分代码
    }

mQueue 是通过 mLooper.mQueue赋值的,也就是 mQueue是Looper的一个变量。这时候就出现了Looper,那么looper是什么呢?说白了looper就是一个一直从MessageQueue 中循环拿消息然后调用消息的处理机制(后面会说具体怎么处理)的一个类。
我们知道了 mQueue是什么了以后继续根据刚才的代码看一下enqueueMessage方法

   private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
   		//这里message有一个target变量 这里把当前的handler传入进入(为后续在looper循环到该message消息时调用自己的handler处理此消息)
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        //这里调用Queue类中的enqueueMessage
        return queue.enqueueMessage(msg, uptimeMillis);
    }

通过这段代码可以看到 我们给要加入messageQueue中的message添加了target指向了当前handler。我们再来看一下Queue类中的enqueueMessage方法

三、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;
			//从这里开始进行把该messge消息放入消息队列中 该队列是一个根据when 执行时间排序的单向链表 
			
            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;
    }

这时候我们就已经把要发送的message消息放入了消息队列中了。那么消息怎么在这个消息自己的when这个时间点去执行呢。这时候我们得来看一下Looper代码了。
看代码之前我们先弄明白Looper什么时候初始化而且是怎么运作的。我们先回顾一下,在Handler构造方法中判断了mLooper是否为null如果为null就会抛出异常,但是我们在平常使用也没有初始化这个looper却没发生异常,是因为主线程已经为我们创建了looper了。
我们看一下ActivityThread.main方法

    public static void main(String[] args) {
		...
		//省略部分代码
		//这里调用了prepareMainLooper方法来创建looper
        Looper.prepareMainLooper();

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

 		...
		//省略部分代码

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

        // End of event ActivityThreadMain.
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        Looper.loop();

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

prepareMainLooper()方法

    public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

可以看到主线程调用prepareMainLooper()创建了主线程的looper并且调用了looper的loop方法,这也就是我们在主线程使用handler的时候不用创建looper的原因。如果我们要在子线程中使用handler需要为该线程创建looper并且调用looper.loop()方法 代码示例如下:

class TestThread extends Thread {
    public Handler mHandler;
    public void run() {
        Looper.prepare();
        mHandler = new Handler() {
            public void handleMessage(Message msg) {
                // process incoming messages here
            }
        };
        Looper.loop();
    }
}

四、Looper中的部分

looper.loop()方法是一个死循环,一直循环quene里面的消息进行处理我们来看一下这个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;
    	...
    	...
    	//省略部分代码
		//下面是个死循环一直获取msg
        for (;;) {
        		//通过queue的next()方法获取messge 我们先不管这个next方法怎么拿到的message后面再分析,只管他返回了一个要处理的message
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }
            ...
    		...
    	//省略部分代码
            //最终调用到了 该message对象所持有的target 也就是之前在handler调用enqueueMessage的时候把自身赋值到了targer对象上。
            //这也就是调用了handler的dispatchMessage方法。
                msg.target.dispatchMessage(msg);
            ...
    		...
    	//省略部分代码
        }
    }

到这我们算是看到了 消息是怎么又回到了handler这调用自身的dispatchMessage方法进行消息处理的。看下dispatchMessage的代码

   public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

五、终于回到了handleMessage

这里可以看到如果给message设置了回调 会优先执行回调,咱们一般不使用回调的时候 就会走到handleMessage这个方法中。handleMessage还记得吧!!就是在咱们自己代码中初始化handler并且重写的那个方法。走了这一圈终于回来了!!后面就是根据自己的业务逻辑处理不同的message了。

六、获取要处理的message逻辑

咱们之前还欠下一个quene.next()方法没看呢。这个方法返回值是一个Message对象,也就是需要处理的message。我们看下代码

 Message next() {
       ...
       ...
       //省略部分代码
       //死循环一直拿message
        for (;;) {
       ...
       ...
            synchronized (this) {
       ...
       ...
                if (msg != null) {
                    if (now < msg.when) {
	         //如果当前时间小于该消息的处理时间那么给nextPollTimeoutMillis 重新赋值 为 消息处理时间-当前时间
                        // 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) {
                            prevMsg.next = msg.next;
                        } else {
                            mMessages = msg.next;
                        }
                        msg.next = null;
                        if (DEBUG) Log.v(TAG, "Returning message: " + msg);
                        msg.markInUse();
	        //拿出要处理的message后把该消息从链表中移除
                        return msg;
                    }
                } else {
                    // No more messages.
                    nextPollTimeoutMillis = -1;
                }
       ...
       ...       
    }

通过代码可以看出我们在把消息放进queue中的时候设置的执行时间,在取出的时候是根据这个时间取出的。这也是咱们发送消息的时候可以发送延迟消息的关键。

七、总结

要弄懂handler机制首先要明白 Handler,MessageQueue,Looper,三者之间的关系。
1、每个线程(包含主线程)要使用handler都要有自己的Looper ,looper在创建的时候会初始化自己的变量queue。也就messagequeue是looper的一个变量。
2、looper在调用loop方法后会一直从messagequeue中拿取消息处理。
3、在把message放进messagequeue之前会把当前的handler赋值给message.target变量,这在后面loop拿到该消息后用该message的target处理该消息。

大家可以根据这个思路自己去看一下源码应该都会有自己的收获!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值