handler 源码分析

handler
Looper 轮询器
MessageQueue 消息对象

1 主线程在一创建的时候就会调用,    public static void prepareMainLooper() {}构造方法。
    public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

2 在prepareMainLooper(){} 内部调用了 prepare(false);方法,这就是在子线程中new Handler()会抱错的关键

    prepare(quitAllowed) {}方法里面设置了一个Looper对象,如果已经有了 Looper 对象,会抛出异常 Only one Looper may be created per thread
    所以说一个 Handler只能有一个Looper对象
    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));//创建一个 Looper构造器
    }

3 在 Looper 的构造器中
    private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);//创建了 MessageQueue对象
        mRun = true;
        mThread = Thread.currentThread();//线程对象
    }

4 但是在 handler(){}的源码构造方法中
    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 that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

5 查看 Looper.myLooper();
    public static Looper myLooper() {
        return sThreadLocal.get();//返回的是一个 Looper对象,这里就跟 2的结果一样了
    }
所以在4 中抛出异常,跟2 也一样了
        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can‘t create handler inside thread that has not called Looper.prepare()");
        }
所以敢肯定(1 2 3)的原理就是主线程 Handler的工作原理
而 (4 5)就是我们手动创建 Handler的时候的工作原理。

handler.sendMessage(msg);他做的是将消息入队操作
6 经过源码跟踪,会发现在调用enqueueMessage(){}构造方法的时候,所做的事情就是将消息就行,入栈处理
   private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);//注意这里,想必从字面意思理解,enqueueMessage就是入栈的意思吧
    }

7 看enqueueMessage()所做的事情
    final boolean enqueueMessage(Message msg, long when) {
        if (msg.isInUse()) {
            throw new AndroidRuntimeException(msg + " This message is already in use.");
        }
        if (msg.target == null) {
            throw new AndroidRuntimeException("Message must have a target.");
        }

        boolean needWake;
        synchronized (this) {
            if (mQuiting) {
                RuntimeException e = new RuntimeException(
                        msg.target + " sending message to a Handler on a dead thread");
                Log.w("MessageQueue", e.getMessage(), e);
                return false;
            }

            msg.when = when;
            Message p = mMessages;
            if (p == null || when == 0 || when < p.when) {
                // New head, wake up the event queue if blocked.
                msg.next = p;
                mMessages = msg; //将消息对象的引用赋值给 Message
                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; //将消息对象的引用赋值给 Message
            }
        }
        if (needWake) {
            nativeWake(mPtr);
        }
        return true;
    }
8 那么问题来了,消息引用都传递给Message对象了,那是如何从 Message中吧消息分发出去,并响应呢?这就得看 Looper的源码中的 public static void loop() {}方法
其实 loop就是一个轮询器,在不断的从  MessageQueue中获取消息,可以看 loop()中的 Message msg = queue.next(); 内部实现源码,next() 方法就是消息队列的出队方法。不过由于这个方法的代码稍微有点长,我就不贴出来了,它的简单逻辑就是如果当前MessageQueue中存在mMessages(即待处理消息),就将这个消息出队,然后让下一条消息成为mMessages,否则就进入一个阻塞状态,一直等到有新的消息入队
    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;

        // Make sure the identity of this thread is that of the local process,
        // and keep track of what that identity token actually is.
        Binder.clearCallingIdentity();
        final long ident = Binder.clearCallingIdentity();

        for (;;) {//天呐,在这里居然是 for的空循环
            //queue.next() 出现了,有兴趣的可以点进去看看
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }

            // This must be in a local variable, in case a UI event sets the logger
            Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }

            msg.target.dispatchMessage(msg);//我们又发现了什么?对,msg.target代表的是Handler,调用了dispatchMessage方法
            // 这样我相信大家就都明白了为什么handleMessage()方法中可以获取到之前发送的消息了吧!
            if (logging != null) {
                logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
            }

            // Make sure that during the course of dispatching the
            // identity of the thread wasn‘t corrupted.
            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.recycle();
        }
    }
时间: 2024-07-29 14:54:48

handler 源码分析的相关文章

Handler源码分析

对于Handler搞android的都熟悉,大概原理也知道,可能很多开发者也看过源码,本人也看过源码,但是一直没有系统的分析过,总结过,今天来一波对Handler的源码分析,本文需要读者了解handler的基本原理,如果不了解请参考Handler消息传递机制! 废话不在多说,直接开整!!! 看官:博主,从哪里开始分析呢? 博主:嗯,咱们就从Message message = Message.obtain();开始入手 然我们进入Message找到obtain方法: /** * Return a

简略的Handler源码分析

相关源码 framework/base/core/java/andorid/os/Handler.java framework/base/core/java/andorid/os/Looper.java framework/base/core/java/andorid/os/Message.java framework/base/core/java/andorid/os/MessageQueue.java libcore/luni/src/main/java/java/lang/ThreadLo

Android异步消息传递机制源码分析&amp;&amp;相关知识常被问的面试题

1.Android异步消息传递机制有以下两个方式:(异步消息传递来解决线程通信问题) handler 和 AsyncTask 2.handler官方解释的用途: 1).定时任务:通过handler.postDelay(Runnable r, time)来在指定时间执行msg. 2).线程间通信:在执行较为耗时操作的时候,在子线程中执行耗时任务,然后handler(主线程的)把执行的结果通过sendmessage的方式发送给UI线程去执行用于更新UI. 3.handler源码分析 一.在Activ

Android之Handler源码深入解析

闲着没事,就来看看源码,看看源码的各种原理,会用只是简单的,知道为什么才是最牛逼的. Handler源码分析那,从使用的步骤来边用边分析: 1.创建一个Handler对象:new Handler(getMainLooper(),this); 这是我常用的一个方式,getMainLooper是获取主线程的Looper,this则是实现CallBack的接口 看一下Handler的构造函数 public Handler() { this(null, false); } public Handler(

Android之Handler源码深入分析

闲着没事,就来看看源码,看看源码的各种原理,会用只是简单的,知道为什么才是最牛逼的. Handler源码分析那,从使用的步骤来边用边分析: 1.创建一个Handler对象:new Handler(getMainLooper(),this); 这是我常用的一个方式,getMainLooper是获取主线程的Looper,this则是实现CallBack的接口 看一下Handler的构造函数 public Handler() { this(null, false); } public Handler(

Android异步消息处理 Handler Looper Message关系源码分析

# 标签: 读博客 对于Handler Looper Message 之前一直只是知道理论,知其然不知所以然,看了hongyang大神的源码分析,写个总结帖. 一.概念.. Handler . Looper .Message 这三者都与Android异步消息处理线程相关的概念. 异步消息处理线程启动后会进入一个无限的循环体之中,每循环一次,从其内部的消息队列中取出一个消息,然后回调相应的消息处理函数,执行完成一个消息后则继续循环.若消息队列为空,线程则会阻塞等待. 说了这一堆,那么和Handle

Handler机制.源码分析

Handler机制的原理 : Android提供了handler 和 looper 来满足线程之间的通信 Handler是先进先出的原则 一个线程可以产生一个looper对象,由它去管理线程里面消息队列 MessageQueue Handler 你可以构造handler对象来与looper沟通.可以发送消息 和处理消息 MessageQueue 用来存放线程放入的消息 线程 一般值的是主线程 UIthread Android启动程序的时候会替他建立一个MessageQueue   .Handle

Android -- 消息处理机制源码分析(Looper,Handler,Message)

android的消息处理有三个核心类:Looper,Handler和Message.其实还有一个Message Queue(消息队列),但是MQ被封装到Looper里面了,我们不会直接与MQ打交道,因此我没将其作为核心类.下面一一介绍: Looper Looper的字面意思是“循环者”,它被设计用来使一个普通线程变成Looper线程.所谓Looper线程就是循环工作的线程.在程序开发中(尤其是GUI开发中),我们经常会需要一个线程不断循环,一旦有新任务则执行,执行完继续等待下一个任务,这就是Lo

【Android】Handler、Looper源码分析

一.前言 源码分析使用的版本是 4.4.2_r1. Handler和Looper的入门知识以及讲解可以参考我的另外一篇博客:Android Handler机制 简单而言:Handler和Looper是对某一个线程实现消息机制的重要组成部分,另外两个重要元素是Message和MessageQueue,通过这四个类,可以让某个线程具备接收.处理消息的能力. 二.源码剖析 虽然只有四个类,而且这里只是剖析其中两个,但是也不能独立分析,必须组合进行解析.切入点是类Looper的注释中的一段示例代码: 1