美文网首页
Handler源码分析

Handler源码分析

作者: Lemon666 | 来源:发表于2020-03-09 18:40 被阅读0次

Handler是Android中消息传递机制,可以将工作线程所创建的消息传递到主线程中去处理,进行UI更新或者其他需要在主线程进行处理的工作。总的来说,就是线程之间的通讯。

Handler原理解析

了解Handler原理之前,我们需要先了解几个相关的类

  • Hander (主要作用发送和处理消息和Runnable)
  • Message (线程间消息传递的载体)
  • MessageQueue(消息队列,存放消息)
  • Looper (循环读取消息队列,发送到指定Handler处理)

Handler的基本使用

//在主线程创建一个Handler对象
//并重载handleMessage方法
Handler mHandler = new Handler(){
    @Override
    public void handleMessage(Message){
        //需要在mHandler的线程处理的业务逻辑
        //可以根据Message的参数处理相应业务,例如UI更新
        textView.setText("通过sendMessage更新UI")
    }
}

//然后在子线程中发送消息
//通过sendMessage方法发送
new Thread(new Runnable(){
    @Override
    public void run(){
        //主线的Handler
        Message message = new Message();
        message.what = 1;
        message.obj = "可以传递对象,这里是传递字符串对象";
        //通过sendMessage发送消息对象
        mHandler.sendMessage(message)
    }
}).start();

//或者可以传递一个Runnable对象
new Thread(new Runnable(){
    @Override
    public void run(){
        mHandler.post(new Runnable(){
            @Override
            public void run(){
                //需要在mHandler的线程处理的业务逻辑
                //如更新UI
                textView.setText("通过post更新UI")
            }
        })
    }
})

除了上面2种方法,Handler发送消息很多种

//发送Runnable
post(Runnable)
postAtTime(Runnable,long)
postAtTime(Runnable,Object,long)
postDelayed(Runnable,long)
postDelayed(Runnable,Object,long)
//发送Message
sendMessage(Message)
sendMessageDelayed(Message,long)
sendMessageAtTime(Message,long)
sendMessageAtFrontOfQueue(Message)
sendEmptyMessage(int)
sendEmptyMessageDelayed(int,long)
sendEmptyMessageAtTime(int,long)

//我们先分析比较简单的sendMessage和post
public final boolean sendMessage(Message msg){
    return sendMessageDelayed(msg, 0);
}
//调用成员方法sendMessageDelayed,延时为0
public final boolean sendMessageDelayed(Message msg, long delayMillis){
    if (delayMillis < 0) {
        delayMillis = 0;
    }
    //所以插入消息队列的时候就是(当前时间+0)
    return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
//uptimeMellis就是消息传递到Handler的时间
public boolean sendMessageAtTime(Message msg, long uptimeMillis){
    MessageQueue queue = mQueue;
    //省略部分代码...
    //最终通过enqueueMessage把消息插入到消息队列
    return enqueueMessage(queue, msg, uptimeMillis);
}

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
    //把当前Handler对象引用保存在Message.target,后续通过这个target来传递到指定Handler去处理消息
    msg.target = this;
    //设置Message是否异步Message
    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
    //插入到消息队列
    return queue.enqueueMessage(msg, uptimeMillis);
}

//MessageQueue.java#enqueueMessage
boolean enqueueMessage(Message msg, long when) {
    //省略部分代码...
    synchronized (this) {
        //省略部分代码...
        msg.markInUse();//标记Message为使用中
        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;
            //遍历消息队列,寻找插入Message的位置
            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;
}
//sendMessage基本流程就如上所示
//sendMessage -> sendMessageDelayed -> sendMessageAtTime -> enqueueMessage

//接着看post流程
public final boolean post(Runnable r){
   return  sendMessageDelayed(getPostMessage(r), 0);
}
//调用getPostMessage把Runnable封装为Message
private static Message getPostMessage(Runnable r) {
    Message m = Message.obtain();
    m.callback = r;
    return m;
}
//最后流程还是sendMessage流程一致

通过上面的代码,了解了Handler如何发送消息的方法,那么线程之间消息是如何传递的呢?

为什么在其他线程通过Hander发送消息后,会到Handler线程进行处理?
首先先看创建Hander实例时候处理

Handler mHandler = new Handler()//创建了Handler实例

//Handler.java
public Handler() {
    this(null, false);
}
    
public Handler(Callback callback, boolean async) {
    ...
    mLooper = Looper.myLooper();
    if (mLooper == null) {
        throw new RuntimeException("Can't create handler inside thread "
        + Thread.currentThread()
        + " that has not called Looper.prepare()");
    }
    mQueue = mLooper.mQueue;
    ...
}
//Handler构造方法主要工作:
//获取Looper对象
//从Looper对象获取mQueue(消息队列)

Looper对象获取

//Looper.java

static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
public static @Nullable Looper myLooper() {
    //通过ThreadLocal.get获取Looper对象
    return sThreadLocal.get();
}

ThreadLoal变量,线程局部变量,简单理解为线程私有变量,这里就不展开描述;

myLooper方法中通过sThreadLocal.get()获取Looper,那Looper是在什么时候set进去的?通过sThreadLocal.set关键字搜索,在Looper的prepare方法内找到

//一般线程初始化Looper
public static void prepare() {
    prepare(true);
}

//主线程初始化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();
    }
}

//真正初始化Looper方法
private static void prepare(boolean quitAllowed) {
    if (sThreadLocal.get() != null) {
        throw new RuntimeException("Only one Looper may be created per thread");
    }
    //创建Looper对象,并将set到ThreadLocal
    sThreadLocal.set(new Looper(quitAllowed));
}

//Looper构造方法
private Looper(boolean quitAllowed) {
    //创建MessageQueue
    mQueue = new MessageQueue(quitAllowed);
    //记录线程ID
    mThread = Thread.currentThread();
}

所以要创建Handler对象,必定要先调用Looper对象的prepare或者prepareMainLooper方法,否则在Handler构造方法就会跑出异常,因为Looper.myLooper返回的对象为null

public Handler(Callback callback, boolean async) {
    ···
    mLooper = Looper.myLooper();
    if (mLooper == null) {
        //获取到Looper对象为空,抛出异常
        //报错说明未调用Looper.prepare()
        throw new RuntimeException(
            "Can't create handler inside thread " + Thread.currentThread()
                    + " that has not called Looper.prepare()");
    }
    mQueue = mLooper.mQueue;
    ···
}

那Looper.prepare方法在什么时候调用?了解过Android源码的可能知道,在ActivityThread的main方法中,调用了Looper.prepareMainLooper,而且当前线程也就是我们所说的主线程

ActivityThread.java

public static void main(String[] args) {
    ···
    //初始化Looper对象
    Looper.prepareMainLooper();
    ···
    //开始循环读取消息
    Looper.loop();
    ···
}

既然我们要循环从消息队列获取消息进行发送,那就可能到开启循环,Looper.loop方法的作用就是循环从消息队列读取消息并且发送。通过源码看看Looper.loop方法是如何循环读取消息

Looper.java
public static void loop() {
    //获取当前线程的Looper对象
    final Looper me = myLooper();
    ···
    //获取Looper的消息队列
    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去处理消息
            //msg.target就是前面sendMessage中设置的Handler引用
            msg.target.dispatchMessage(msg);
            ···
        } finally {
            if (traceTag != 0) {
                Trace.traceEnd(traceTag);
            }
        }
        ···
        //回收Message对象
        msg.recycleUnchecked();
    }
}

知道了Message如何分发到指定Handler,跟踪dispatchMessage看看最后如何传递到Hander的handleMessage方法

//Handler.java#dispatchMessage
public void dispatchMessage(Message msg) {
    if (msg.callback != null) {
        //判断Runnable对象存在
        handleCallback(msg);
    } else {
        //可以在构造方法传入Callback,作用和handlerMessage一样
        //一般都直接重写handleMessage方法
        if (mCallback != null) {
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        //最终调用handlerMessage,把消息传递到我们实例话的Handler对象,一般我们都会重写handleMessage方法
        handleMessage(msg);
    }
}

总结

Handler消息传递机制使用之前,需要先初始化Looper绑定当前线程,再循环从消息队列获取消息分发到指定的Handler去处理,以上只分析了Handerl机制的一般用法,还有其他如异步消息,IdleHandlder的用法还未涉及,后续逐步进行分析

相关文章

网友评论

      本文标题:Handler源码分析

      本文链接:https://www.haomeiwen.com/subject/fsfmdhtx.html