Handler由浅入深(二)--Handler的实现原理以及Looper、Handler、Message三者之间的关系

来源:互联网 发布:数据挖掘工 编辑:程序博客网 时间:2024/06/11 14:40

1、前言

上一篇介绍了Handler的几种基本使用方法,本篇将介绍一下Handler的实现原理,这也是面试经常会被问到的问题,其实我们只要搞清楚Looper、Handler、Message三者之间的关系,自然就明白了Handler的实现原理。本篇文章参考Android异步消息处理机制

2、简介

在Android系统内部其实是有一套消息循环机制,Android消息循环是针对线程的(每个线程都可以有自己的消息队列和消息循环),说的通俗点,比如当我们在启动一个Activity后,Android系统会默认为当前Activity创建消息队列和消息循环(只有主线程享受此待遇),在无限循环中每循环一次,Handler就从其对应的消息队列(MessageQueue)中取出一个消息(Message),然后回调相应的消息处理函数(dispatchMessage或者handlerMessage()),当执行完一个消息后再继续循环,若消息队列中的消息为空,则线程会被阻塞等待,直到有新消息进入时再被唤醒。
而在消息循环机制中,完成主要功能的有以下几个类:
- Handler
- Looper
- Message、MessageQueue
接下来我们来详细探究一下其内部原理

3、Handler解读

Handler主要是对外提供消息发送和消息接收的接口,即sendMessage(Message msg),dispatchMessage(Message msg),handlerMessage(Message msg)这三个函数。
我们先通过一个小案例来展开分析Handler内部实现

public class MainActivity extends AppCompatActivity{    private Handler mHandler0;    private Handler mHandler1;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        mHandler0 = new Handler();        new Thread(new Runnable() {            @Override            public void run() {                mHandler1 = new Handler();            }        }).start();    }

以上的代码主要创建了两个Handler,一个在主线程,一个在子线程,表面上好像一切正常,但是运行起来你会发现,在子线程创建的Handler直接导致程序崩溃,报错为

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

那么我们根据错误提示在子线程加上Looper.prepare()跑一下试试

new Thread(new Runnable(){    @override    public void run(){        Looper.prepare();        mHandler1 = new Handler();    }}).start();

再次运行程序,发现程序不会报错了,那么这一句Looper.prepare()在子线程到底干了什么呢?为什么主线程不用加呢?带着疑问我们来看下Handler()的构造函数

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

构造函数直接调用了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.myLooper()方法获取了一个mLooper对象,当mLooper为空时,直接抛出一个”Can’t create handler inside thread that has not called Looper.prepare()”异常,那么什么时候mLooper会为空呢?我们再来研究一下Looper.myLooper(),点进去看看

/**     * Return the Looper object associated with the current thread.  Returns     * null if the calling thread is not associated with a Looper.     */    public static @Nullable Looper myLooper() {        return sThreadLocal.get();    }

这个方法在sThreadLocal变量中直接取出Looper对象,若sThreadLocal变量中存在Looper对象,则直接返回,若不存在则直接返回null,那么sThreadLocal是什么来头呢?

// sThreadLocal.get() will return null unless you've called prepare().    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

它是本线程变量,用来存放Looper对象,并且每个线程只能存一个Looper对象(下面有解释),那么问题又来了,Looper是从哪里塞到sThreadLocal 集合里的呢?回头想想,我们在子线程做了什么操作?是不是加了一个代码:Looper.prepare();是不是它呢,我们再来看看这一句的源码到底做了什么

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()方法中给sThreadLocal变量设置Looper对象,这样也就理解了为什么要先调用Looper.prepare()方法,才能创建Handler对象,才不会导致崩溃。同时也验证了为什么sThreadLocal只能有一个Looper对象”Only one Looper may be created per thread”,Looper.prepare()方法不能被调用两次,保证了一个线程中只有一个Looper实例。到这里是不是遗忘了点什么,主线程为什么不用调用呢,别急,我们再来看看主线程做了什么,我们来查看一下ActivityThread中的main()方法,这里引用一篇文章帮助大家了解ActivityThread

 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());        AndroidKeyStoreProvider.install();        // 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");    }

代码中调用了Looper.prepareMainLooper();而这个方法内部则又调用了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();        }    }    *****************************************************    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));    }

是不是又调回来了,哈哈~,其实在主线程中google工程师已经帮我们在代码中实现了,因此我们不需要在手动调用Looper.prepare()创建了,而子线程中,因为没有自动帮我们创建Looper对象,因此需要我们手动添加,调用方法是Looper.prepare(),这样我们才能正确的创建Handler对象。

4、Message解读

上篇文章已经介绍了通过Message传递消息,那么具体是如何实现的呢?

new Thread(new Runnable() {                @Override                public void run() {                    Message msg = Message.obtain();                    msg.arg1 = 0;                    msg.obj = "来自于工作线程sendMessage发送到消息队列,在主线程中执行";                    mHandler.sendMessage(msg);//还有其他几种发送空消息和定时、延迟就不一一列举了                }            }).start();

点进mHandler.sendMessage(msg)方法看一下

public final boolean sendMessage(Message msg)    {        return sendMessageDelayed(msg, 0);    }

再进sendMessageDelayed去看看

public final boolean sendMessageDelayed(Message msg, long delayMillis)    {        if (delayMillis < 0) {            delayMillis = 0;        }        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);    }

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

呵呵,有没有发现这三个方法很眼熟sendMessage、sendMessageDelayed、sendMessageAtTime,不管你调用哪个方法最后都是走到sendMessageAtTime。同时还会发现这里用到了消息队列MessageQueue,这个MessageQueue在创建Handler时由mQueue赋值,而由源码分析得出mQueue = mLooper.mQueue,而mLooper则是Looper对象,由上面分析我们知道,每个线程只有一个Looper,因此,一个Looper也就只对应唯一一个MessageQueue对象,之后调用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);    }

enqueueMessage中首先为msg.target赋值为this,【下面会分析到:Looper的loop方法会取出每个msg然后交给msg.target.dispatchMessage(msg)去处理消息】,也就是把当前的handler作为msg的target属性。最终会调用queue的enqueueMessage的方法,也就是说handler发出的消息,最终会保存到消息队列中去。
接着通过MessageQueue调用其内部的enqueueMessage(Message msg, long uptimeMills)方法:

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

首先要知道,源码中用mMessages代表当前等待处理的消息,MessageQueue也没有使用一个集合保存所有的消息。观察中间的代码部分,队列中根据时间when来进行时间排序,这个时间也就是我们传进来延迟的时间uptimeMills参数,之后再根据时间的顺序调用msg.next,从而指定下一个将要处理的消息是什么。如果只是通过sendMessageAtFrontOfQueue()方法来发送消息

public final boolean sendMessageAtFrontOfQueue(Message msg) {    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, 0);}

它也是直接调用enqueueMessage()进行入队,但没有延迟时间,此时会将传递的此消息直接添加到队头处,现在入队操作已经了解得差不多了,接下来应该来了解一下出队操作,那么出队在哪里进行的呢,不要忘记MessageQueue对象是在Looper中赋值,因此我们可以在Looper类中找,先看一下Looper类的构造方法:

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

在构造方法中,创建了一个MessageQueue(消息队列)。
再来看一看Looper.loop()方法:

/**     * Run the message queue in this thread. Be sure to call     * {@link #quit()} to end the loop.     */    public static void loop() {    //该方法直接返回了sThreadLocal存储的Looper实例,如果me为null则抛出异常,也就是说looper方法必须在prepare方法之后运行        final Looper me = myLooper();        if (me == null) {            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");        }        //拿到该looper实例中的mQueue(消息队列)        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            Printer logging = me.mLogging;            if (logging != null) {                logging.println(">>>>> Dispatching to " + msg.target + " " +                        msg.callback + ": " + msg.what);            }        //使用调用 msg.target.dispatchMessage(msg);把消息交给msg的target的dispatchMessage方法去处理。Msg的target是什么呢?其实就是handler对象            msg.target.dispatchMessage(msg);            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();        }    }

代码比较多,我们只挑重要的分析一下,我们可以看到下面的代码用for(;;)进入了一个死循环,之后不断的从MessageQueue对象queue中取出消息msg,而我们不难知道,此时的next()就是进行队列的出队方法,next()方法代码有点长,有兴趣的话可以自行翻阅查看,主要逻辑是判断当前的MessageQueue是否存在待处理的mMessages消息,如果有,则将这个消息出队,然后让下一个消息成为mMessages,否则就进入一个阻塞状态,一直等到有新的消息入队唤醒。回看loop()方法,可以发现当执行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);    }}

先进行判断msg.callback是否为空,若不为空则调用Handler的handleCallback()方法,若为空再判断mCallback是否为空,如果不为空则由mCallback.handleMessage()来处理,如果msg.callback == null且mCallback == null,则由Handler自身的handleMessage()来处理,并将消息作为参数传出去。
我们先看下mCallback是在什么时候赋值的呢?以下为Handler的三个构造函数:

public Handler() {        this(null, false);//默认为null    }一、public Handler(Callback callback, boolean async) {       ……(省略)        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;    }二、public Handler(Looper looper, Callback callback, boolean async) {        mLooper = looper;        mQueue = looper.mQueue;        mCallback = callback;        mAsynchronous = async;    }

再看下msg.callback是在什么时候赋值的?
先看一个代码块:

final Handler handler = new Handler();final Runnable r = new Runnable() {        @Override        public void run() {        }    };new Thread(new Runnable() {        @Override        public void run() {            Message msg = Message.obtain(handler, r);            msg.what = 0;            handler.sendMessage(msg);        }    });

从代码块中可以看出在调用方法obtain时可以将Runnable对象作为callback参数传入
再看一下obtain源码,以下是Message的两个obtain构造消息函数

一、public static Message obtain(Message orig) {        Message m = obtain();        m.what = orig.what;        m.arg1 = orig.arg1;        m.arg2 = orig.arg2;        m.obj = orig.obj;        m.replyTo = orig.replyTo;        if (orig.data != null) {            m.data = new Bundle(orig.data);        }        m.target = orig.target;        m.callback = orig.callback;        return m;    }二、public static Message obtain(Handler h, Runnable callback) {        Message m = obtain();        m.target = h;        m.callback = callback;        return m;    }

通过上面两个方法是不是很明显知道callback的由来了~
接下来我们再以Handler的post方法为例分析下callback
点进post方法看看

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

注意到没,这里又用到了sendMessageDelayed方法去发送消息,并且还使用了getPostMessage()方法将Runnable对象转换成了一条消息,我们来看下这个方法的源码:

private static Message getPostMessage(Runnable r) {        Message m = Message.obtain();        m.callback = r;        return m;    }

在这个方法中,将Runnable对象赋值给了消息的callback字段,这也就说明了在Handler的dispatchMessage()方法中,如果Message的callback等于null才会去调用handleMessage()方法,否则就调用handleCallback()方法。那我们快来看下handleCallback()方法中的代码吧:

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

纳尼!竟然就是直接调用了一开始传入的Runnable对象的run()方法。因此在子线程中通过Handler的post()方法进行UI操作就可以这么写:

Handler handler = new Handler();          new Thread(new Runnable() {              @Override              public void run() {                  handler.post(new Runnable() {                      @Override                      public void run() {                          // 在这里进行UI操作                      }                  });              }          }).start(); 

虽然写法上相差很多,但是原理是完全一样的,我们在Runnable对象的run()方法里更新UI,效果完全等同于在handleMessage()方法中更新UI。
总之,在判断调用哪个函数处理消息时,一定要先看是否在调用obtain构造消息的时候是不是传递了msg或者Runable参数,如果没有,则判断在构造Handler时是否将Callback函数当作参数传递了进来,最后再看自己的Handler是否重写了handleMessage函数。

既然说到这了,那就再顺便看下另外两种更新UI的原理吧
1、看一下View中的post()方法,代码如下所示:

public boolean post(Runnable action) {      Handler handler;      if (mAttachInfo != null) {          handler = mAttachInfo.mHandler;      } else {          ViewRoot.getRunQueue().post(action);          return true;      }      return handler.post(action);  } 

原来就是调用了Handler中的post()方法
2、再来看一下Activity中的runOnUiThread()方法,代码如下所示:

    public final void runOnUiThread(Runnable action) {          if (Thread.currentThread() != mUiThread) {              mHandler.post(action);          } else {              action.run();          }      }  

如果当前的线程不等于UI线程(主线程),就去调用Handler的post()方法,否则就直接调用Runnable对象的run()方法。有没有发现其实它们内部都是调用了Handler的post方法实现的。

说了这么多,相信大家应该明白了为什么我们代码中要使用handleMessage()来捕获我们之前传递过去的信息。
因此,一个最标准的异步消息处理线程的写法应该是这样:

class myThread extends Thread{    public Handler myHandler;    @Override    public void run() {        Looper.prepare();        myHandler = new Handler(){            @Override            public void handleMessage(Message msg) {                super.handleMessage(msg);                //处理消息            }        };       Looper.loop();    }}

5、总结

通过以上异步消息处理线程的讲解,我们不难真正地理解Handler、Looper以及Message之间的关系,概括性来说,Looper负责的是创建一个MessageQueue对象,然后进入到一个无限循环体中不断取出消息,而这些消息都是由一个或者多个Handler进行创建处理。

1、首先Looper.prepare()在本线程中保存一个Looper实例,然后该实例中保存一个MessageQueue对象;因为Looper.prepare()在一个线程中只能调用一次,所以MessageQueue在一个线程中只会存在一个。

2、Looper.loop()会让当前线程进入一个无限循环,不端从MessageQueue的实例中读取消息,然后回调msg.target.dispatchMessage(msg)方法。

3、Handler的构造方法,会首先得到当前线程中保存的Looper实例,进而与Looper实例中的MessageQueue想关联。

4、Handler的sendMessage方法,会给msg的target赋值为handler自身,然后加入MessageQueue中。

5、在构造Handler实例时,我们会重写handleMessage方法,也就是msg.target.dispatchMessage(msg)最终调用的方法。

阅读全文
0 0
原创粉丝点击