Android Handler分析

前言

Adnroid的消息机制主要是指Handler的运行机制。本次主要分析Android消息机制,主要分析包括Handler、MessageQueue、Looper等实现原理。

1、Handler是什么?

Handler是为了在工作线程中更新UI线程的机制,也是消息处理机制,包括消息的发送和消息的处理过程。

2、为什么要用Handler消息传递机制?

a.为什么Android系统不允许工作线程更新UI?

  • 1、因为ui控件不是线程安全的,多线程中并发访问可能会导致ui控件处于不可预期状态。

  • 2、如果对ui控件进行上锁机制,则会使ui空间操作变得复杂低效。也可能出现阻塞进程的执行。

  • 3、采用单线程模型处理ui,不用关心多线程问题,都在ui线程的消息队列中轮询处理。

    访问UI只能在主线程中进行。若在工作线程中访问UI就会抛出异常。在Adnroid源码frameworks/base/core/java/android/view/ViewRootImpl.java中的checkThread()来检查。

void checkThread() {
    if (mThread != Thread.currentThread()) {
        throw new CalledFromWrongThreadException(
            "Only the original thread that created a view hierarchy can touch its views.");
        }
    }

3、Handler工作原理分四个步骤:

  • 1、通信准备
  • 2、消息发送
  • 3、消息循环
  • 4、消息处理

1、通信准备

在主线程中创建操作对象,Handler对象,消息循环Looper对象,消息队列MessageQueue对象,且都属于主线程。Handler自动绑定了主线程的Looper、MessageQueue。Hnadler负责发送消息,Looper负责接收消息,并把消息回传给handler中。
 public Handler(Callback callback, boolean async) {
       // 省略代码...
        // 获取对应线程的Looper对象
        mLooper = Looper.myLooper();
        
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
        // 获取Looper内部包含的MessageQueue对象
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

2、消息发送

在工作线程中,通过Handler发送消息到消息队列MessageQueue中。Handler类中常用的几个发送消息方法。

 public final boolean post(Runnable r){
       return  sendMessageDelayed(getPostMessage(r), 0);
}

private static Message getPostMessage(Runnable r) {
        // 获取一个消息对象
        Message m = Message.obtain();
        //此处传递的Runnable只是作为普通的callback处理使用
        m.callback = r;
        return m;
 }

 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){
        //获取当前Handler所在的消息队列
        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);
    }
    
//最终调用enqueueMessage方法,调用MessageQueue中的enqueueMessage方法添加消息
 private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
}

//消息入队 入参:msg 消息 when 延迟时间
boolean enqueueMessage(Message msg, long when) {
        if (msg.target == null) {
            // 判断消息对应的Handler是否空
            throw new IllegalArgumentException("Message must have a target.");
        }
        if (msg.isInUse()) {
            // 判断消息是否正在使用
            throw new IllegalStateException(msg + " This message is already in use.");
        }

        synchronized (this) {
            if (mQuitting) {
            // 判断是否在清除消息队列
                IllegalStateException e = new IllegalStateException(
                        msg.target + " sending message to a Handler on a dead thread");
                Log.w(TAG, e.getMessage(), e);
                msg.recycle();
                return false;
            }
            //标记为使用
            msg.markInUse();
            msg.when = when;
            Message p = mMessages;
            boolean needWake;
            // p 为空直接赋值, 或者消息优先处理,则直接放入队列头部。
            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 {
                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;
    }


消息发送中获取Message的方式:

   
   // 从全局池返回一个新消息实例。允许我们在许多情况下避免分配新对象。如果通过new方式创建,则会出现大量的Message对象,导致频繁的gc,消耗性能。
    public static Message obtain() {
        synchronized (sPoolSync) {
            if (sPool != null) {
            //sPool 为一个Message对象,Message使用的是链表的方式存储
            // m 取出消息链表的头部
                Message m = sPool;
                // sPool指向下一条消息
                sPool = m.next;
                m.next = null;
                m.flags = 0; // 清空 in-use flag
                sPoolSize--;
                //返回从池中获取到的消息
                return m;
            }
        }
        // 池为空则创建一个消息返回
        return new Message();
    }

Message消息在回收的时候添加到消息链表中:

Message采用了类似享元设计模式,通过享元模式创建一个大小为50的消息池,避免重复创建Message对象。

    //将Message对象回收到消息池中
  public void recycle() {
        //省略代码 ...
        // 清空消息状态,并添加到消息池中。
        recycleUnchecked();
    }
    
void recycleUnchecked() {
      // 设置标识位flags ,该flags会在obtain()中置0
        flags = FLAG_IN_USE;
        what = 0;
        arg1 = 0;
        arg2 = 0;
        obj = null;
        replyTo = null;
        sendingUid = -1;
        when = 0;
        target = null;
        callback = null;
        data = null;
        
        synchronized (sPoolSync) {
        //池的大小小于MAX_POOL_SIZE,则将next消息添加到链表头部
        // 如果池中有元素,当调用obtain()时,从池中获取表头元素即sPool,
            if (sPoolSize < MAX_POOL_SIZE) {
                next = sPool;
                sPool = this;
                sPoolSize++;
            }
        }
    }

3、消息循环

Looper循环取出MessageQueue中的消息,并将取出的消息发送给Handler进行处理,如果消息队列为空,则线程阻塞。

前面讲到创建Hanlder时通过 Looper类的静态方法 Looper.myLooper(); 获得Looper对象,并获取到MessageQueue对象。

 //获取当前线程对应的Looper对象
public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
}

public static void prepare() {
        prepare(true);
}
    
   // 创建当前线程的looper对象,并且在之后先调用 loop(),结束时候调用quit() 
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对象
public static void prepareMainLooper() {
    prepare(false);
    synchronized (Looper.class) {
    if (sMainLooper != null) {
        throw new IllegalStateException("The main Looper has already been prepared.");
    }
    sMainLooper = myLooper();
}
    

prepareMainLooper() 方法是在frameworks/base/core/java/android/app/ActivityThread.java中的UI主线程中被调用,初始化主线程looper。

  public static void main(String[] args) {
        //省略代码 ...
        // 初始化主线程looper
        Looper.prepareMainLooper();
        //  主线程
        ActivityThread thread = new ActivityThread();
        thread.attach(false);

        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }

        // 省略代码 ...
        
        // 开启循环
        Looper.loop();

        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

了解下ThreadLocal

ThreadLocal是Java中的线程内部的数据类,它使得各线程能够保持各自独立的一个对象,一般情况下,通过ThreadLocal.set() 到线程中的对象是该线程自己使用的对象,对于其他线程而言则无法获取到数据.

创建Looper对象后,调用loop() 方法,这个方法会不断的从消息队列中取出、处理消息,

  public static void loop() {
        final Looper me = myLooper();
        // 该方法调用之前先调用 prepare()
         if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
         //省略代码 ...
        // 核心代码
        //获取消息队列
        final MessageQueue queue = me.mQueue;
        for (;;) {
        // 获取消息,might block,可能会阻塞
            Message msg = queue.next(); // might block
            if (msg == null) {
                return;
            }
            // 处理消息 target 即为Handler
            msg.target.dispatchMessage(msg);
            // 回收消息,放入消息池中
            msg.recycleUnchecked();
        }
    }

MessageQueue中next() 方法取出消息:

 Message next() {
        // 省略代码 ...
        //获取消息
        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }
            // native 事件处理
            nativePollOnce(ptr, nextPollTimeoutMillis);

            synchronized (this) {
                // Try to retrieve the next message.  Return if found.
                final long now = SystemClock.uptimeMillis();
                Message prevMsg = null;
                
                // java 层 Message对象
                Message msg = mMessages;
                if (msg != null && msg.target == null) {
                    // 过滤非isAsynchronous 消息
                    do {
                        prevMsg = msg;
                        msg = msg.next;
                    } while (msg != null && !msg.isAsynchronous());
                }
                if (msg != null) {
                    if (now < msg.when) {
                      // 设置等待时间
                        nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                    } else {
                        // 获取到消息
                        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 {
                    // 队尾,没有更多消息
                    nextPollTimeoutMillis = -1;
                }
        }
    }

4、处理消息

Handler接收Looper发送来的消息,并作出相应的处理,主线程操作.

public void dispatchMessage(Message msg){  
    // msg.callback 其实为Runnable对象,通过Handler的post方法传递过来的
    if(msg.callback!=null){  
        handleCallback(msg);  
    }else{  
    // mCallback 不为空,则直接调用handleMessge()
        if(mCallback!=null){  
            if(mCallback.handleMessge(msg)){  
                return;  
            }  
        } 
        // 如果callback 和 mCallback 都为空,则执行Handler的handleMessage(msg)
        handleMessage(msg);  
    }  
} 

5、简单总结

1、Handler的工作主要包含消息的发送和接收过程。Handler发送消息向MessageQueue中插入一条消息。
2、MessageQueue的next()方法会取出消息给Looper,Looper接收到消息后开始处理。
3、Looper最终将消息交由Handler处理,调用Handler的dispatchMessage(msg)方法处理。

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

推荐阅读更多精彩内容