从源码的角度理解Android消息处理机制

来源:互联网 发布:ansys软件百度云 编辑:程序博客网 时间:2024/06/12 18:12

总结

与Handler共同作用的有Looper,MessageQueue,Message。我么接下来从源码的角度看看整个过程的大概实现。首先说一下每个对象的作用:
Looper:消息轮询循器,不断的从消息队列中取出消息交给Handler处理
MessageQueue:消息队列,用于存储从Handler发送过来的消息
Message:消息对象,可以携带数据
Handler:用于发送和处理消息

在Android中,主线程默认已经创建了Looper和MessageQueue对象,我们去分析一下。

ActivityThread代表了主线程对象,它的main方法是应用程序的入口,在main方法中创建了Looper。

  Looper.prepareMainLooper();        ActivityThread thread = new ActivityThread();        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);        Looper.loop();

我们看看prepareMainLooper的实现

 public static void prepareMainLooper() {        prepare(false);        synchronized (Looper.class) {            if (sMainLooper != null) {                throw new IllegalStateException("The main Looper has already been prepared.");            }            sMainLooper = myLooper();        }    }

调用了带参数的prepare方法

  private static void prepare(boolean quitAllowed) {        if (sThreadLocal.get() != null) {            throw new RuntimeException("Only one Looper may be created per thread");        }        //将Looper保存在ThreadLocal中        sThreadLocal.set(new Looper(quitAllowed));    }

我们看看Looper的构造方法

  private Looper(boolean quitAllowed) {         //创建了消息队列        mQueue = new MessageQueue(quitAllowed);        mThread = Thread.currentThread();    }

最后是myLooper()方法

 public static @Nullable Looper myLooper() {         //从ThreadLocal中取出Looper对象        return sThreadLocal.get();    }

ThreadLocal有什么作用呢?下面大概介绍一下

ThreadLocal是一个线程内部的数据存储类,通过它可以在指定的线程中存储数据,数据存储以后,只有在指定线程中可以获取到存储的数据,对于其它线程来说无法获取到数据,ThreadLocal可以在不同的线程之中互不干扰地存储并提供数据,通过ThreadLocal可以轻松获取每个线程的Looper。

总结:Looper.prepareMainLooper()方法做了三件事

  • 创建Looper对象以及MessageQueue对象
  • 将当前线程的Looper对象保存到ThreadLocal中
  • 取出ThreadLocal中保存的looper,赋值给Looper的全局静态变量

    接下来我们看看Looper.loop()方法

  public static void loop() {  //获取Looper对象        final Looper me = myLooper();        if (me == null) {        //没有调用Looper.prepare方法会报此异常            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");        }        //取出looper对应的消息队列        final MessageQueue queue = me.mQueue;        ......        //死循环,可能阻塞,作用是不断从消息队列取消息        for (;;) {        //取出消息队列的消息            Message msg = queue.next();            if (msg == null) {              //没有消息说明消息队列退出了                return;            }            ......            //调用消息对象的target的dispatchMessage方法分发消息            //其实这个target是Handler对象,后面我们会看到            msg.target.dispatchMessage(msg);            ......        }    }

接下来我们看看这个msg.target是如何被赋值的,这就要从发送消息的过程开始分析。首先需要创建Handler对象

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()");        }        //将Looper中的消息队列与当前Handler关联        mQueue = mLooper.mQueue;        mCallback = callback;        mAsynchronous = async;    }

有了Handler对象,我们开始发送消息,我们一般采用下面的方式发送消息

 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 sendMessageDelayed(Message msg, long delayMillis)    {        if (delayMillis < 0) {            delayMillis = 0;        }        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);    }

继续往下看

  public boolean sendMessageAtTime(Message msg, long uptimeMillis) {  //取出Handler关联的消息队列,这个消息队列是在Handler的构造方法中赋值的        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方法

  private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {      //把Handler对象赋值给msg的target属性        msg.target = this;        if (mAsynchronous) {            msg.setAsynchronous(true);        }        return queue.enqueueMessage(msg, uptimeMillis);    }

在enqueueMessage方法中,我们终于证实了msg.target是一个Handler对象,接下来调用了消息队列的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) {                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;    }

最后我们就要知道消息是在何时被处理的,也就是说handleMessage方法在何处被调用的,我们知道,在Looper的loop()方法中调用了下面的代码

  msg.target.dispatchMessage(msg);

也就是Looper所关联的Handler对象的dispatchMessage方法

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

看到了吧,终于发现了handleMessage方法的调用。

Handler的优缺点

用到Handler,需要对比一下近似方法:
a.Activity,runOnUiThread(Runnnable)
View.post
View.postDelayed
b.Handler类
c.AsyncTask

这三种方法实际上都是基于Handler类演变而来,只是表现形式不一样,比如AsyncTask是对Handler和Thread的一个封装。三种方式区别

  • a中三个方法代码较复杂,难以维护,结果不清晰,容易出错
  • 而AsyncTask在单个异步操作时较为简单,使用起来简单快捷,但在多个异步操作和UI进行交互是逻辑控制较困难,代码维护不易;
  • Handler类结构清晰,功能明确,多个异步执行和UI交互也容易控制,缺点是单个异步操作时相对AsyncTask代码较多
  • 因此,在单个异步操作时选择AsyncTask较好,在多个异步操作或者特殊操作(比如定时器)时选择Handler较好
0 0