Android Handler异步消息处理机制解读

Android Handler异步消息处理机制解读

前言

去年年底很忙,就没什么时间写博客,后面就是疫情了,疫情在老家把整个人都搞的浑浑噩噩的,提不起兴致。回到公司复工也是比较忙,没啥时间写,周末不陪陪媳妇儿还要不高兴,最近稍微空闲了一点,准备重新开始继续找回状态吧,从基础的安卓异步消息处理机制开始,网上类似博客很多,但是打算自己重新回顾一下加深印象。

开始之前

​ 说到消息机制,大家一定非常熟悉,因为平时coding的时候高频率的使用。我们都知道,Android系统规定只能在主线程更新UI,子线程进行耗时操作,如果主线程进行耗时操作就会出现ANR(Application Not Responding)的现象,子线程更新UI就会报错,看看子线程更新UI会有什么情况:

       new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                tvContent = findViewById(R.id.tv_content);
                tvContent.setText("89797");
            }
        }).start();

这段代码,我们运行之后,不出意外会报下面的错误,

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

那么怎么解决呢,当然是用handler机制啦,不过我们只知道如何使用肯定是不行的,不然也不用花费时间来写这篇文章了。

(PS:有的人可能会说,子线程并非一定不能更新UI啊,我在onCreate里创建一个子线程刷新UI就可以啊,当然没错,子线程可以在ViewRootImpl还没有被创建之前更新UI,但是我们这里指的是谷歌官方的规定,通用情况下,是不可以在子线程里更新UI的)

先来看看如何解决这个问题,改完之后的代码:

   new Thread(new Runnable() {
                @Override
                public void run() {
                  //  Looper.prepare();//子线程中创建handler Looper得先prepare
                    Handler handler = new Handler(){
                        @Override
                        public void handleMessage(Message msg) {
                            super.handleMessage(msg);
                            tvContent.setText(msg.obj.toString());
                        }
                    };
                    Message message = Message.obtain();
                    message.obj = "test";
                    message.what = 1;
                    handler.sendMessage(message);
                    //Looper.loop();//接收消息
                }
            }).start();

这样就解决了,运行一下,发现又报错了

   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)
        at com.lyj.git.MainActivity$1$1.<init>(MainActivity.java:33)
        at com.lyj.git.MainActivity$1.run(MainActivity.java:33)
        at java.lang.Thread.run(Thread.java:764)

好的,根据报错提示,加上Looper.prepare(),解决,但是发现虽然没有报错了,但是消息没有接收到,加上Looper.loop(),完美解决。

正题

好了,说了半天,进入正题,从源码角度分析。
首先我们来看看这个报错原因,为什么在子线程实例化的时候不调用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;
    }

这个方法的倒数第六行我们可以看到,如果loop为空,就会抛出异常,就是我们最开始出现的错误日志,那么什么时候这个对象才会为空呢,我们来看看mylooper方法

   public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }

这个方法很简单,就是从sThreadLocal中获取,很显然如果sThreadLocal中有Looper存在就返回Looper,如果没有Looper存在就返回空了

那么这个又是在哪给sThreadLocal设置变量的呢,是在Loop.prepare里面

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

//可以看到,该方法在当前thread创建了一个Looper(), ThreadLocal主要用于维护线程的本地变量,  

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

看这段代码,判断sThreadLocal中是否已经存在Looper了,如果还没有则创建一个新的Looper设置进去。这样也就完全解释了为什么我们要先调用Loop.prepare()方法,才能创建Handler对象。同时也可以看出每个线程中最多只会有一个Looper对象

那么肯定有人会问了,我在主线程实例化handler的时候也没有调用Loop.prepare()呀,其实在主线程被创建的时候,已经调用了。我们都知道,应用初始化的时候都会调用ActivityThread类中的main方法(不知道的可以去看看应用启动流程),我们看看这个main方法中干了啥

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

在这个方法里面我们看到在应用初始化的时候主线程已经调用了Loop.prepare了,所以我们平时用的时候不用Looper.prepare。到这里我们就可以在主线程发送消息了

消息入队

不管你是用post的方式还是sendMessage的方式,我们一步步跟进源码可以发现实际上调用的最终都是sendMessageAtTime方法,他俩本质上是没有区别的,就是写的方式不一样罢了,下面我们来看看这个sendMessageAtTime方法

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

实际他调用的是enqueueMessage方法

  boolean enqueueMessage(Message msg, long when) {
        if (msg.target == null) {
            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;
            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;
            }

            // We can assume mPtr != 0 because mQuitting is false.
            if (needWake) {
                nativeWake(mPtr);
            }
        }
        return true;
    }
//我们可以看到,Message被存入MessageQueue时是将Message存到了上一个Message.next上, 
//形成了一个链式的列表,同时也保证了Message列表的时序性。

可以看到, MessageQueue 实际上里面维护了一个 Message 构成的链表,每次插入数据都会按时间顺序进行插入,也就是说 MessageQueue 中的 Message 都是按照时间排好序的,这样的话就使得循环取出 Message 的时候只需要一个个地从前往后拿即可,这样 Message 都可以按时间先后顺序被消费

消息循环

存入我们看到了,那么是何时取出的呢,想必都猜到是Loop里面的逻辑,之前我们也发现子线程里面创建handler需要Looper.prepare(),并且不调用Loop.loop()方法handler接受不到消息,现在我们来看看这个方法。

 public static void loop() {
     //在调用Looper.prepare()之前是不能调用该方法的,不然就得抛出异常了
        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 slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;

            final long traceTag = me.mTraceTag;
            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            final long end;
            try {
                msg.target.dispatchMessage(msg);
                end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            if (slowDispatchThresholdMs > 0) {
                final long time = end - start;
                if (time > slowDispatchThresholdMs) {
                    Slog.w(TAG, "Dispatch took " + time + "ms on "
                            + Thread.currentThread().getName() + ", h=" +
                            msg.target + " cb=" + msg.callback + " msg=" + msg.what);
                }
            }

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

第3,4行:判断Looper对象是否为空,如果是空,抛出"No Looper; Looper.prepare() wasn’t called on this thread."异常。这就是我们最开始写示例代码的时候抛出的异常,如果我们在线程中创建handler,并且调用sendMessage方法,由于没有Looper对象,就会抛此异常。

消息的处理

for (;😉 循环里面,是个死循环,不断的执行next方法,这个方法这里我们暂时先不分析,如果有新消息,就交给 msg.target.dispatchMessage(msg),这里msg.target其实就是Handler对象,我们来看看dispatchMessage这个方法

    public void dispatchMessage(Message msg) {
    if (msg.callback != null) {
        handleCallback(msg);
    } else {
        if (mCallback != null) {
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        handleMessage(msg);
    }
}

1、若msg.callback属性不为空,则代表使用了post(Runnable r)发送消息,直接回调Runnable对象里复写的run()
2、若msg.callback属性为空,则代表使用了sendMessage(Message msg)发送消息,则回调复写的

所以,一个最标准的异步写法就是下面这样的

class HandlerThread extends Thread {
        private Handler handler;
        @Override
        public void run() {
            Looper.prepare();
            handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    tvContent.setText("13232");
                }
            };
            Looper.loop();
        }
    }

到这里,handler的消息异步处理机制就差不多了,我们来总结一下

Message:消息,其中包含了消息ID,消息处理对象以及处理的数据等,由MessageQueue统一列队,终由Handler处理

MessageQueue:用于存储 Message,内部维护了 Message 的链表,每次拿取 Message 时,若该 Message 离真正执行还需要一段时间,会通过 nativePollOnce 进入阻塞状态,避免资源的浪费。若存在消息屏障,则会忽略同步消息优先拿取异步消息,从而实现异步消息的优先消费。

Looper:一个用于遍历 MessageQueue 的类,每个线程有一个独有的 Looper,它会在所处的线程开启一个死循环,不断从 MessageQueue 中拿出消息,并将其发送给 target 进行处理

Handler:事件的发送及处理者,在构造方法中可以设置其 async,默认为 “默认为 true。若 async 为 false 则该 Handler 发送的 Message 均为异步消息,有同步屏障的情况下会被优先处理”

1、一在handler所创建的线程需要维护一个唯一的Looper对象, 一个线程只能有一个Looper,每个线程的Looper通过ThreadLocal来保证,Looper对象的内部又维护有唯一的一个MessageQueue,所以一个线程可以有多个handler,但是只能有一个Looper和一个MessageQueue
2、Message在MessageQueue不是通过一个列表来存储的,而是将传入的Message存入到了上一个Message的next中,在取出的时候通过顶部的Message就能按放入的顺序依次取出Message
3、Looper对象通过loop()方法开启了一个死循环,不断地从looper内的MessageQueue中取出Message然后通过handler将消息分发传回handler所在的线程

借用网上的一张总结的不错的图来表示handler消息机制的流程:


关于消息屏障的内容,很多人都忽略了,我们下次再专门研究

参考:
https://blog.csdn.net/guolin_blog/article/details/9991569
https://blog.csdn.net/wsq_tomato/article/details/80301851
https://www.jianshu.com/p/ddc70efa57e4

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章