Android 的消息机制

爱情池

都说感情路难走
但这句话只说对一半
难走在于
它压根就没有路
你只能走一步看一步
等这条路走久了
你回头才发现
这条路有这么长
而她在哪一步跟你碰面
你不知道
这条路上
你总是走的步履维艰
谨小甚微
但其实走着走着
你就会发现
其实机缘
也没那么罕见
所以大胆的往前走吧
这一步没遇见
下一步
下下步
下下下步
我相信你早晚能遇见

简介

Handler 是 Android 消息机制的上层接口.开发中只需要和Handler交互即可. 通过 它可以很轻松地将一个任务切换到 Handler 所在的线程中执行,很多人 会认为 Handler 的作用是更新 UI , 这的确没有错, 但是 更新 UI 仅仅 是 Handler 的一个特殊的 使用场景. 具体来说是这样的:
有时候需要在在线程中进行耗时的 I/O 操作,可能读取文件或者访问网络等, 当耗时操作完成以后可能需要在UI上做一些改变,由于Android开发规范的限制,我们并不能在子线程中访问UI控件,因此 所以我们这里有一个误解:Handler 并是专门用来更新UI的,而是开发人员做的一个规避异常的控制

Android 的消息机制 主要是指 Handler的运行机制, Handler的底层需要
1) MessageQueue1 消息队列

Android消息机制概述

  • Android为什么要在某个线程中处理的任务交给Handler处理?为什要提供这样的功能
Android 规定 UI 只能在主线程中进行,如果子线程中访问 UI,那么程序就会抛出异常. ViewRootImpl 对 ui 操作做了验证
  • 系统为什不允许在子线程中访问 ui 呢?
Android 的ui 控件不是线程安全的,多线程访问,可能会导致 UI 控件处于不可预期的状态
  • 系统为什么不允许在子线程中访问 ui 呢?
①. 因为 加上锁机制会让ui访问效率降低,因为锁机制会阻碍某些线程的执行
②. 加锁机制会让 ui 的访问逻辑变得更加复杂

∴ 只是需要通过 Handler 切换一下 UI 访问 的执行线程即可

Handler 原理分析

Handler 创建完毕,这个时候 其内部 的 Looper 以及 MessagerQueue 就可以 和 Handler 一起协同工作了, Handler 的post 方法 将 Runnable 投递 给 Handler 内部的 Looper 中去处理,也可以通过Handler 的 send 方法发送一个send 方法 发送一个消息,Handler 的 send 方法被调用 时,它会调用 MessageQueue 方法就会被调用. 注意 Looper 是运行在创建Handler 所在 线程中,这样一来 Handler 中的业务就会被切换到创建 Handler 的线程中了

Android机制分析

  • ThreadLocal 的工作原理

    • 什么是ThreadLocal?
      ThreadLocal 是一个线程内部的数据存储类,通过它可以存储数据,数据存储以后,只有在指定的线程中获取到存储的数据,对于其他线程来说则无法获取到数据
    public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

如何获取当前线程中的ThradLocal数据,在Thread类中有一个成员专门存储线程中的ThreadLocal数据: ThreadLocal.value localValues

ThreadLocal 的 get 方法比较清晰,如果这个对象为空,那么返回初始值

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

初始值由 ThreadLocal 的 initValue 方法来描述

  protected T initialValue() {
        return null;
    }

从Thread 的set() get() 方法可以看出.他所操作的对象都是当前线程的LocalValue对象的table数组,因此 ThreadLocal 所做的读写操作仅限于各自线程的内部,这就是为什么 ThreadLocal 可以在多个线程中互不干扰的存储数据和修改数据.

消息队列的工作原理

消息队列在Android中指的是 MessageQueque,MessageQueque 主要包括两个操作: 插入[equeueMeassage]和读取[next],读取操作本身会伴随着删除操作,其中equeueMeassage的作用是在消息队列中插入一条消息,而next是从消息队里中读取一条消息将其从消息队列中移除.尽管 MessageQueque 叫消息队列,但她内部实现并不是用的消息对列. 实际上他是通过一个单链表的数据结构去维护消息列表,单链表在插入和删除比较有优势.

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

next方法是一个无线循环的方法,如果消息队列中没有消息,那么next方法会一直阻塞在这里,当有新的消息的时候,next方法会返回这条消息并将其从单链表中移除

Message next() {
        // Return here if the message loop has already quit and been disposed.
        // This can happen if the application tries to restart a looper after quit
        // which is not supported.
        final long ptr = mPtr;
        if (ptr == 0) {
            return null;
        }

        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        int nextPollTimeoutMillis = 0;
        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }

            nativePollOnce(ptr, nextPollTimeoutMillis);

            synchronized (this) {
                // Try to retrieve the next message.  Return if found.
                final long now = SystemClock.uptimeMillis();
                Message prevMsg = null;
                Message msg = mMessages;
                if (msg != null && msg.target == null) {
                    // Stalled by a barrier.  Find the next asynchronous message in the queue.
                    do {
                        prevMsg = msg;
                        msg = msg.next;
                    } while (msg != null && !msg.isAsynchronous());
                }
                if (msg != null) {
                    if (now < msg.when) {
                        // Next message is not ready.  Set a timeout to wake up when it is ready.
                        nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                    } else {
                        // Got a message.
                        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 {
                    // No more messages.
                    nextPollTimeoutMillis = -1;
                }

                // Process the quit message now that all pending messages have been handled.
                if (mQuitting) {
                    dispose();
                    return null;
                }

                // If first time idle, then get the number of idlers to run.
                // Idle handles only run if the queue is empty or if the first message
                // in the queue (possibly a barrier) is due to be handled in the future.
                if (pendingIdleHandlerCount < 0
                        && (mMessages == null || now < mMessages.when)) {
                    pendingIdleHandlerCount = mIdleHandlers.size();
                }
                if (pendingIdleHandlerCount <= 0) {
                    // No idle handlers to run.  Loop and wait some more.
                    mBlocked = true;
                    continue;
                }

                if (mPendingIdleHandlers == null) {
                    mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
                }
                mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
            }

            // Run the idle handlers.
            // We only ever reach this code block during the first iteration.
            for (int i = 0; i < pendingIdleHandlerCount; i++) {
                final IdleHandler idler = mPendingIdleHandlers[i];
                mPendingIdleHandlers[i] = null; // release the reference to the handler

                boolean keep = false;
                try {
                    keep = idler.queueIdle();
                } catch (Throwable t) {
                    Log.wtf(TAG, "IdleHandler threw exception", t);
                }

                if (!keep) {
                    synchronized (this) {
                        mIdleHandlers.remove(idler);
                    }
                }
            }

            // Reset the idle handler count to 0 so we do not run them again.
            pendingIdleHandlerCount = 0;

            // While calling an idle handler, a new message could have been delivered
            // so go back and look again for a pending message without waiting.
            nextPollTimeoutMillis = 0;
        }
  • Looper 的工作原理

    Looper 在 Android 消息机制中扮演消息循环的角色,具体来说,就是不断 的从 MessageQueque中查看是否有新的消息,如果有新的消息就会立刻处理,否则一直阻塞,下面我们来看一下它的构造方法

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

Handler 的工作需要Looper, 没有Looper 的线程就会报错,那么如何为一个线程创建Looper呢?
通过Looper.loop()即可为当前线程创建Looper,接着通过 Looper.loop()来开启线程

new Thread(){
    @Override
    public void run() {

        Looper.prepare();
        final Handler handler = new Handler();
        Looper.loop();
        super.run();
    }
}.start();

Looper 除了 prepare 方法以外,还提供了 prepareMainLooper 方法,这个方法主要是给主线程也就是 ActivityThread使用的,其本质也是通过prepare 方法来实现的.由于子线程比较特殊,所以Looper提供了一个getMainLooper方法,通过它可以在任何地方获取主线程的Looper.Looper也是可以退出的,Looper提供了 quit 和 quitSafely 来退出一个标记,然后把消息队列中的已有消息处理完毕才安全退出,Looper退出后,通过Handler发送消息会失败,这个时候Handler的send方法会返回false.在子线程中如果手动创建了Looper,那么所有事情完成应该调用quit方法来终止消息循环,否则这个子线程就一直处于等待状态,而如果退出Looper以后,这个线程就会立刻终止,因此不建议终止Looper

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

Looper 最重要的一个方法是 loop方法,只有调用loop 后,消息循环才会真正起作用,
Looper的 loop()也好理解,loop方法是一个死循环,唯一跳出死循环的形式是 MessageQueue 的 next 方法 返回 null. 当 Looper quit 方法被调用时, Looper就会调用 MessageQueue 的 quit 或者 quitSafty 方法来通知消息队列退出,当消息队列被标记为退出的时候,它的 next() 返回为null,也就是next方法必须退出,否则loop就会一直阻塞在那里,这也导致 loop 方法一直阻塞在那里,如果 MessageQueue 的 next 方法 返回新的消息,Looper就会处理这条消息, 如果 MessageQueue 的 next 方法返回了新消息, Looper就会处理这条消息: msg.target.dispatchMessage(msg) ,这里的 msg.target 是发送这条消息的Handler对象,这样hangdler发送的消息最终交给dispatchMessage 方法来处理,但是这里不同的是,Handler 的 dispatchMessage 方法 是创建 Handler 时所使用的 Looper介绍的,这也就成功地将代码逻辑切换到指定线程中去执行了.

Hander 的工作原理

Handler 的工作主要包括消息的发送和接收过程.消息的发送可以通过 post 的一系列方=方法实现,post 的一系列 方法最终通过send 的一系列方法来实现的,发送一条消息典型过程如下:

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

可以发现,Handler 发送消息的过程仅仅是向消息队列中插入了一条消息,MessageQue 的 next 方法就会返回 消息给Looper,Lopper 收到消息后开始处理了最终消息由 Looper 交由 Handler 处理,即 Handler 的 的disPatcherMessage 方法被调用,这时Handler 就进入了处理消息的阶段.

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

Handler 处理消息的过程如下:
首先检查 Message 的 callback 是否为空,不为空 就通过 handleCallback 来处理消息,Message 的 callback 是一个runable对象 ,实际上 就是 Handler 的 post 方法 所传递的 Runnable 参数, handleCallback 逻辑也是简单,如下图所示:

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

其次,检查 mCallBack 是否为 null,不为 null 就调用 mCallBack 的 handleMessage 方法来处理消息,CallBack 他是接口

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

callBack 可以采用 如下方式创建 Handler 对象: Handler handler = new Handler(callback). 那么 CallBack 的意义 是什么呢? 源码里面的注释也已经说明了:
可以用来创建一个Handler 的实例,但并不需要派生 Handler 的子类,在日常开发中,创建 Handler 最常见的 方式 就是派生 一个 Handler 的子类 并重写 其 handleMessage 方法 处理 具体消息, 而 Callback 给我们提供了另外一种 Handler 的方式, 当我们不想派生子类时,就可以 通过 CallBack 来实现
最后调用 Handler 的 handleMessage 方法来处理消息. Handler 处理消息的过程可以归纳为一个流程图:


Handler 还有 一个特定的构造方法 就是通过 特定的 Looper 来构造 Handler ,他的实现如下所示:

    public Handler(Looper looper) {
        this(looper, null, false);
    }

下面 看一下 Handler 的默认构造方法 public Handler(), 这个构造方法会调用下面的 构造方法,很明显,如果当前线程没有Lopper的话会抛出
The following Handler class should be static or leaks might occur:
这也解释了在没有Looper的子线程中创建 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());
            }
        }

主线程的消息循环

Android 的主线程就是 ActivtyThread ,主线程的入口方法为main ,在 main 方法中系统会通过 Lopper.prepareMainLooper()来创建主线程的Looper 以及 MessageQueque,并通过 Looper.loop()来开启主线程的消息循环.
主线程的消息循环开始以后, ActivityThread 还需要一个Handler 来和消息队列进行交互,这个Handler 就是 ActivityThread.H ,它内部定义了一组消息类型,主要包括四大组件的启动和终止过程
ActivityThread 通过Application 和 AMS 进行进程间的通信,AMS以进程间的通信完成 ActivityThread 的请求回调 AplicationThread 中的 Binder 方法,然后 ApplitionThread 会向 H 发送消息,H 收到消息后会将 ApplicationThread 中的逻辑切换到ActivityThread中执行,即切换到主线程中去执行.这个过程就是 主线程中的消息循环模型.


  1. 内部存储了一组消息,以队列的形式对外提供插入和删除工作,虽然叫消息队列,但内部并不是真正存储的队列,而是采用单链表的数据结构来存储消息列表.
    2) Looper [^Looper] 消息循环
    [^Looper]: Looper 会以 无限循环的形式去查是否有新消息,如果有new 消息,她就会去处理消息,没有消息她就等着,
    Looper 还有一个特殊的概念 那就是 ThreadLocal , ThreadLoacal 刻意很轻松的获取每个线程的 Looper
    我们经常提到的主线程,也叫UI线程,他就是 ActivityThread, ActivtyThread 被创建的时候就会初始化 Looper,这就是主线程默认可以使用Handler的原因呢

猜你喜欢

转载自blog.csdn.net/Kibaco/article/details/80722651
今日推荐