从源码角度深入理解Handler
为了获得良好的用户体验,Android不允许开发者在UI线程中调用耗时操作,否则会报ANR异常,很多时候,比如我们要去网络请求数据,或者遍历本地文件夹都需要我们在新线程中来完成,新线程中不能更新UI,一个常规的解决方法就是在主线程中实例化一个Handler,在新线程中将消息封装在一个Message中,发送到主线程中,然后主线程来更新界面。这些都很简单,我们就不多说了,今天我主要想通过阅读源码来理解Handler,Looper之间的关系。
缘起
促使我去看Handler源码是由于在公司的开发中遇到的一个问题,一位同事在一个非UI线程中实例化Handler,结果程序一启动就崩溃,当时来问我,我以前也没遇到过,不知道是什么原因,但是我发现这个问题是由于新线程导致的,就是不能在新线程中创建Handler,但是究竟是什么原因,当时并没有发现。
上下求索
这周时间充裕,决定看一下原因,通过阅读源码来彻底了解Handler的工作机制。
首先,会崩溃的代码是这样的:
        new Thread(new Runnable() {
            @Override
            public void run() {
                mHandler = new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        switch (msg.what) {
                        case 0:
                            Log.i("lenve", msg.obj.toString());
                            break;
                        default:
                            break;
                        }
                    }
                };
            }
        }).start();
报的错是这样的: 
说是Can’t create handler inside thread that has not called Looper.prepare(),就是说呀不能在没有调用Looper.prepare的线程中创建Handler,那么我们在创建之前如果调用Looper.prepared(),结果又会怎么样呢?
好吧,那么就在创建Handler之前加上一句Looper.prepared(),这个时候应用不崩溃了,而且日志也能如期打印出来,代码如下:
        new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                mHandler = new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        switch (msg.what) {
                        case 0:
                            Log.i("lenve", msg.obj.toString());
                            break;
                        default:
                            break;
                        }
                    }
                };
            }
        }).start();
那么Looper.prepare()究竟做了什么?我们先来看看Handler的构造方法,代码如下:
    /**
     * Default constructor associates this handler with the {@link Looper} for the
     * current thread.
     *
     * If this thread does not have a looper, this handler won't be able to receive messages
     * so an exception is thrown.
     */
    public Handler() {
        this(null, false);
    }
看代码之前我们先来看看注释,说是默认的构造方法将这个Handler与当前的Thread关联,如果当前的Thread没有一个Looper,那么这个Handler不能接收消息,会抛出一个异常。然后看看代码,还是很简单的,只有一句,this(null,false);这是调用了另外一个有两个参数的构造方法,那我们就再看看这个有两个参数的构造函数:
    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;
    }
这个构造函数有两个参数,第一个参数是回调函数,这个不用多说,第二参数是说这个Handler是不是异步的,很明显,如果我们使用了无参构造方法来获得一个Handler实例,那么这个Handler不是异步的。那么这个构造函数中有一句是获得一个Looper对象的,如果获得的值为null,那么就会抛出一个异常,这个抛出的异常就是我们刚才看到的那么异常,看来问题就出在mLooper = Looper.myLooper();这句里。那我们看看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() {
        return sThreadLocal.get();
    }
注释说的很明白了,返回一个和当前Thread关联的Looper对象,如果当前Thread没有关联一个Looper对象,那么就会返回一个null。这里之所以会返回一个null是因为TheadLocal创建之后就没有执行过set方法,所以它根本就不会有Looper对象。那我们看看Looper.prepare()究竟做了什么让Handler可以正常使用了。 
源码如下:
    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));
    }
当我们执行prepare函数时,它又会调用它的重载函数,在这个重载函数中,如果当前Thead已经有了一个Looper,那么再次调用就会抛出一个异常,这也是为什么我们常说一个线程中只有一个Looper,如果当前线程中没有Looper,那么就会创建一个新的Looper给它。
这下总算弄明白了,为什么在新线程中使用Handler一定要先调用Looper.prepare(),这个时候有的童鞋可能会有疑问,什么我们在UI线程中使用Handler不用先调用一下Looper.prepare()? 
这里我们得看看ActivityThread类中的相关方法
    public static void main(String[] args) {
        SamplingProfilerIntegration.start();
        // CloseGuard defaults to true and can be quite spammy.  We
        // disable it here, but selectively enable it later (via
        // StrictMode) on debug builds, but using DropBox, not logs.
        CloseGuard.setEnabled(false);
        Environment.initForCurrentUser();
        // Set the reporter for event logging in libcore
        EventLogger.setReporter(new EventLoggingReporter());
        Security.addProvider(new AndroidKeyStoreProvider());
        // Make sure TrustedCertificateStore looks in the right place for CA certificates
        final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
        TrustedCertificateStore.setDefaultUserDirectory(configDir);
        Process.setArgV0("<pre-initialized>");
        Looper.prepareMainLooper();
        ActivityThread thread = new ActivityThread();
        thread.attach(false);
        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }
        AsyncTask.init();
        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }
        Looper.loop();
        throw new RuntimeException("Main thread loop unexpectedly exited");
    }
在ActivityThread类的main方法中调用了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.  See also: {@link #prepare()}
     */
    public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }
最后的最后,还有调用了我们前文说的prepare方法。也就是说在UI线程中,不用我们自己创建Looper,系统会自动为我们添加一个Looper。
说到这里,第一个问题总算解决了,下面我们就要看看消息的发送流程了。 
当我们调用sendMessage方法时,经过一路追踪,最后来到了这里:
    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);
    }
先是一个Message队列,这个mQueue在我们创建一个Looper对象的时候就被new出来了。最后返回的这个东西是把一个Message放入Message队列中,我们再看看这个入队的方法:
    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }
注意这里有个msg.target = this;把当前的Handler交给了msg.target,这里是个伏笔,下文我们会用到这个。继续往下看,这个是MessageQueue类中的enqueueMessage方法:
    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;
                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;
            }
        }
        if (needWake) {
            nativeWake(mPtr);
        }
        return true;
    }
这是关于入队操作,出队操作则在Looper类的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;
        // 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 (;;) {
            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);
            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();
        }
    }
这里会不断的读消息,读到消息后调用msg.target.dispatchMessage(msg);这个msg.target就是我们前面说的那个Handler,也就是我们发消息的Handler,这个时候会调用Handler的dispatchMessage(Messge msg)这个方法。在看看这个方法:
    /**
     * Subclasses must implement this to receive messages.
     */
    public void handleMessage(Message msg) {
    }
    /**
     * Handle system messages here.
     */
    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }
在dispatchMessage方法中,最终会调用handleMessage(msg);而handleMessage();的方法体是空的,原因是这个方法是由我们自己来实现的。
转了好大一圈,终于回来了。
另外我们有的时候会用到Handler的post方法,这个方法可以让我们在非UI线程中更新UI,看看源码,如下:
    public final boolean post(Runnable r)
    {
       return  sendMessageDelayed(getPostMessage(r), 0);
    }
getPostMessage方法会给msg一个回调函数:
    private static Message getPostMessage(Runnable r) {
        Message m = Message.obtain();
        m.callback = r;
        return m;
    }
这样,当我们在最后一步调用dispatchMessage方法时,就不会走上文说的流程,而是会跑到这个方法里来:
    private static void handleCallback(Message message) {
        message.callback.run();
    }
可以看出,最后调用了run()方法。
还有一个runOnUiThread,这个也可以在非UI线程中更新UI,看看代码:
    public final void runOnUiThread(Runnable action) {
        if (Thread.currentThread() != mUiThread) {
            mHandler.post(action);
        } else {
            action.run();
        }
    }
这个逻辑也很简单,如果当前的Thread是UIThread,则直接调用上面说的post 方法,如果是UIThread,则直接run()方法中的代码。
所以我个人觉得这两个方法都是有点折腾,最好就是统一在新线程中发消息,UI线程收消息,然后更新界面。反正这两个方法的原理本身也是这样。
好了,就这么多吧。
版权声明:本文为博主原创文章,未经博主允许不得转载。若有错误地方,还望批评指正,不胜感激。
从源码角度深入理解Handler的更多相关文章
- 从源码角度深入理解Toast
		
Toast这个东西我们在开发中经常用到,使用也很简单,一行代码就能搞定: 1: Toast.makeText(", Toast.LENGTH_LONG).show(); 但是我们经常会遇到这 ...
 - 从源码角度彻底理解ReentrantLock(重入锁)
		
目录 1.前言 2.AbstractQueuedSynchronizer介绍 2.1 AQS是构建同步组件的基础 2.2 AQS的内部结构(ReentrantLock的语境下) 3 非公平模式加锁流程 ...
 - java并发系列(四)-----源码角度彻底理解ReentrantLock(重入锁)
		
1.前言 ReentrantLock可以有公平锁和非公平锁的不同实现,只要在构造它的时候传入不同的布尔值,继续跟进下源码我们就能发现,关键在于实例化内部变量sync的方式不同,如下所示: /** * ...
 - 从源码角度深入理解LayoutInflater
		
关于LayoutInflater,在开发中经常会遇到,特别是在使用ListView的时候,这个几乎是必不可少.今天我们就一起来探讨LayoutInflater的工作原理. 一般情况下,有两种方式获得一 ...
 - 从源码角度理解Java设计模式——装饰者模式
		
一.饰器者模式介绍 装饰者模式定义:在不改变原有对象的基础上附加功能,相比生成子类更灵活. 适用场景:动态的给一个对象添加或者撤销功能. 优点:可以不改变原有对象的情况下动态扩展功能,可以使扩展的多个 ...
 - 从源码角度了解SpringMVC的执行流程
		
目录 从源码角度了解SpringMVC的执行流程 SpringMVC介绍 源码分析思路 源码解读 几个关键接口和类 前端控制器 DispatcherServlet 结语 从源码角度了解SpringMV ...
 - Android -- 带你从源码角度领悟Dagger2入门到放弃(二)
		
1,接着我们上一篇继续介绍,在上一篇我们介绍了简单的@Inject和@Component的结合使用,现在我们继续以老师和学生的例子,我们知道学生上课的时候都会有书籍来辅助听课,先来看看我们之前的Stu ...
 - 从template到DOM(Vue.js源码角度看内部运行机制)
		
写在前面 这篇文章算是对最近写的一系列Vue.js源码的文章(https://github.com/answershuto/learnVue)的总结吧,在阅读源码的过程中也确实受益匪浅,希望自己的这些 ...
 - Android进阶:二、从源码角度看透 HandlerThread 和 IntentService 本质
		
上篇文章我们讲日志的存储策略的时候用到了HandlerThread,它适合处理"多而小的任务"的耗时任务的时候,避免产生太多线程影响性能,那这个HandlerThread的原理到底 ...
 
随机推荐
- NOIP 2011 提高组 计算系数
			
有二项式定理 `\left( a+b\right) ^{n}=\sum _{r=0}^{n}\left( \begin{matrix} n\\ r\end{matrix} \right) a^{n-r ...
 - IronPython脚本调用C#dll示例
			
上篇Python脚本调用C#代码数据交互示例(hello world)介绍了与C#紧密结合的示例,这里还将提供一个与C#结合更紧密的示例,直接调用C#编写的DLL. 我们还是沿用了上篇文章的 ...
 - mysql优化案例
			
MySQL优化案例 Mysql5.1大表分区效率测试 Mysql5.1大表分区效率测试MySQL | add at 2009-03-27 12:29:31 by PConline | view:60, ...
 - [转贴] C/C++中动态链接库的创建和调用
			
DLL 有助于共享数据和资源.多个应用程序可同时访问内存中单个DLL 副本的内容.DLL 是一个包含可由多个程序同时使用的代码和数据的库.下面为你介绍C/C++中动态链接库的创建和调用. 动态连接库的 ...
 - C#文本处理(String)学习笔记
			
摘要:string是编程中使用最频繁的类型.一个string表示一个恒定不变的字符序列集合.string类型直接继承自object,故他是一个引用类型,也就是说线程的堆栈上不会有任何字符串(直接继承自 ...
 - [ZOJ 3631] Watashi's BG
			
Watashi's BG Time Limit: 3 Seconds Memory Limit: 65536 KB Watashi is the couch of ZJU-ICPC Team ...
 - 第一章 用three.js创建你的第一个3D场景
			
第一章 用three.js创建你的第一个3D场景 到官网下载three.js的源码和示例. 创建HTML框架界面 第一个示例的代码如下: 01-basic-skeleton.html 位于 Learn ...
 - 英语之路 zt
			
各位为英语而郁闷的兄弟姐妹们: 自从考完GRE和TOEFL以后,心有所感,本想写点心得,但是因为太懒没写成.今日风雨如晦,心中又有所感,于是一舒笔墨,写下我学英语的方法.俺知道有很多兄弟姐妹们和曾经的 ...
 - windows下面配置jdk环境变量
			
在环境变量中添加如下: Path D:\Program Files\Java\jdk1.6.0_26\binJAVA_HOME D:\Program Files\Java\jdk1.6.0_26CLA ...
 - 升级到 ExtJS 5的过程记录
			
升级到 ExtJS 5的过程记录 最近为公司的一个项目创建了一个 ExtJS 5 的分支,顺便记录一下升级到 ExtJS 5 所遇到的问题以及填掉的坑.由于 Sencha Cmd 的 sencha ...