Android异步消息处理机制解析

概述

由于Handler总是依附于创建时所在的线程,比如我们的Handler是在主线程中创建的,而在子线程中又无法直接对UI进行操作,于是我们就通过一系列的发送消息、入队、出队等环节,最后调用到handleMessage()方法中,这时的handleMessage()方法已经是在主线程中运行的,因而我们当然可以在这里进行UI操作了。整个异步消息处理流程的示意图如下图所示:
这里写图片描述

1.Message:
Message定义一个消息包含一个描述和任意的数据对象,可以发送给一个Handler。Android 更推荐我们通过Message.obtain()或者Handler.obtainMessage()获取Message对象。这样先从消息池中看有没有可用的Message实例,存在则直接取出并返回这个实例。反之如果消息池中没有可用的Message实例,则根据给定的参数new一个新Message对象。
2.MessageQueue:
消息队列,用来存放Message对象的数据结构,其中Message对象以链表的方式串联起来的。Looper对象对其进行管理,一个线程最多只可以拥有一个 MessageQueue。我们可以通过Looper.myQueue()获取当前线程中的MessageQueue。
3.Looper:
Looper是用于给一个线程添加一个消息队列(MessageQueue),并且循环等待,当有消息时会唤起线程来处理消息的一个工具,直到线程结束为止。通常情况下不会用到Looper,因为对于Activity,Service等系统组件,Frameworks已经为我们初始化好了线程(俗称的UI线程或主线程),在其内含有一个Looper,和由Looper创建的消息队列
4.Handler:
一个Handler允许你发送和处理一个与一个线程的MessageQueue相关联的Message和Runnable对象。当你创建一个新的Handler实例 ,它被绑定到创建它的线程/消息队列的线程——从那时起,它将处理这个MessageQueue 里面的消息和runnables,执行MessageQueue 面出来的消息。
除了发送消息之外,我们还有以下几种方法可以在子线程中进行UI操作:
① Handler的post()/postDelay()方法
② View的post(Runnable)/postDelay(Runnable,long)方法
③Activity的runOnUiThread(Runnable)方法
这几种方法的原理均为异步消息处理机制


源码分析

1.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()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

由此可见,若mLooper为空,将会抛出运行时异常,进而无法正确创建Handler对象,而且还告诉我们应该调用Looper.prepare()。那么,我们先进入Looper.myLooper()方法内部看一看:

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

很显然,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,使得Handler可以成功创建。而主线程中,在程序启动的时候,系统已经帮我们自动调用了Looper.prepare()方法。
小结:在主线程中可以直接创建Handler对象,而在子线程中需要先调用Looper.prepare()才能创建Handler对象。

2.发送消息
Handler在发送消息时,内部基本都会调用到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);
    }

sendMessageAtTime()方法接收两个参数,其中msg参数就是我们发送的Message对象,而uptimeMillis参数则表示发送消息的时间(若调用的不是sendMessageDelayed()方法,延迟时间就为0),然后将这两个参数都传递到MessageQueue的enqueueMessage()方法中,即入队操作,将消息进入到消息队列MessageQueue中。
入队有了,那么出队呢?就得看看Looper.loop()方法:

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
            Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }

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

可知,queue.next()方法即为出队操作。有一个重要的方法:msg.target.dispatchMessage(msg)
msg.taget即为Handler

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

如果mCallback不为空,则调用mCallback的handleMessage()方法,否则直接调用Handler的handleMessage()方法,并将消息对象作为参数传递过去。

标准的异步消息处理线程

 class LooperThread extends Thread {
      public Handler mHandler;
    //private Looper mLooper;
      public void run() {
          Looper.prepare();
          //可加上:mLooper = Looper.myLooper();
          mHandler = new Handler() {    //可改为:mHandler = new Handler(mLooper){}
              public void handleMessage(Message msg) {
                  // process incoming messages here
              }
          };

          Looper.loop();
      }
  }        
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值