android handler源码分析,Android中的handler源码解析(超详细)

Handler是什么?

Android中的异步消息处理机制,使用者可以在不阻塞UI线程的前提下轻松的实现消息管理和发送。

原理:

handler机制中包含4个关键类(下面对源码的解析也是从这4个类入手),Message(消息),MessageQueue(消息队列),Looper(轮询器),Handler(消息发送和接收并处理),简单一句话概括就是:handler负责发送message,将其加入到MessageQueue中,Looper不间断的从MessageQueue中取出消息,并发送给对应的handler实例去处理。

重点:源码解析

有些同学不知道如何去看源码,这就很尴尬了,往往想知道系统里面的源码或者牛逼的开源项目是如何设计的,但是就是不知道如何入手,还有些同学觉得看源码没用,懂得怎么用不就行了吗,非也,懂得如何用那只是招式,可能换个地方换种形式你就不认识了,懂源码,那是心法,知其所以然,才能千变万化!

首先,我们使用的时候是这样的:

Handler handler = new Handler() {

@Override

public void handleMessage(Message msg) {

//消息处理

·········

}

};

Message msg = Message.obtain();

handler.sendMessage(Message msg);

定义一个handler,并重写了他的handleMessage()方法;我们来看看它的构造方法:

public Handler() {

this(null, false);

}

public Handler(Callback callback) {

this(callback, false);

}

public Handler(Looper looper) {

this(looper, null, false);

}

public Handler(Looper looper, Callback callback) {

this(looper, callback, false);

}

public Handler(Looper looper, Callback callback) {

this(looper, callback, false);

}

@hide

public Handler(boolean async) {

this(null, async);

}

@hide

public Handler(Callback callback, boolean async) {

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;

}

@hide

public Handler(Looper looper, Callback callback, boolean async) {

mLooper = looper;

mQueue = looper.mQueue;

mCallback = callback;

mAsynchronous = async;

}

蒙蔽了,这么多!但是注意,后面三个你都是没法使用的,因为有@hide;

先看空参构造,他直接调用了Handler(Callback callback, boolean async);看看里面做了什么:

获取looper对象:Looper.myLooper(); 进去可以看到 返回了,sThreadLocal.get();这个是什么玩意?ThreadLocal,他是一个容器,里面封装了一个map,以当前线程的ThreadLocal作为key,以你要存的值作为value,我们这里value就是looper对象,这个容器是专门用来保存线程所特有的变量的,起到了线程间隔离的作用,如果有人想知道,我专门开一篇博客来讲。至于looper是怎么初始化的,客官莫急,下面会讲。

mQueue = mLooper.mQueue;拿到消息队列,这是一个链表结构,注:一个线程对应一个looper,一个looper同样也只有一个queue;

callback这个是handler里面的一个接口,在消息分发的时候会讲到,默认是null,mAsynchronous这个参数表示消息是否是异步消息,默认是false;

接下来看Message.obtain():

public static Message obtain() {

synchronized (sPoolSync) { //同步代码块

if (sPool != null) {

Message m = sPool; //sPool是一个静态的Message 引用

sPool = m.next; //next也是Message,但是他不是静态的;

m.next = null;

m.flags = 0;

sPoolSize--;

return m;

}

}

return new Message();

}

obtain()的实现非常有意思,我们知道message其实是复用的,message中有一个方法:recycle(),大家可以去看一下,消息被处理完毕后会调用recycle()方法,将message还原,并将sPool这个赋值为this,也就是当前自己的实例对象,如果sPool是null那么当前没有消息可以复用,直接new出来并返回,如果不是null,那么将当前的sPool返回,那么这个next又是干什么的呢?代码可见,sPool =m.next;将sPool重新赋值,这个m.next就是一条将要处理的消息,也就是说每一个msg里面都有对下一个将要处理的消息的引用,这样,sPool被赋值了,下次再执行obtain()的时候,sPool指向的其实是另外一个Message实例了,至于next如何赋值,稍后在MessageQueue中详细解析。

Message拿到了,开始发消息吧,sendMessage(Message msg);

public final boolean sendMessage(Message msg){

return sendMessageDelayed(msg, 0); //直接调用sendMessageDelayed方法

}

通过源码,一层一层往下找,发现:sendMessage ——> sendMessageDelayed ——>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);

}

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {

msg.target = this; //重点:this表示的是当前的handler实例,每个message都会记录发送它的那个handler

if (mAsynchronous) {

msg.setAsynchronous(true);

}

return queue.enqueueMessage(msg, uptimeMillis); //这里调用了messageQueue的方法;

}

重点:为什么msg要保存handler的引用呢?

我们都知道,handler机制消息处理,哪一个handler实例发出的消息,那么那一个handler就负责处理这个消息,这里的msg.target = this; 作用就在这,用来记住谁将msg发出来,等到处理的时候谁就来处理。

接着分析,handler最后调用了queue.enqueueMessage(msg, uptimeMillis);

我们来看看这个方法:(比较多,我精简了一下,留下重要的部分)

boolean enqueueMessage(Message msg, long when) {

msg.markInUse();

msg.when = when;

Message p = mMessages;//当前将要被处理的msg

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;

prev.next = msg;

}

// We can assume mPtr != 0 because mQuitting is false.

if (needWake) {

nativeWake(mPtr);

}

}

return true;

}

mMessages是即将要处理的message,先看第一个if最有一个条件,when

重点又来了! Looper!

上面留下了一个问题,Looper是怎么初始化的呢,app中的通信,UI的刷新,都需要依赖handler,那么,我们就猜想,Looper在app启动的时候就已经开始创建并初始化了,那么我们去源码中找 ActivityThread main()方法 ;

public static void main(String[] args) {

````````

Looper.prepareMainLooper(); //在这里!

ActivityThread thread = new ActivityThread();

thread.attach(false);

if (sMainThreadHandler == null) {

sMainThreadHandler = thread.getHandler();

}

if (false) {

Looper.myLooper().setMessageLogging(new

LogPrinter(Log.DEBUG, "ActivityThread"));

}

Looper.loop(); //还有这里

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

}

果然,在主线程启动的时候就已经启动了Looper并调用了,prepareMainLooper()和loop();接着去looper里面看看:

public static void prepareMainLooper() {

prepare(false);

synchronized (Looper.class) {

if (sMainLooper != null) {

throw new IllegalStateException("The main Looper has already been prepared.");

}

sMainLooper = myLooper();

}

}

private static void prepare(boolean quitAllowed) {

//判断looper是否是null如果是,就创建,并将其存到ThreadLocal中,上面说的handler中的looper就是从ThreadLocal中取出来的;

if (sThreadLocal.get() != null) {

throw new RuntimeException("Only one Looper may be created per thread");

}

sThreadLocal.set(new Looper(quitAllowed));

}

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;

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;

}

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 {

msg.target.dispatchMessage(msg); //分发消息

} finally {

if (traceTag != 0) {

Trace.traceEnd(traceTag);

}

}

if (logging != null) {

logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);

}

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(); //消息的回收

}

}

三个方法,prepareMainLooper()其实内部调用了prepare(false);这个boolean参数是什么意思呢,意识就是不允许messageQueue退出,这个参数会在构建Queue的时候传递进去,因为主线程的消息队列只有在应用退出的时候才允许退出,否则······没有否则,消息机制都没了,还怎么玩!

prepare()方法创建了一个looper,但是looper并没有启动,启动的方法是下面的loop();loop()有一个for(;;),死循环,里面做的工作就是一直取消息,并处理,然后recycleUnchecked()复用。这个时候looper就启动起来了,只要你的应用还在运行,他就会一直在。looper拿到消息后会通过msg.target.dispatchMessage(msg); 将消息发出来给handler处理,这里的msg.target不就是我们发消息的时候初始化的handler吗?(篇幅有点长,不记得可以往上翻)

继续看,又到重点了

public void dispatchMessage(Message msg) {

if (msg.callback != null) {

handleCallback(msg);

} else {

if (mCallback != null) {

if (mCallback.handleMessage(msg)) {

return;

}

}

handleMessage(msg);

}

}

通过一系列判断,来处理消息,如下:

判断msg.callback是不是null,如果不是,那么就给这个callback处理,这个callback是message中的一个Runnable;Message.obtain()其实是有其他参数的方法的,其中有一个是obtain(Handler h, Runnable callback);如果你用了这个,那么消息就会在你实现的Runnable中接收到处理的回调;

第二个是判断handler内部的callback是不是null,如果不是null,就让他去处理,这里的Callback可不是Runnable了,他是一个interface,里面定义了一个handleMessage(Message msg);方法,这个怎么实现呢?handler类里同样有Handler(Callback callback)构造方法

最后才轮到handler类里的方法handleMessage来处理消息。也就是我们在开始写的那个简单的handler使用方法。

结语:本文从使用过程为主线,来分析Handler原理,文中含有大量篇幅的源码,也比较详细,网上其他的博客也很多,但是讲的都比较粗糙,讲解的流程也不容易理解,无法串联起来,希望通过这篇博客能让大家完全理解Handler机制,若有错误的地方,欢迎指正!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值