Android之浅谈:带你手撕Handler来了解handler原理

前言

首先先祝大家2023年新年快乐呀!这篇文章打算讲handler原理,我相信handler原理已经被很多大佬写透过的东西,但是我想从一个不同的角度来写,从实践来了解handler原理。希望这篇文章能带给你来点收获。

Handler介绍

handler是Android一套消息传递机制,像在Andorid里AsyncTask、IntentService、activity生命周期控制等…都存在handler的身影,handler机制中有四个很重要的对象:

  • Handler 负责消息的发送和处理
  • MessageQueue 消息队列(虽然听名字数据结构像是队列,但是实际上是单向链表)
  • Message 传递的消息
  • Looper 负责消息的轮询,并且将消息发送给持有该消息的handler(一个线程只能有一个looper)
1、实现handler

首先我们看下handler源码的构造函数

    public interface Callback {
        /**
         * @param msg A {@link android.os.Message Message} object
         * @return True if no further handling is desired
         */
        public boolean handleMessage(Message msg);
    }


    public Handler(Looper looper, Callback callback, boolean async) {
        mLooper = looper;
        mQueue = looper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

    public Handler(Callback callback, boolean async) {
        if (FIND_POTENTIAL_LEAKS) {
            final Class<? extends Handler> klass = getClass();
            if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
                    (klass.getModifiers() & Modifier.STATIC) == 0) {
                Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
                    klass.getCanonicalName());
            }
        }

        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;
        mCallback = callback;
        mAsynchronous = async;
    }

callback参数:回调handlerMessag ,我们将在handler所在的线程收到Message
looper参数:消息泵,handler将会与这个looper绑定,mQueue是一个Messagequeue,Messagequeue是looper的成员变量 ,可以看的出来如果没有looper将会报错 。
async:是否是异步消息

这里我们模仿源码实现简易handler类

public class Handler {
    private final MessageQueue mQueue;
    private Looper mLooper;

    public Handler(){
        Looper looper=Looper.myLooper();
        mLooper=looper;
        mQueue=looper.mQueue;
    }
    //发送消息
    public void sendMessage(Message message){
       message.target=this;
       mQueue.enqueueMessage(message);
    }
   //处理消息
    public void handleMessage(Message message) {
    }
}

2、实现Looper

我们以Looper.myLooper()作为入口看下Looper的源码

    /** 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 void prepare() {
        prepare(true);
    }

    private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper(quitAllowed));
    }
    /**
     * Return the Looper object associated with the current thread.  Returns
     * null if the calling thread is not associated with a Looper.
     */
    public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }

可以看的出如果要获得looper最终是要调prepare(boolean quitAllowed)这个函数,这里再次证明一个线程只能创建一个looper,这里就会有小伙伴问我在主线程明明没有调用Looper.prepare啊,其实在主线程ActivityThread已经自动帮我创建了,所以在其他线程需要Looper的话均需要手动调用Looper.prepare();

那Looper又是怎么作为消息泵,并且将消息传递给handler呢?我们来看Looper.loop的源码(有剪切)

    /**
     * Run the message queue in this thread. Be sure to call
     * {@link #quit()} to end the 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;
        ...
        ...
        for (;;) {
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }
         try {
                msg.target.dispatchMessage(msg);
                ...
            } 
         ...

可以看得出来Looper的消息轮询是一个死循环,且不断的调用 Message msg = queue.next() 从MessageQueue取消息,然后调用 msg.target.dispatchMessage(msg);这里的target即handler,这样将消息传递给handler了;

这里我们模仿源码实现简易Looper

public class Looper {
    //用于存放在该线程中的looper,确保一条线程只有一个looper,
    //当使用ThreadLocal维护变量时,ThreadLocal为每个使用该变量的线程提供独立的变量副本,
    //所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本
   private static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<>();
     MessageQueue mQueue;

     private Looper(){
         mQueue =new MessageQueue();
     }
    public static Looper myLooper(){
        return sThreadLocal.get();
    }
    public static void prepare(){
         if (null!=sThreadLocal.get()){
             throw new RuntimeException("Only one Looper may be created per thread");
         }
         sThreadLocal.set(new Looper());
    }

    public static void loop(){
         Looper looper=myLooper();
         if (looper==null){
             throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
         }
         MessageQueue queue=looper.mQueue;
         for (;;){
             Message next=queue.next();
             if (next==null||next.target==null){
                 continue;
             }
             next.target.handleMessage(next);
         }
    }
    public void quit(){
         mQueue.quit();
    }
}

3、实现MessageQueue

我就以上述queue.nxet()为切入点进入源码看一下

  Message next() {
        // Return here if the message loop has already quit and been disposed.
        // This can happen if the application tries to restart a looper after quit
        // which is not supported.
        final long ptr = mPtr;
        if (ptr == 0) {
            return null;
        }
        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        int nextPollTimeoutMillis = 0;
        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }

            nativePollOnce(ptr, nextPollTimeoutMillis);

            synchronized (this) {
                // Try to retrieve the next message.  Return if found.
                final long now = SystemClock.uptimeMillis();
                Message prevMsg = null;
                Message msg = mMessages;
                if (msg != null && msg.target == null) {
                    // Stalled by a barrier.  Find the next asynchronous message in the queue.
                    do {
                        prevMsg = msg;
                        msg = msg.next;
                    } while (msg != null && !msg.isAsynchronous());
                }
                if (msg != null) {
                    if (now < msg.when) {
                        // 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();
                        return msg;
                    }
                } else {
                    // No more messages.
                    nextPollTimeoutMillis = -1;
                }
                    // Process the quit message now that all pending messages have been handled.
                if (mQuitting) {
                    dispose();
                    return null;
                }

                // If first time idle, then get the number of idlers to run.
                // Idle handles only run if the queue is empty or if the first message
                // in the queue (possibly a barrier) is due to be handled in the future.
                if (pendingIdleHandlerCount < 0
                        && (mMessages == null || now < mMessages.when)) {
                    pendingIdleHandlerCount = mIdleHandlers.size();
                }
                if (pendingIdleHandlerCount <= 0) {
                    // No idle handlers to run.  Loop and wait some more.
                    mBlocked = true;
                    continue;
                }

                if (mPendingIdleHandlers == null) {
                    mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
                }
                mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
            }

            // Run the idle handlers.
            // We only ever reach this code block during the first iteration.
            for (int i = 0; i < pendingIdleHandlerCount; i++) {
                final IdleHandler idler = mPendingIdleHandlers[i];
                mPendingIdleHandlers[i] = null; // release the reference to the handler

                boolean keep = false;
                try {
                    keep = idler.queueIdle();
                } catch (Throwable t) {
                    Log.wtf(TAG, "IdleHandler threw exception", t);
                }

                if (!keep) {
                    synchronized (this) {
                        mIdleHandlers.remove(idler);
                    }
                }
            }

            // Reset the idle handler count to 0 so we do not run them again.
            pendingIdleHandlerCount = 0;

            // While calling an idle handler, a new message could have been delivered
            // so go back and look again for a pending message without waiting.
            nextPollTimeoutMillis = 0;
        }


这里看似很繁琐,其实可以大致流程为 nativePollOnce(ptr, nextPollTimeoutMillis);执行Native的消息机制,该方法会一直等待Native消息,其中 timeOutMillis参数为超时等待时间。如果为-1,则表示无限等待,直到有事件发生为止。如果值为0,则无需等待立即返回,所以主线程一直轮询是不会一直消耗cpu性能的,也不会造成卡顿,因为一有消息就会被唤醒。如果想进一步了解native消息机制可以看深入理解Java Binder和MessageQueue
接下来就是看 if (msg != null && msg.target == null) 是否有屏障消息,如果有就过滤掉同步消息直接执行就近的异步消息,代码再往下看就是时间是否到了消息等待的时候,到了则返回,接着往下看,这里涉及到空闲任务,当没有消息的时候,会执行一些空闲任务,例如GC,空闲任务执行完后nextPollTimeoutMillis又会重新置为0。

那MessageQueue里是怎么存消息的呢,当调用Handler发送消息的时候,不管是调用sendMessage,sendEmptyMessage,sendMessageDelayed还是其他发送一系列方法。最终都会调用 sendMessageAtTime(Message msg, long uptimeMillis),然而这个方法最后会调用enqueueMessage(Message msg, long when)。

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

 boolean enqueueMessage(Message msg, long when) {
            ...省略
        synchronized (this) {
            ...省略
            msg.markInUse();
            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;
                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;
    }

消息队列里没有消息或者无需等待、小于消息头的等待时间的时候直接将消息放在头部,否则将消息插入合适的位置(比较等待时间),如果触发needWake那么就会直接唤醒native的消息,这里的mptr是NativeMessageQueue对象然后返回的地址。

这里我们模仿实现简易MessageQueue

public class MessageQueue {
    //消息链表
    Message mMessage;
    private boolean isQuit;
    public void enqueueMessage(Message message){
          synchronized (this){
              if (isQuit){
                  return;
              }
              Message p=mMessage;
              if (null==p){
                  mMessage=message;
              }else {
                  Message prev;
                  for (;;){
                      prev =p;
                      p=p.next;
                      if (null==p){
                          break;
                      }
                  }
                  prev.next=message;
              }
              notify();//唤醒,模拟 nativeWake(mPtr);
          }
    }
    public Message next(){
        synchronized (this){
            Message message;
            for (;;){
                if (isQuit){
                    return null;
                }
                message=mMessage;
                if (null!=message){
                    break;
                }try {
                    wait(); //等待唤醒 模拟  nativePollOnce(ptr, nextPollTimeoutMillis);
                }catch (InterruptedException e  ){
                    e.printStackTrace();
                }
            }
            mMessage=mMessage.next;
            return message;
        }
    }
    public void  quit(){
        synchronized (this){
            isQuit=true;
            Message message=this.mMessage;
            while (null!=message){
                Message next=message.next;
                message.recycle();
                message=next;
            }
            notify();
        }
    }
}

4、实现Message

Message部分源码

    /*package*/ Handler target;

    /*package*/ Runnable callback;

    // sometimes we store linked lists of these things
    /*package*/ Message next;
  /**
     * Return a new Message instance from the global pool. Allows us to
     * avoid allocating new objects in many cases.
     */
    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();
    }

这里的target就是handler这样就可以同过message.target.handlMessage() 去让handler处理消息了,这里还有一个next,这样他在messageQueue里就可以产生一个消息的单向链表。这里还有一个变量池,有兴趣的小伙伴可以自行去了解下message的复用

这里我们模仿实现简易Message

public class Message {
    int what;
    Object object;
    Message next;
    Handler  target;
    public void  recycle(){
        object=null;
        next=null;
         target=null;
    }
}

这次我们分析和模拟handler机制算是完成了,让我们来看一下效果吧。

   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Looper.prepare(); //手动调用我们自己prepare方法
        final Handler handler=new Handler(){
            @Override
            public void handleMessage(Message message) { //处理消息
                Log.i("info1", "handleMessage: "+message.what);
            }
        };
        new Thread() {
            @Override
            public void run() {
                Message message=new Message();
                message.what=45;
                handler.sendMessage(message); //子线程里发送消息
            }
        }.start();
        Looper.loop(); //开启轮询
    }

链接;https://www.jianshu.com/p/fefd613893d7
作者:是takiku啊

如果你想要深入系统的学习Android Framework框架,这里可以分享一份《Android Framework源码开发揭秘》,其中记录了从系统启动流程到WMS全部源码解析,相信你能优秀地学习整个Framework框架。

因文章篇幅原因,只放了部分内容,完整版扫码免费领取!!

第一章 系统启动流程分析

  • 第一节 Android启动概览
  • 第二节 init.rc解析
  • 第三节 Zygote
  • 第四节 面试题

在这里插入图片描述

第二章 跨进程通信IPC解析

  • 第一节 Sercice 还可以这么理解
  • 第二节 Binder基础
  • 第三节 Binder应用
  • 第四节 AIDL应用(上)
  • 第五节 AIDL应用(下)
  • 第六节 Messenger原理及应用
  • 第七节 服务端回调
  • 第八节 获取服务(IBinder)
  • 第九节 Binder面试题全解析

在这里插入图片描述

第三章 Handler源码解析

  • 第一节 源码分析
  • 第二节 难点问题
  • 第三节 Handler常问面试题
  • 在这里插入图片描述

第四章 AMS源码解析

  • 第一节 引言
  • 第二节 Android架构
  • 第三节 通信方式
  • 第四节 系统启动系列
  • 第五节 AMS
  • 第六节 AMS 面试题解析

在这里插入图片描述

第五章 WMS源码解析

  • 第一节 WMS与activity启动流程
  • 第二节 WMS绘制原理
  • 第三节 WMS角色与实例化过程
  • 第四节 WMS工作原理

在这里插入图片描述

第六章 Surface源码解析

  • 第一节 创建流程及软硬件绘制
  • 第二节 双缓冲及SurfaceView解析
  • 第三节 Android图形系统综述
  • 在这里插入图片描述

第七章 基于Android12.0的SurfaceFlinger源码解析

  • 第一节 应用建立和SurfaceFlinger的沟通的桥梁
  • 第二节 SurfaceFlinger的启动和消息队列处理机制
  • 第三节 SurfaceFlinger 之 VSync(上)
  • 第四节 SurfaceFlinger之VSync(中)
  • 第五节 SurfaceFlinger之VSync(下)
  • 在这里插入图片描述

第八章 PKMS源码解析

  • 第一节 PKMS调用方式
  • 第二节 PKMS启动过程分析
  • 第三节 APK的扫描
  • 第四节 APK的安装
  • 第五节 PKMS之权限扫描
  • 第六节 静默安装
  • 第七节 requestPermissions源码流程解析

在这里插入图片描述

第九章 InputManagerService源码解析

  • 第一节 Android Input输入事件处理流程(1)
  • 第二节 Android Input输入事件处理流程(2)
  • 第三节 Android Input输入事件处理流程(3)

在这里插入图片描述

第十章 DisplayManagerService源码解析

  • 第一节 DisplayManagerService启动
  • 第二节 DisplayAdapter和DisplayDevice的创建
  • 第三节 DMS部分亮灭屏流程
  • 第四节 亮度调节
  • 第五节 Proximity Sensor灭屏原理
  • 第六节 Logical Display和Physical Display配置的更新

在这里插入图片描述

各位小伙伴们如果有需要这份《Android Framework源码开发揭秘》资料,扫码即可【免费领取】

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值