Android中异步消息处理机制



1. Thread Local Storage (线程局部存储)

     我们通过位于android.os包下的Looper.class源码可以看到成员变量区有一个线程局部变量sThreadLocal,该类的作用是线程局部存储?那么是线程局部存储TLS?这个问题可以从变量作用域的角度来理解。
     
     变量的常见作用域一般包括以下几种。
  • 函数内部变量。其作用区域是该函数,即每次调用该函数,该变量都会重新回到初始值。
  • 类内部的变量。其作用就是该类所产生的对象,即只要该对象没有被销毁,则对象内部的变量则一直保持。
  • 类内部的静态变量。其作用是整个进程,即只要在该进程中,该变量的值就会一直保持,无论使用多少类来构造这个对象,该变量只有一个赋值,且一直保持。
对于类内部的静态变量而言,无论是从进程中那个线程引用该变量,其值总是相同的,因为编译器内部为静态变量分配了单独的内存空间。但有时我们却希望,当从同一个线程中引用该变量时,其值总是相同的, 而从不同的线程引用该变量,其值应该不同,即我们需要一种作用域为线程的变量定义,这就是线程局部存储。

ThreadLocal内部其实是使用弱引用 WeakReference 来存储当前线程对象,但是不同的线程有不同的ThreadLocal对象,因此会有一个用于区别的id,由此内部封装了一个静态内部类Values,这个类就相当于一个map,存储了每一个线程的实例的值。

sThreadLocal 在prepare()函数被调用的时候就进行了一次赋值,即构造一个新的Looper对象存储到本地线程局部变量中,当然一个线程只能有一个Looper对象,否则会抛出如下图所示的异常。

          

Looper中有2个用于构造Looper对象的方法。一个是prepare(),另一个是 prepareMainLooper()。
prepare()我们已经说过了,下面说下 prepareMainLooper()。
prepareMainLooper(),由方法注释我们可以知道,这个应用程序的mainlooper对象是由android环境创建的,所以你自己永远没必要调用这个函数。
               

2.  Looper

我们可以从类注释来了解Looper类的作用到底是干什么的。

Class used to run a message loop for a thread. Threads by default do not have a message loop associated with them; to create one, call prepare in the thread that is to run the loop, and then loop to have it process messages until the loop is stopped.

Most interaction with a message loop is through the Handler class.

This is a typical example of the implementation of a Looper thread, using the separation of prepare and loop to create an initial Handler to communicate with the Looper.

  class LooperThread extends Thread {
      public Handler mHandler;

      public void run() {
          Looper.prepare();

          mHandler = new Handler() {
              public void handleMessage(Message msg) {
                  // process incoming messages here
              }
          };

          Looper.loop();
      }
  }
Looper类的作用就是给在线程内部创建一个消息循环,当然线程自身内部是没有一个消息循环机制;在run()函数首行调用Looper.prepare(),即使创建了一个消息循环队列,然后在run函数尾行调用Looper.loop()则开始处理消息直到消息循环停止。
大多数消息循环的交互是通过Handler类进行的。


3. Handler

这里我们只从消息循环机制角度来分析这个Handler。首先看Handler的构造函数
/**
     * Default constructor associates this handler with the queue for the
     * current thread.
     *
     * If there isn't one, this handler won't be able to receive messages.
     */
    public Handler() {
        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());
            }
        }
         //从TLS(局部线程存储)中取出已经存放好的Looper对象
        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
        //将Looper对象中的MessageQueue赋值给Handler中的对象
        mQueue = mLooper.mQueue;
        mCallback = null;
    }

然后我们在从使用的角度分析,这里我只从异步处理UI界面分析。
我们(程序员)通过 Handler调用sendMessage()函数在线程内部向UI主线程发送一个Message对象,该Message对象会依次通过Handler中的函数
sendMessage(...) -> sendMessageDelayed(...) -> sendMessageAtTime(...) 
最终会通过sendMessageAtTime发送消息对象。
public boolean sendMessageAtTime(Message msg, long uptimeMillis)
    {
        boolean sent = false;
        MessageQueue queue = mQueue;
        if (queue != null) {
            msg.target = this;
       
            //将消息对象加入到消息队列

            sent = queue.enqueueMessage(msg, uptimeMillis);
        }
        else {
            RuntimeException e = new RuntimeException(
                this + " sendMessageAtTime() called with no mQueue");
            Log.w("Looper", e.getMessage(), e);
        }
        return sent;
    }

然后我们在来看看enqueueMessage进行了什么操作。

    final  boolean enqueueMessage(Message msg, long when) {
                      ...

        if (needWake) {
            nativeWake(mPtr);
        }

                      ...
   }

nativeWake是一个java本地方法,这里涉及了消息机制中的Sleep-Wakeup机制,关于如何唤醒Looper线程的动作,这里不做赘述,其最终就是调用了 native层的Looper的wake函数,唤醒了这个函数之后,就开始进行消息循环
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android消息处理机是指Android系统用于处理异步任务的一种机。它基于事件驱动的方式,通过消息队列和线程来实现异步任务的处理。 在Android消息处理机主要包括HandlerMessage和Looper三个核心组件: 1. HandlerHandler消息处理的核心,它用于发送和处理消息。每个Handler对象都关联一个特定的线程,并且在该线程处理消息。通过Handler,我们可以发送消息消息队列,或者处理消息队列消息。 2. MessageMessage消息的载体,用于在不同线程之间传递信息。每个Message对象包含了一个标识符(what)、一个可选的整数参数(arg1和arg2)、一个可选的对象参数(obj)以及一个可选的Handler对象(target)。通过这些属性,我们可以传递需要处理的信息和相关的数据。 3. Looper:Looper是一个消息循环器,它用于不断地从消息队列取出消息,并将其分发给对应的Handler进行处理。每个线程只能有一个Looper对象,它通过轮询机实现不断地从消息队列取出消息。 当我们需要在某个线程处理异步任务时,可以创建一个Handler对象,并将其关联到该线程的Looper。然后,我们可以通过Handler发送消息消息队列,并在对应的Handler处理这些消息。这样就可以实现在不同线程之间进行通信和任务处理。 总的来说,Android消息处理机提供了一种简单而有效的方式来处理异步任务,使得我们能够更好地进行多线程编程和实现UI更新等操作。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值