Android消息机制Handler

不忘初心 砥砺前行, Tomorrow Is Another Day !html

本文概要:android

  1. 对于Handler两个常见的问题
  2. messageQueue、Looper、Handler之间的关系

前言:安全

Android的消息机制主要是指Handler运行机制,handler它的做用就是切换到指定线程执行任务,记住是切换到指定线程执行任务,能够子线程也能够是主线程,只是在实际开发中常常应用于更新UI.在handler底层须要MessageQueue与Looper支持.接着咱们来具体介绍.bash

一. 两个常见问题:

  1. android为何不容许在子线程更新UI?
为了不多线程,更新UI线程是不安全的.
复制代码
  1. 线程不安全,对UI访问为何不采用锁的机制?
锁机制会形成逻辑复杂而且下降访问UI的效率,阻塞某些线程的执行.
复制代码

二. messageQueue、Looper、Handler之间的关系

  • messageQueue:存储消息
  • looper: 处理消息,存储在ThreadLocal中.
  • Handler: 是基于looper构建内部消息循环系统.

对于ThreadLocal若是暂不了解,能够先阅读三. 线程管理之ThreadLocal,这样更容易理解Handler消息机制.多线程

接下来咱们看三剑客的各自工做原理,首先看messageQueue.async

messageQueue

messageQueue称为消息队列,用来存储消息.它涉及到两个关键操做一个就是将消息插入消息队列,另外一个就是读取消息而且移除该消息.ide

涉及的两个操做的方法oop

  • enqueueMessage: 插入消息
  • next: 读取消息接着移除消息

这里重点说下next方法,它是一个无线循环的方法,会不断的从消息队列中读取消息而且移除,若是此时无消息,那么将会一直处于阻塞中.post

对于messageQueue暂时了解到这里,接着看Looper,下面还会涉及到消息队列.学习

Looper

Looper称为消息循环,在消息机制中扮演着很重要的角色. 不断的从消息队列中获取新消息.有消息就处理,无消息也一直处于阻塞中.

1. 首先看Looper的构造方法.

对应源码

private Looper(boolean quitAllowed) {
        //初始化一个消息队列
        mQueue = new MessageQueue(quitAllowed);
        //获取当前线程
        mThread = Thread.currentThread();
}
复制代码

上面looper的构造方法是一个private修饰,因此通常状况不能直接调用,系统提供了prepare()方法来建立Looper.

对应源码

public static void prepare() {
        prepare(true);
}

private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {
            //说明一个线程只能绑定一个looper
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        //将Looper保存于ThreadLocal中.
        sThreadLocal.set(new Looper(quitAllowed));
}
复制代码

对于主线程的特殊性,系统还提供了prepareMainLooper( )来初始化Looper,其主要供ActivityThread使用.而且系统还提供了getMainLooper( )方法,这样就能够在任何地方获取主线程的looper.

2. 接着看Looper的loop方法.

对应源码

public static void loop() {
        final Looper me = myLooper();
        if (me == null) {
            //1.获取当前线程的looper,没有直接报错.
            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 (;;) {
           /*
            * 2.调用MessageQueue的next获取消息.
            * (很是重要)
            */
            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 {
                //3. (很是重要)调用handler分发处理消息
                msg.target.dispatchMessage(msg);
                end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            //...省略部分代码
        }
    }
复制代码

loop方法表明开启消息循环,具体流程能够看注释这样更清晰.这里特别提一点,须要注意的loop是一个无限循环,不断的从messageQueue中获取消息,在以前咱们已经了解到next获取消息时,若是没有则一直处于阻塞状态,因此这里一样也是处于阻塞状态.只有当msg为null的时候才会退出,因此在自定义looper时须要在适当的时候,调用quit/quitSafely退出looper.也间接的退出了messageQueue.能够看下面源码.

对应源码

public void quit() {
        //调用了MessageQueue
        mQueue.quit(false);
}

public void quitSafely() {
        mQueue.quit(true);
}

复制代码

另外在分发消息时,回调了Handler的dispatchMessage,此方法是在建立handler所使用的Looper中去执行的,而looper又与当前线程相绑定的.也就顺利的切换到指定线程去执行处理任务了.

关于Looper咱们分析到这里,最后总结下Looper几个比较重要的API.

  • Looper.prepare(): 建立looper
  • Looper.loop(): 开启消息循环
  • Looper.quit/quitSafely: 当即退出/安全退出
    • 当looper退出后,经过handler发送消失会失败,send方法会返回false.
handler工做原理

经过前面对MessageQueue与Looper的了解,咱们能够用一句话总结出三者关系:"Handler依赖Looper(获取当前线程的Looper),而Looper则依赖于MessageQueue(实例化Looper时会同时实例化一个MessageQueue)"

1. handler 准备阶段

咱们知道Handler依赖于当前线程的Looper,而在主线程咱们并无手动建立looper,其实在主线程启动时也就是ActivityThread,已经初始化了一个looper,而且开启了消息循环.

对应源码

public static void main(String[] args) {
        
        //...省略部分代码
        final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
        TrustedCertificateStore.setDefaultUserDirectory(configDir);

        Process.setArgV0("<pre-initialized>");
        //建立Looper
        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");
    }
复制代码

如上源码,一切准备工做都以就绪,咱们就能够尽情使用handler了.

2. handler 发送阶段

当咱们建立Handler时,会检查当前线程是否包含Looper.

对应源码

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());
            }
        }
        
        //获取当前线程的Looper
        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;
    }
复制代码

若是准备工做一切都没问题,那么就可使用handler发送消息了.

对应源码

//经过Send发送普通消息
public final boolean sendMessage(Message msg){
        return sendMessageDelayed(msg, 0);
}

//经过Post发送Runnable消息
public final boolean post(Runnable r){
       return  sendMessageDelayed(getPostMessage(r), 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=handler.
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
}
复制代码

从上面源码可知,不管是Send仍是Post,最终都是经过send方法将消息发送出去,而且发送消息仅仅往消息队列中插入了一条消息而已.

3. handler 处理阶段

当咱们往消息队列中插入一条消息时,此时looper从MessageQueue中获取到新消息,就进入消息处理阶段.调用了handler的dispatchMessage方法进行处理.

对应源码

public void dispatchMessage(Message msg) {
       
        if (msg.callback != null) {//说明是一个Post消息
          //callback为POST方法传递的Runnable对象
            handleCallback(msg);
        } else {//说明是一个普通消息
            if (mCallback != null) { //mCallback是个接口,提供一个建立时不须要派生handler子类.参考构造方法
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            //回调自身的handleMessage方法
            handleMessage(msg);
        }
    }
复制代码

最后咱们对Hanlder流程作一个总结.

  • handler 准备阶段
    1. 线程启动时,Looper.prepare() 建立一个Looper,经过ThreadLocal将Looper对象和当前线程绑定.
    2. Looper.loop() 方法开启消息循环,不断从MessageQueue的中读取消息,如没有消息,则处于阻塞状态.
  • handler 发送阶段
    1. 当Handle建立时,会得到当前线程相关的Looper对象.

    2. 当经过Handle发送消息时,不管是Post仍是Send普通消息,仅仅加入一条消息到MessageQueue.

    3. looper经过MessageQueue的next方法获取新消息后,而后处理这个消息,最终looper会交由Handler的dispatchMessage方法.

  • handler 处理阶段
    1. 若是是Post消息,则回调Runnable的run方法.

    2. 若是是普通消息,则回调mCallback的handleMessage或自身的HandleMessage方法.

三. 在自定义Thread中使用hanlder

此外经过以上流程分析,咱们能够知道若是在某些特殊状况须要在子线程使用handler.那么只须要为其线程建立looper,开启消息循环.这样再其余地方发送的消息都将在此线程中执行.

示例代码

//伪代码
 new Thread(){
            @Override
            public void run() {
                Looper.prepare();
                Handler handler = new Handler();
                Looper.loop();
            }
        }.start();
复制代码

四. Handler机制的扩展

为了更加方便使用Handler,Androi系统提供了两种方式.具体使用笔记简单就不讲述了,直接看源码.

  • Activity.runOnUiThread(Runnable)

对应源码

public final void runOnUiThread(Runnable action) {
        if (Thread.currentThread() != mUiThread) {
            //发送Post消息
            mHandler.post(action);
        } else {
            //直接执行任务
            action.run();
        }
}
复制代码
  • View.post(Runnable)

对应源码

public boolean post(Runnable action) {
        final AttachInfo attachInfo = mAttachInfo;
        if (attachInfo != null) {
            //直接经过handler发送Post消息
            return attachInfo.mHandler.post(action);
        }

        //先加入队列,等attachInfo被赋值时,会经过handler发送消息.
        getRunQueue().post(action);
        return true;
    }
复制代码

最后用一张Handler工做原理图结束本文.

Handler工做原理

因为本人技术有限,若有错误的地方,麻烦你们给我提出来,本人不胜感激,你们一块儿学习进步.

参考连接:

相关文章
相关标签/搜索