Handler 机制 源码分析

看之前先问自己下面几个问题:


  1. Message 是怎么获取到消息对象的
  2. 消息是怎么加入到消息队列中的,又是怎么被取出来的
  3. 到底是怎么实现子线程和主线程的通信的
  4. Handler sendMessage 是把消息发送到哪里了
  5. Handler 处理消息的方法有几种

消息传递机制的核心类:

Handler

Message

MessageQueue

Looper


下面是自己看的一些源码

  • Message 是怎么获取到消息对象的

    **Message.java**
    
    通过 Message.obtain();
    
/**
  * Return a new Message instance from the global pool. Allows us to
  * avoid allocating new objects in many cases.
  */
        public static Message obtain() {
            synchronized (mPoolSync) {
                if (mPool != null) {
                    Message m = mPool;
                    mPool = m.next;
                    m.next = null;
                    mPoolSize--;
                    return m;
                }
            }
            return new Message();
        }
  • 是通过一个单链表来维护的,如果消息池不为空,就把已有的消息赋值给 m ,然后把下一条消息变成第一条消息。
  • 当消息池为空的时候,再去 new Message();

  • 在创建 Handler 对象的时候,在其构造方法中就可以获得 Looper 和 MessageQueue 对象

    **Handler.java**
    
/**
         * Default constructor associates this handler with the queue for the
         * current thread.
         *
         * If there isn't one, this handler won't be able to receive messages.
         */
        public Handler() {

          ......

            //获取到一个 Looper
            mLooper = Looper.myLooper();

            if (mLooper == null) {
                throw new RuntimeException(
                    "Can't create handler inside thread that has not called Looper.prepare()");
            }

            //获取到一个 MessageQueue
            mQueue = mLooper.mQueue;
            mCallback = null;
        }

        来看看 Looper.myLooper()做了些什么

        Looper.java

        /**
         * Return the Looper object associated with the current thread.  Returns
         * null if the calling thread is not associated with a Looper.
         */
        public static final Looper myLooper() {
            return (Looper)sThreadLocal.get();
        }

ThreadLocal: 线程内单例 ThreadLocal.get(); 在哪个线程中set,get拿的就是哪个线程中的对象

  sThreadLocal 有get 方法大概就有set方法,去查找一下
/** Initialize the current thread as a looper.
 * This gives you a chance to create handlers that then reference
 * this looper, before actually starting the loop. Be sure to call
 * {@link #loop()} after calling this method, and end it by calling
 * {@link #quit()}.
 */
public static final void prepare() {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");//一个线程只能有一个 Looper
        }
        sThreadLocal.set(new Looper());
    }

在这里看出来 直接 new 出了一个 Looper();并且一个线程只能有一个 Looper Looper
在哪个线程new就会存在在哪个线程 在 Looper 的构造方法中 new 出了 MessageQueue

  private Looper() {
        mQueue = new MessageQueue();
        mRun = true;
        mThread = Thread.currentThread();
   }

Looper.prepare();就是向线程中添加了一个looper, sThreadLocal.set(new Looper());

    * 上面的prepare方法是在prepareMainLooper 中调用的
    /** Initialize the current thread as a looper, marking it as an application's main 
      *  looper. The main looper for your application is created by the Android environment,
      *  so you should never need to call this function yourself.
      * {@link #prepare()}
      */

        public static final void prepareMainLooper() {
            prepare();
            setMainLooper(myLooper());//设置一个主线程的轮询器
            if (Process.supportsProcesses()) {
                myLooper().mQueue.mQuitAllowed = false;
            }
        }

prepareMainLooper()方法是在 ActivityThread 类的 main
方法中调用的在应用启动时,主线程要被启动,ActivityThread
会被创建,在此类的main方法中,在主线程调用任何方法,执行都会跑到主线程

    ActivityThread.java
//主线程
public static void main(String[] args) {

    Looper.prepareMainLooper();//Looper存在在主线程,然后不断的去轮询读消息

                ....

    Looper.loop();//不断的轮询读消息
}
    - Looper.loop();方法中有一个死循环,不断的从消息队列中取消息
        /**
         *  Run the message queue in this thread. Be sure to call
         * {@link #quit()} to end the loop.
         */
        public static final void loop() {
            Looper me = myLooper();
            MessageQueue queue = me.mQueue;

            ......

            while (true) {

                //取出消息队列中的下一条消息,可能会阻塞
                Message msg = queue.next(); // might block

                if (msg != null) {
                    if (msg.target == null) {// msg.target 其实就是一个 handler 对象,如果没有handler来处理,直接返回
                        // No target is a magic identifier for the quit message.
                        return;
                    }

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

                    msg.recycle();
                }
            }
        }
  • 关于取消息时的阻塞

Linux 的进程间通信机制: Pipe(管道)
原理:在内存中有一个特殊的文件,这个文件有两个句柄(引用),一个是读句柄,一个是写句柄。主线程 Looper
从主线程读取消息,当读取完所有的消息时,会进入睡眠状态,主线程阻塞。当子线程往消息队列中发送消息,并且往管道文件中写入数据,主线程马上被唤醒,从管道文件中读取数据。主线程被唤醒就是为了读取数据,当再次读取完毕之后,再次进入休眠状态

Handler 发消息 sendMessage() … sendEmptyMessage() … sendMessageDelay()… 其实最后都调用了同一个方法

Handler.java
public boolean sendMessageAtTime(Message msg, long uptimeMillis){
      boolean sent = false;
       MessageQueue queue = mQueue;
       if (queue != null) {
           msg.target = this;//在拿Handler发消息的时候,把Handler保存到了Message里面了,this就是handler对象,所以msg.target也是handler对象
           sent = queue.enqueueMessage(msg, uptimeMillis);//把消息msg放入到了消息队列(MessageQueue)中
       }
       else {
         ......
       }
       return sent;
}

MessageQueue.java

//enqueueMessage 把消息重新排列后放入消息队列中
            //排序的方式:根据消息队列中是否有消息,和消息时间的对比,之后放入队列。
final boolean enqueueMessage(Message msg, long when) {
       if (msg.when != 0) {
           throw new AndroidRuntimeException(msg
                   + " This message is already in use.");
       }

          msg.when = when;

          Message p = mMessages; // 队列中的第一条消息
          // 如果消息为空,或者时间为0,或者时间比第一条消息的时间要短,就把这条消息放在队列中的第一个位置
          if (p == null || when == 0 || when < p.when) { 
              msg.next = p;
              mMessages = msg;
              needWake = mBlocked; // new head, might need to wake up
          } else {
            //如果消息不为空,并且时间不比第一条消息的时间短。就把该消息插入到合适的队列中的位置。
              Message prev = null;
              //循环找出当前消息的位置
              while (p != null && p.when <= when) {
                  prev = p;
                  p = p.next;//当前消息要插到 prev 消息后面。
              }
              msg.next = prev.next;
              prev.next = msg;
              needWake = false; // still waiting on head, no need to wake up
          }
      }

        //唤醒主线程
   if (needWake) {
       nativeWake(mPtr);
   }

      return true;
}

此时,消息队列中如果已经有了消息,那么 Looper.loop() 就会不断的去轮询,通过 queue.next() 拿到消息,然后通过
handler 分发处理

Looper.loop()
//获取消息队列的消息
 Message msg = queue.next(); // might block
 ...
//分发消息,消息由哪个handler对象创建,则由它分发,并由它的handlerMessage处理  
msg.target.dispatchMessage(msg);
  • msg的target属性,用于记录该消息是由哪个 Handler 创建的,在obtain中赋值。

    • Handler 处理消息的几种方法
/**
  * Handle system messages here.
  */

 public void dispatchMessage(Message msg) {
     if (msg.callback != null) {
         handleCallback(msg);//下面的第 2 种方式。
     } else {
         if (mCallback != null) {
             if (mCallback.handleMessage(msg)) { // 下面的第 3 种方式
                 return;
             }
         }
         handleMessage(msg);//这个就是下面的第 1 种方式
     }
 }



//1,重写 handleMessage()方法进行处理。我们最常用的方法

Handler handler = new Handler(){

public void handleMessage(android.os.Message msg) {
        //处理相应的逻辑
    ......
    };
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Message msg = Message.obtain();
    handler.sendMessage(msg);
}


//2,封装一个 CallBack 的 Runnable 任务,在这个任务中处理数据

Handler handler = new Handler();

Runnable callback = new Runnable() {

    @Override
    public void run() {
        //在这里处理一些逻辑
        ......
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Message msg = Message.obtain(handler, callback);
    handler.sendMessage(msg);

}

//3, new 一个 Handler 的 CallBack ,重写 handleMessage 方法。
//和第 1 种方式中 的 handleMessage 方法哪个优先级高呢?从dispatchMessage 方法中可以看出来。如果下面的 handleMessage 返回值为 true,
//那么将不会执行 第一种方式的 handleMessage 方法。

Handler.Callback callback = new Handler.Callback(){

public boolean handleMessage(Message msg) {
        //处理相应逻辑
    ......
        return false;
    };
};

Handler handler = new Handler();


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Message msg = Message.obtain();
    handler.sendMessage(msg);

}
  • 处理方式的优先级从分发消息的方法可以看的出来: 2 > 3 > 1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_kayce

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值