首页 > 移动平台 > 详细

Android 开发艺术探索——第十章 Android的消息机制

时间:2016-05-16 11:08:46      阅读:252      评论:0      收藏:0      [点我收藏+]

Android 开发艺术探索——第十章 Android的消息机制读书笔记

Handler并不是专门用于更新UI的,只是常被用来更新UI

概述

Android的消息机制主要值得就是Handler的运行机制,Handler的运行需要底层的MessageQueue和Looper的支撑。


  • MessageQueue即为消息队列,顾名思义,它的内部存储了一组消息,以队列的的形式对外提供插入和删除的工作。虽然叫队列,但内部存储结构并不是真正的队列,而是采用单链表的数据结构来存储消息列表。
  • Looper意思为循环,可以理解为消息循环。MessageQueue只是一个消息的存储单元,并不能处理消息,而Looper就填补了这个功能。Looper会以无限循环的的形式去查找是否有新消息。如果有消息就处理,否则就一直等待。

Looper中还有一个特殊概念,那就是ThreadLocal。ThreadLocal并不是线程,它的作用是可以在每个线程中存储数据。Handler创建的时候会采用当前线程的Looper来构造消息循环系统,Handler内部利用ThreadLocal来获取当前线程的Looper。

TheadLoacl可以在不同的线程中互不干扰地提供数据。线程默认是没有ThreadLoacl。如果需要使用Handler就必须为线程创建Looper。而主线程即UI线程,就是ActcivityThread。ActivityThread被创建时会初始化Looper,所以在主线程中默认就可以使用Handler。

10.1 Android的消息机制概述

Handler,Looper,MessageQueue三者实际为一体
Handler的主要作用是将一个任务切换到某个指定的的线程中去执行。
Android为何会提供这个功能?因为Android规定UI只能在主线程中进行,在子线程中访问UI就会抛出异常。ViewRootImpl对UI操作做了验证,这个验证由ViewRootImpl的checkThread方法来完成。

void checkThread(){
    if(mThread != Thread.currentThread()){
         throw new CalledFromWrongThreadException(
            "Only the original thread that created a view hierarchy can touch its views"
         );
   }
}

系统为什么不允许在子线程中访问UI呢?
Android的UI控件不是线程安全的,如果在多线程中并发访问可能会导致UI控件处于不可预期的的状态。

为什么系统不对UI控件的访问加上锁机制?
缺点有两个:

  • 加上锁机制会让UI访问的逻辑变得复杂;
  • 锁机制会降低UI访问的效率,因为锁机制会阻塞某些线程的执行。

Handler工作原理概述
Handler创建时会采用当前线程的Looper来构建内部消息循环系统,如果当前线程没有Looper,会报”java.lang.RuntimeException:Cant’s create handler inside thread that has not called Looper.prepare()”。这个时候需要为当前线程创建Looper。
Handler创建好之后,内部的Looper和MessageQueue就可以和Handler一起协同工作了。通过Handler的post方法将一个Runnable投递到Handler内部的Looper中去处理,也可以通过Handler的send方法发送一个消息到Looper中去处理。


Handler的post方法最终也是通过send方法来完成的。
当Handler的send方法被调用时,Handler会调用MessageQueue的enqueueMessage方法将这个消息放入消息队列中,然后Looper发现有新信息到来时,就处理这个消息,最终消息中的Runnable或者Handler的Handler的handleMessage方法会被调用。
注意Looper是运行在创建Handler所在的线程中的,这样Handler中的业务就被切换到创建Handler所在的线程中去执行了。

技术分享

10.2Android的消息机制分析

10.2.1 ThreadLocal的工作原理

ThreadLocal是一个线程内部的数据存储类,通过它可以在指定的线程中存储数据,数据存储以后,只有在指定的线程中可以获取到存储的数据,对于其他线程来说则无法获取到数据。
一般使用到ThreadLocal的地方较少。
ThreadLocal的使用场景:

  • 当某些数据是以线程为作用域并且不同线程具有不同的数据副本的时候,可以考虑ThreadLoacl。
  • ThreadLoacl的另一个使用场景是复杂逻辑下的对象传递。

案例
首先定义一个THreadLocal对象,这里选择Booelan类型的,如下:
private ThreadLocal<Boolean>mBooleanThreadLocal = new ThreadLocal<Boolean>();
然后分别在主线程、子线程1和子线程2中设置和访问它的值,代码如下。

mBooleanThreadLocal.set(true);
Log.d(TAG,"[Thread#mian]mBooleanThreadLocal="+mBooleanThreadLocal.get());

new Thread("Thread#1"){
    @Override
    puboic void run(){
          mBooleanThreadLoacl.set(false);
          Log.d(TAG,"[Thread#mian]mBooleanThreadLocal="+mBooleanThreadLocal.get());
    }
}.start();

new Thread("Thread#2"){
    @Override
    puboic void run(){
           Log.d(TAG,"[Thread#mian]mBooleanThreadLocal="+mBooleanThreadLocal.get());
    }
}.start();

在上面的代码中,在主线程中设置mBooleanThreadLocal的值为true,在子线程1中设置mBooleanThreadLocal的值为false,在子线程2中不设置mBooleanThreadLocal的值。然后分别在3个线程中通过get方法获取mBooleanThreadLocal的值根据前面对ThreadLocal的描述,这个时候,主线程应该是true,子线程1中应该是false,而子线程2中由于没有设置值,所以应该是null。
运行结果如下:

D/TestActivity(8676):[Thread#main]mBooleanThreadLocal=true
D/TestActivity(8676):[Thread#1]mBooleanThreadLocal=false
D/TestActivity(8676):[Thread#2]mBooleanThreadLocal=null

ThreadLocal之所以有这么奇妙的用法,是不同的线程中访问同一个ThreadLocal的get方法,ThreadLocal内部会从各自的线程中取出一个数组,然后再从数组中根据当前ThreadLocal的索引去查找对应的Value值。


ThreadLocal是一个泛型类,它定义为public class ThreadLocal<T> ,内部含有一个set和get方法。

ThreadLoacl的set方法:

public void set(T value){
   ThreadLocal currentThread = Thread.currentThread();
   Values values = values(c);
   if(values == null){
       values = initializeValues(currentThread);
   }
   values.put(this,value);
}

在set方法中,首先会通过values方法来获取当前线程中的ThreadLoacl数据。在Thread类的内部有一个成员专门用于存储线程的ThreadLoacl数据:ThreadLoacl.Values。如果localValues为null,那么需要对其进行
初始化后再将ThreadLoacl的值进行存储。在localValues内部有一个数组:public Object[] table,ThreadLoacl的值就存在在这个table数组中。

10.2.2 消息队列的工作原理

消息队列在Android中指的是MessageQueue,MessageQueue主要包含两个操作:插入和读取。读取操作本身会伴随着删除操作,插入和读取对应的方法分别enqueueMessage和next,其中enqueueMessage的作用是往消息队列中插入一个消息,而next的作用是从消息队列中取出一条消息并将其从消息队列中移除。尽管MessageQueue叫消息队列,但是它的内部实现并不是用的队列,实际上它是通过一个单链表的数据结构来维护消息列表,单链表在插入和删除上比较有优势。

书中的源码没看懂,多看几遍

10.2.3 Looper的工作原理

Looper在Android的消息机制中扮演着消息循环的角色。它会不停从MessageQueue中查看是否有新消息,如果有新消息就会立刻处理,否则就一直阻塞在那里。


构造方法,在构造方法中会创建一个MessageQueue即消息队列,然后将当前的对象保存起来。

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

Handler工作需要Looper,没有Looper的线程就会报错。Looper.prepare()即可为当前线程创建一个Looper,接着通过Looper.loop()来开启消息循环。

new Thread("Thread#2"){
      @Override
      public void run(){
      Looper.prepare();
      Handler handler = new Handler();
      Looper.loop();
    }
}.start();

Looper除了prepare方法外,还提供了prepareMainLooper方法,这个方法主要是给主线程ActivityThread创建Looper使用的,其本质也会上通过preare方法来实现的。由于主线程的Looper特殊,Looper提供了一个getMainLooper方法,通过它可以在任何地方获取到主线程的Looper。


Looper也是可以退出的,Looper提供了quit和quitSafely来退出一个Looper。
区别:
quit会直接退出Looper。而quitSafely只是设定一个退出标记,然后把消息队列中的已有消息处理完毕后才安全地退出。


Looper退出后,通过Handler发送的消息会失败,这个时候Handler的send方法会返回false。在子线程中,如果手动为其创建了Looper,那么在所有的事情完成以后应该调用quit方法来终止消息循环,否则这个子线程就会一直处于一个等待的状态,而如果退出Looper以后,则这个线程就会立刻终止,所以建议不需要的时候终止Looper。


Looper最重要的一个方法是loop方法,只有调用loop后,消息循环才会真正地起作用。

public void 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();

   Binder.clearCallingIdentity();
   fianl long ident = Binder.clearCallingIdentity();

   for(;;){
       Message msg = queue.next();
       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 longging = me.mLogging;
       if(logging != null){
           logging.println(">>>>>Dispatching to"+msg.tartget +" "+msg.callback + ":"+msg.what);
       }

       msg.target.dispatchMessage(msg);
       if(logging != null){
          logging.println("<<<<<<Finished to" + msg.target + " "+msg.callbak);
       }
       //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.recyckeUnchecked();
   }
}

Looper的loop方法的工作过程:
loop方法是一个死循环,唯一跳出循环的方式是MessageQueue的next方法返回了null。当Looper的quit方法调用时,Looper就会调用MessagQueue的quit或者quitSafely方法来通知消息队列退出,当消息队列被标记为退出状态时,它的的next就会返回null。也就是说,Looper必须退出,否则loop方法就会无限循环下去。loop方法会调用MessageQueue的next方法获取新消息,而next是一个阻塞操作,当没有消息时,next方法会一直阻塞在那里。如果MessageQueue的next方法返回了新消息,Looper就会处理这条消息:msg.target.dispatchingMessage(msg),这里的msg.target是发送这条消息的Handler对象,这样Handler发送的消息最终又交给它的dispatchMessage方法来处理了。但这里不同的是,Handler的dispatchMessage方法是在创建Handler时所使用的Looper中执行的,这样成功地将代码逻辑切换到指定的线程去执行了。

10.2.4 Handler的工作原理

Handler工作主要包含:消息的发送和接收过程。
消息的发送可以通过post的一系列方法及send的一系列方法来实现,post的一系列方法最终是通过send的一系列方法来实现。


发送一条典型的消息的过程:

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

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

public final sendMessageAtTime(Message msg, long uptimeMills){
      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,uptimeMills);
}

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMills){
    msg.target = this;
    if(mAsynchronus){
        msg.setAsynchronous(true);
    }
    return queue.enqueueMessage(msg,uptimeMills);
}

Handler发送消息的过程仅仅是向消息队列中插入一条消息,MessageQueue的next方法就会返回这条消息给Looper,Looper收到消息后就开始处理了,最终消息由Looper交由Handler处理,即Handler的diapatchMessage方法会被调用,这时Handler就进入处理消息的阶段。


Handler的diapatchMessage方法:

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

Handler处理消息的过程如下:
首先,检查Message的callback是否为null,不为null就通过handleCallback来处理消息。Message的callback是一个Runnable对象,实际上就是Handler的post方法所传递的Runnable参数。handleCallback的逻辑也是很简单,如下:

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

其次,检查mCallback是否为null,不为null就调用mCallback的handleMessage方法来处理消息。CallBack是个接口。

public interface Callback{
    public boolean handleMessage(Message msg);
}

通过Callback可以采用:Handler handler = new Handler(callback);
Callback的意义:可以用来创建一个Handler的实例但并不需要派生Handler的子类。
在日常的开发中,创建Handler最常见的方式就是派生一个Handler的子类并重写其handlerMessage方法来处理具体的消息,而Callback给我们提供了另一种使用Handler的方式,当我们不想派生子类时,就可以通过Callback来实现。


最后调用Handler的handleMessage方法来处理消息。
流程图如下:
技术分享


Handler还有一个特殊的构造方法,那就是通过一个特定的Looper来构造Handler,它的实现如下:

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

下面是Handler的一个默认构造方法pubic Handler()。根据方法中的代码可以看出,如果当前当前线程没有Looper的话,就会抛出”Can’t create handler inside thread that has not called Looper.prepare()”

public Handler(Callback callback, boolean asyn){
     ···
     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;
}

10.3主线程的消息循环

Android的主线程就是ActivityThread,主线程的入口方法为main,在main方法中系统会通过Looper.loop()来开启主线程的Looper以及MessageQueue,通过Looper.loop来开启主线程的消息循环。

public static void main(String[]args){
    ...
    Process.setArgV0("<pre-initialized>");

    Looper.prepareMainLooper();

    ActivityThread thread = new ActivityThread();
    thread.attach(false);

    if(sMainThreadHandler == null){
       sMainThreaddHandler = thread.getHandler();
    }

    AsyncTask.init();

    if(false){
        Looper.myLooper().setMessageLogging(
            new LogPrinter(Log.DEBUG,"ActivityThread"));
        );
    }

    Looper.loop();
    throw new RuntimeException("Main thread loop unexpectedly exited");
}

主线程的消息循环开始了以后,ActivityThread还需要一个Handler来和消息队列进行交互,这个Handler就是ActivityThread.H,它内部定义了一组消息类型,主要包含了四大组件的启动和停止等过程。


ActivityThread通过ApplicationThread和AMS进行进程间通信,AMS以进程间通信的方式完成ActivityThread的请求后回调ApplicationThhread中的Binder方法,然后ApplicationThread会向H发送消息,H收到消息会将ApplicationThread中逻辑切换到ActicvityThread。

Android 开发艺术探索——第十章 Android的消息机制

原文:http://blog.csdn.net/hdszlk/article/details/51422678

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!