Android-Handler机制

本文主要讲解Android线程间通信的一种方式,即Handler机制。

子线程使用Handler

相信很多童鞋有过子线程中new Handler时系统报错的经历

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:203)
at android.os.Handler.<init>(Handler.java:117)

报错的原因是,在没有调用过Looper.prepare()的子线程中不能new Handler。

正确的使用方式是

new Thread() {                            
    @Override                             
    public void run() {                                                               
        Looper.prepare();                 
        Looper looper = Looper.myLooper();
        Looper.loop();
        Handler handler = new Hander();                                                                                         
    }                                     
}.start();                                

这到底是什么原因,Handler的构造函数做了什么操作,Looper.prepare()做了什么处理,我们接着往下看。

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

这里可以很清晰的看到抛出的异常

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

接着看Looper中的实现。

Looper

public final class Looper {

    ...

    // sThreadLocal.get() will return null unless you've called prepare().
    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<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();
    }
    
    ...
    
    /**
     * 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);
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }

              ...
              
            msg.recycleUnchecked();
        }
    }
}

上面贴了Looper的一些主要代码,主要工作流程如下:

  1. prepare() 中就做了一件事,用ThreadLoacl在当前Thread中保存了一份Looper实例对象,并保证了每个线程只拥有一个Looper实例对象,保证循环中的消息队列的唯一性。有兴趣的童鞋可以看看这个ThreadLocal类详解

  2. myLooper() 就是将当前线程中保存的Looper对象返回。

  3. loop() 开启MessageQueue中消息列表的循环处理,若当前无消息则阻塞,有消息则发送。

Looper和Handler的联系

public class Handler { 

    ...

    public final boolean post(Runnable r){
       return  sendMessageDelayed(getPostMessage(r), 0);
    }
    
    public final boolean postAtTime(Runnable r, long uptimeMillis){
        return sendMessageAtTime(getPostMessage(r), uptimeMillis);
    }
    
    public final boolean postAtTime(Runnable r, Object token, long uptimeMillis){
        return sendMessageAtTime(getPostMessage(r, token), uptimeMillis);
    }
    
    public final boolean postDelayed(Runnable r, long delayMillis){
        return sendMessageDelayed(getPostMessage(r), delayMillis);
    }
    
    public final boolean postAtFrontOfQueue(Runnable r){
        return sendMessageAtFrontOfQueue(getPostMessage(r));
    }

    public final boolean sendMessage(Message msg){
        return sendMessageDelayed(msg, 0);
    }

    public final boolean sendEmptyMessage(int what){
        return sendEmptyMessageDelayed(what, 0);
    }

    public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
        Message msg = Message.obtain();
        msg.what = what;
        return sendMessageDelayed(msg, delayMillis);
    }

    public final boolean sendEmptyMessageAtTime(int what, long uptimeMillis){
        Message msg = Message.obtain();
        msg.what = what;
        return sendMessageAtTime(msg, uptimeMillis);
    }

    public final boolean sendMessageDelayed(Message msg, long delayMillis){
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }

    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);
    }
    
    public final boolean sendMessageAtFrontOfQueue(Message msg) {
        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, 0);
    }
    
    
    //消息入队
    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }
    
    ...
}

上面这些方法,到最后调用就是个方法

    //消息入队
    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

在开头的Hanlder构造函数里我们可以知道,这里所用的queue就是Looper中的queue,也就是Handler中发送的消息其实入到了Looper中,两者在这里关联起来。

这也就解释了为什么Handler实例化之前需要Looper先行prepare。

这里先说明一点,post(Runnable r)等一系列方法中,最后Runnable回调都会被设置到msg中的callback中,看下面这个2方法

private static Message getPostMessage(Runnable r) {               
    Message m = Message.obtain();                                 
    m.callback = r;                                               
    return m;                                                     
}                                                                 
                                                                  
private static Message getPostMessage(Runnable r, Object token) { 
    Message m = Message.obtain();                                 
    m.obj = token;                                                
    m.callback = r;                                               
    return m;                                                     
}                                                                 

这里特做说明,下文会用到这点。

Hanlder和Message的联系

上面看到handler消息入队列的时候会给msg.target赋值为this,也就是当前handler实例对象。

在Looper的loop()中message从MessageQueue取出,并调用 msg.target.dispatchMessage(msg),并传递给他的target进行处理,也就是哪个h
andler发送的消息,最后又经由谁来处理。

来看一下Handler的dispatchMessage()

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

private static void handleCallback(Message message) {
    message.callback.run();                          
}                                                    

/**                                                    
 * Subclasses must implement this to receive messages. 
 */                                                    
public void handleMessage(Message msg) {  
    //用户自行实现的消息处理          
}                                                      

上面可以清晰的看到

  1. 如果msg有回调,则msg的回掉先行处理msg;
  2. 如果Handler实例化时有传入Callback,则这个Callback处理msg;
  3. 最后由用户自行实现的消息处理方式处理msg。

从上面可以看出,如果msg没有回调,则都会回到Handler所在线程进行处理。这也就是可以利用Handler更新UI的原理。

好了,Hanlder机制的整体流程如下图所示(图片来源网络,侵删):

handler机制图解.png

文章看完了,肯定有童鞋有疑问,为什么在UI线程new Handler时不需要先进行Looper.perpare(),原因是系统自动帮你完成了UI线程Looper.perpare()操作。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270

推荐阅读更多精彩内容