Handler消息机制(个人学习笔记)

涉及到的对象:
  • Handler
  • Message
  • MessageQueue
  • Looper

Message

一般用法

Message msg = Message.obtain();//存在复用机制,性能好,推荐使用
Message msg = new Message();

Message.obtain()方法:

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

Handler

一般用法:

Handler handler = new Handler(){
    public void handleMessage(Message msg) {
        
    }
};

class MyHandler extends Handler{
    public void handleMessage(Message msg) {
        
    }
}

看其构造方法:

 public Handler() {
    this(null, false);
 }

 public Handler(Callback callback, boolean async) {
    ...省略无用代码
    //得到当前线程的looper对象
    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;
    mAsynchronous = async;
}

一般使用sendMessage方法发送消息,其最终调用的是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);
}

看enqueueMessage()方法
在Message入队操作中,Message对象持有了当前Handler对象

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
    //这个target现在就是当前的Handler
    msg.target = this;
    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
    return queue.enqueueMessage(msg, uptimeMillis);
}

Looper

Looper.myLooper()方法:

/**
 * Return the Looper object associated with the current thread.  Returns
 * null if the calling thread is not associated with a Looper.
 */
public static Looper myLooper() {
    //使用TreadLocal对象来将Looper对象和创建Handler的线程绑定
    //取得时候从当前线程中获取。
    return sThreadLocal.get(); 
}

有取出就有放入,看Looper.prepare():

private static void prepare(boolean quitAllowed) {
    if (sThreadLocal.get() != null) {
        //同一个线程智能创建一个Looper对象
        throw new RuntimeException("Only one Looper may be created per thread");
    }
    //创建Looper对象和当前线程绑定,new Looper()时便会创建一个MessageQueue消息队列
    sThreadLocal.set(new Looper(quitAllowed));
}

再看下方,有一个prepareMainLooper(),顾名思义就是创建主线程的Looper(主线程是默认就存在一个Looper对象,其他线程初始时是没有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对象呢,这里就要追溯到我们应用启动的入口,ActivityThead里的main方法了(这个类SDK中是没有的,需要到系统源码中去找)。

public static final void main(String [] args){
    //...省略无用代码
    Looper.prepareMainLooper();
    if(sMainThreadHandler == null){
        sMainTheadHandler = new Handler();
    }
    //开启死循环检测消息 这句是确保我们的程序一直运行,不会退出
    Looper.loop();//
    //这里多写一句,当我们主线程的Looper被奇奇怪怪的事情给退出了(结束循环),那么我们的程序也就退出了。
    if(Process.supportsProcesses){
        throw new RuntimeException("Main thread loop unexpectedly exited");
    }
    //thread是ActivityThread
    thread.detach();
}

这时,主线程中就创建了Looper对象。

再看Looper.loop()方法:

//在此方法中,循环检测消息
public static final void loop(){
   Looper me = myLooper();
   //此时可能会产生阻塞(队列里没消息)
   //产生疑问:假设这里是主线程,产生阻塞却不会触发ANR,搜索发现这和Linux系统里使用管道(pipe)来进行进程间通信有关。
   MessageQueue queue = me.mQueue;
   while(true){
       Message msg = queue.next();
       if(msg != null){
            //...省略一些判空检测
            //Message对象里会持有一个Handler引用,target就是我们的Handler
            //调用Handler的dispatchMessage处理消息
            msg.target.dispatchMessage(msg);
            msg.recycle();//回收消息对象
       }
   }
}
  • 管道通信:Linux中的一种进程间通信方式,使用了特殊的文件,有两个文件描述符(一个是读取,一个是写入)
  • 一般应用场景:主进程拿着读取描述符等待读取,没有内容时就会阻塞,另一个进程拿着写入描述符取写数据,此时会唤醒主进程,主进程拿着读取符读取到内容,继续执行。
  • Handler应用场景:Looper调用loop方法会产生阻塞,等待消息的到来(此时会主线程会让出cpu,等待被唤醒)。一旦被唤醒,就会将消息取出,交给Handler来处理。(也就是说程序启动,无时无刻伴随着睡眠唤醒,只要你有操作,什么触摸,点击,滑动,所以不会出现卡顿,这也解释了,当你在主线程执行耗时操作,很长时间looper都没有收到消息,也就是没有被唤醒,便会出现ANR异常,我是这么理解的)

最后再看Handler的dispatchMessage方法:

/**
 * Handle system messages here.
 */
public void dispatchMessage(Message msg) {
    //如果你给Message对象设置了回调 则优先调用
    if (msg.callback != null) {
        handleCallback(msg);
    } else {
        //否则查看Handler对象里的回调,也就是执行handler.post之类的方法
        if (mCallback != null) {
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        //当以上都不满足 则调用Hanlder类里的抽象方法 也就是我们一般重写的
        handleMessage(msg);
    }
}

至此Handler消息机制已经到了尾声,中间略过了消息入队的相关操作,这些操作是在MessageQueue中完成了。有兴趣的小伙伴可以去研究下。

下一篇,我们看一看AsyncTask是怎么工作的。

    原文作者:旧时光KK
    原文地址: https://www.jianshu.com/p/cbb2f42f4353
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞