源码解析 Handler Message MessageQueue Looper


  • 基础认识 Handler Message MessageQueue Looper
  • Handler Message MessageQueue Looper 的关系
  • 经常碰上的问题(含解决方式)

基础认识

Handler :主要用来子线程和主线程数据传递,更新UI。
Message:信息类,它可包含任意的数据传给Handler。
MessageQueue:Message的消息队列。
Looper :用于Message消息循环的一个类。

关系: 通过一个例子,结合源码分析它们的工作流程。

以下是一个可运行的代码,点击Button,在Button事件中创建子线程,然后结合它们去更新button.setText的UI。
因为我要讲得更细,而且语文能力有限,所以啰嗦点了。

从子线程中的run方法开始讲。
27行:
通过Message.obtain(),handler.obtainMessage()去获取Message实例,当然也可以new Message()获取,推荐前两种方式创建Message实例,以下源码解释说明,就是资源利用优化问题。

 * <p class="note">While the constructor of Message is public, the best way to get
 * one of these is to call {@link #obtain Message.obtain()} or one of the
 * {@link Handler#obtainMessage Handler.obtainMessage()} methods, which will pull
 * them from a pool of recycled objects.</p>

30行:
用msg.what建立一个标识,还可以利用msg.setData(Bundle data)传递数据等等。前者方便在handleMessage里面区分事件处理情况。

31行:
handler.sendMessage(msg)是将Message放到消息队列MessageQueue里面,没有处理消息的内容。那么消息什么时候处理,接着看...
sendMessage源码 依次点击去里面的4函数,最后到了jni层。

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

第40行:
有一个表面意思翻译就是处理Message消息的函数handleMessage(Message msg), 是时候引入Looper这个东西了。

来到这里我有几个疑问:
Q 1. handleMessage(Message msg)在什么时候执行里面的事件?
Q 2. 假设是Looper这个东西的里面有个事件让handleMessage触发事件,那看我最上面的例子,根本没出现过Looper啊,我们也没主动创建过Looper,究竟Looper是谁创建了?什么时候创建?
Q 3. 假设Looper已经创建出来了,那是什么方法去触发handleMessage执行,什么时候启动Looper里面那个我们还没知道的方法?
不要急着一下全部解决,看我下面分析后再回想这几个问题。

问题到这里必须得看源码了。 上源码~~
Tips:github上可以源码 地址

 public static void main(String[] args) {
        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
        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());

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

        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }

        // End of event ActivityThreadMain.
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        Looper.loop();

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

第一份源码来自ActivityThread.java(6131行),你应该留意到了一句 Looper.prepareMainLooper(); 然后我再去找Looper这个类的prepareMainLooper()方法究竟是干嘛用的。 94~108行找到

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

77~92 行

/** 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);
    }
    // True if the message queue can be quit.---quitAllowed
    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.prepareMainLooper()调用了prepare(false)方法,而prepare(boolean quitAllowed)方法里面倒数第二行它创建了一个Looper并且将创建的这个Looper放到sThreadLocal(保存当前的Looper对象)里面。
这里解决了第二个问题!
Q: 谁创建的Looper,什么时候创建 -
A:系统自动在Activity启动中ActivityThread里创建了Looper。

接着麻烦回去看ActivityThread.java的源码,最后那几行看到最后这个没Looper.loop(); 在去源码中找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
            final Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }

            final long traceTag = me.mTraceTag;
            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            try {
                msg.target.dispatchMessage(msg);
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }

            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.recycleUnchecked();
        }
    }

上面代码所做的工作大概是

  1. 利用final Looper me = myLooper(); 找出当前的Looper。
  2. 通过final MessageQueue queue = me.mQueue;找出当前Looper有的MessageQueue。
    (final MessageQueue mQueue,mQueue就是MessageQueue来的)
  3. 最后就是msg.target.dispatchMessage(msg); msg就是Message,那么target是什么,在Message.java源码中看到如下
   /*package*/ Handler target;

那就清楚明白了,就是 调用了handler的dispatchMessage(msg)方法,那么它dispatchMessage又是干嘛的呢。 又在Handler.java源码中找到

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

NICE 看到源码中那个handleMessage(msg)没,是不是好有成就感~~~
这里解决了第一和第三个问题!
Q:Looper里面哪个方法触发handleMessage(msg),什么时候触发那个方法(也就是触发handleMessage(msg)方法)
A: 那个触发handleMessage(msg)的方法就是loop(), 它是在Activity启动中ActivityThread.java里面触发的。

上面的已经很好的介绍了Handler Message MessageQueue Looper,但是可能理解起来比较乱。下面整理下(还是跟着例子讲):
  1. 子线程中创建了 Message,将需要传递的数据或者标识给Message。
  2. Message创建赋值完毕后就由handler中的snedMessage(msg)将Message塞到MessageQueue里面(做到这里只是单纯的保存数据,其它什么事都没干)。
  3. 因为一个Activity启动过程中,在ActivityThread里面的主函数里通过 Looper.prepareMainLooper()创建了默认的Looper,并且调用Looper.loop()把当前Looper中的MessageQueue消息通过dispatchMessage(msg)方法分发给handler中的handleMessage(msg)。
  4. 最后我们调用handleMessage(msg),在里面完成我们所需要的事件(如 例子中就是更新UI)。
    而当中的第三步骤我们是看不到的,因为这是系统的机制。

经常碰上的问题(含解决方式)

1. Can't create handler inside thread that has not called Looper.prepare()

直接在子线程里面创建一个Handler实施,然后调用handleMessage去更新UI。


Due to :在里面的线程里面没有调用Looper.prepare()直接Crash。
Looper.prepare() 用来获取Looper实例,虽然主线程是有默认的Looper实例,但是在子线程中它不会默认帮我们创建。但是为什么一定要Looper呢。
Tips: 怎样比较快去找到所出现的问题在源码的哪里,首先找对应的类先,然后里面直接搜索出现的错误原因:如这里直接search“Can't create handler inside thread that has not called Looper.prepare()”

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

看到上面源码的中下可得知,因为在子线程里面不会自动创建Looper实例,Looper.myLooper()为null,所以导致抛异常。那为什么一定要创建Looper实例呢? 你留意下源码mQueue = mLooper.mQueue;和 mCallback = callback;
mCallback的接口源码如下: 它是调用handleMessage的

    public interface Callback {
        public boolean handleMessage(Message msg);
    }
    
    /**
     * Subclasses must implement this to receive messages.
     */
    public void handleMessage(Message msg) {
    }

由此我们可以这样理解:如果你没Looper实例,那么你就获取不到由Looper从MessageQueue分发出来的Message。那么Message都获取不到,还处理消息handleMessage个毛啊!

好~~~那我就老老实实在new Handler之前添加Looper.prepare();


很好,程序顺利运行成功,起码不会crash先,但是我发现我点击button 并没有执行handleMessage(Message msg)里面的所有事件。
噢噢~~我大概想到了,虽然我创建了Looper实例,但是我们不是还需要出发Looper里面的loop()函数的么,因为这函数会触发msg.target.dispatchMessage(msg); 去分发Message给handler。SO~我再加个Looper.loop()给它咯。

咦~ 怎么还是不行的,添加Looper.loop()放在new Handler前后都不可以。WHAT ? WHAT ? WHAT ?
那是因为我根本就没sendMessage,所以MessageQueue根本没信息,那handle个毛啊?


加了 又错 TT

2. Only the original thread that created a view hierarchy can touch its views.

它告诉我只能在主线程中更新UI的东西,这个也没什么,因为我虽然是Looper.prepare()获取到了Looper实例,而且触动handleMessage,但是我依然是在子线里程更新UI了。
ViewRootImpl.java源码 一直说更新UI只能在主线程,但是不知道为什么,看下面源码

 public ViewRootImpl(Context context, Display display) {
        mContext = context;
        mWindowSession = WindowManagerGlobal.getWindowSession();
        mDisplay = display;
        mBasePackageName = context.getBasePackageName();
        mThread = Thread.currentThread();
        mLocation = new WindowLeaked(null);
        mLocation.fillInStackTrace();
        mWidth = -1;
-----------------------------------------------------------------------------------------------
    @Override
    public void requestLayout() {
        if (!mHandlingLayoutInLayoutRequest) {
            checkThread();
            mLayoutRequested = true;
            scheduleTraversals();
        }
    }
-------------------------------------------------------------------------------------------
    void checkThread() {
        if (mThread != Thread.currentThread()) {
            throw new CalledFromWrongThreadException(
                    "Only the original thread that created a view hierarchy can touch its views.");
        }
    }

requestLayout 是用来更新UI的,而里面的方法有个checkThread,mThread是指最初的主线程,因为Activity 在创建就新建了一个 ViewRootImpl 对象,所以是产生那个时候当前的Activity的主线程,而Thread.currentThread()就是当前执行的线程了。

那么如果我想,我就喜欢在子线程里面new Handler去跟新UI,有没有办法呢,有!不过这样做了没什么意思吧了 哈哈。
方法:在new Handler时候,既然它那么喜欢主线程才能更新UI,那么我就通过Looper.getMainLooper()作为参数给它咯。

哎呀~~~ 我在添加Looper.prepare()时候,不小心添加多了一个喔,又creash

3. Only one Looper may be created per thread

继续上源码 Looper.java

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

第一次我们Looper.prepare()之后,就new了一个Looper实例

Looper.java
    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

    private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }
-------------------------------------------------------------------------------------
ThreadLocal.java

    public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null)
                return (T)e.value;
        }
        return setInitialValue();
    }

这样的话,sThreadLocal.get()就有了刚才创建的线程了,所以就Crash咯。

转载请在开头注明作者详细信息和本文出处

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

推荐阅读更多精彩内容