Android知识Android知识Android技术知识

Android消息机制底层原理

2017-03-29  本文已影响439人  黄俊彬

1.概述

Android的消息机制主要是指Handler的运行机制,Handler的运行需要底层的MessageQueue和Looper的支撑。MessageQueue是消息队列。他的内存存储了一组消息,以队列的形式对外提供插入和删除的工作。他的内部存储结构并不是真正的队列,而是采用单链表的数据结构来存储消息列表。Looper为消息循环,由于MessageQueue只是一个消息的存储单元,它不能去处理消息,而Looper就填补了这个功能,Looper会以无限循环的形式去查找是否有新的消息,如果有的话就处理消息,否则就一直等待,Looper还有一个特殊的概念,那就是ThreadLocal,ThreadLocal并不是线程,它的作用可以在每个线程中存储数据。我们知道,Handler创建的时候会采用当前线程的Looper来构造消息循环系统,那么Handler内部如何获取到当前线程的Looper呢?这就要使用ThreadLocal了,ThreadLocal可以在不同的线程中互不干扰地存储并提供数据,通过ThreadLocal可以轻松获取每个线程的Looper。当然需要注意的是,线程是默认没有Looper的,如果需要使用Handler就必须为线程创建Looper。我们经常提到的主线程,也就是UI线程,它就是ActivityThread,ActivityThread被创建时会初始化Looper,这也是在主线程中默认可以使用Handler的原因。

2.ThreadLocal-线程局部变量

ThreadLocal是一个现场内部的数据存储类,通过它可以在指定的线程中存储数据,数据存储以后,只有在指定线程中可以获取到存储的数据。对于Handler来说,它需要获取当前线程的Looper,很显然Looper的作用域就是线程并且不同线程具有不同的Looper,这个时候通过ThreadLocal就可以轻松实现Looper在线程中的存储。ThreadLocal是一个泛型类。


2.1存储机制

在localValues内部有一个数组;private Object[]table,ThreadLocal的值就存在这个table数组中,ThreadLocal的值在table数组中的存储位置总是为ThreadLocal的reference字段所标识的对象的下一个位置,比如ThreadLocal的reference对象在table数组中的索引为index,那么ThreadLocal的值在table数组中的索引就是index+1.最终ThreadLocal的值将会被存储在table数组中:table[index+1]=value

2.put

 void put(ThreadLocal<?> key, Object value) {  
  cleanUp();  
  
  // Keep track of first tombstone. That's where we want to go back  
  // and add an entry if necessary.  
  int firstTombstone = -1;  
  
  for (int index = key.hash & mask;; index = next(index)) {  
  Object k = table[index];  
  
  if (k == key.reference) {  
  // Replace existing entry.  
  table[index + 1] = value;  
  return;  
  }  
  
  if (k == null) {  
  if (firstTombstone == -1) {  
  // Fill in null slot.  
  table[index] = key.reference;  
  table[index + 1] = value;  
  size++;  
  return;  
  }  
  
  // Go back and replace first tombstone.  
  table[firstTombstone] = key.reference;  
  table[firstTombstone + 1] = value;  
  tombstones--;  
  size++;  
  return;  
  }  
  
  // Remember first tombstone.  
  if (firstTombstone == -1 && k == TOMBSTONE) {  
  firstTombstone = index;  
  }  
  }  
  }  
  
//获取当前线程的数据  
  Values values(Thread current) {  
  return current.localValues;//当前线程存储的数组  
  }  
  
//初始化当前线程的数据  
Values initializeValues(Thread current) {  
  return current.localValues = new Values();  
  }  

2.3 set

public void set(T value) {  
Thread currentThread = Thread.currentThread();//获取当前的线程  
Values values = values(currentThread);//  
if (values == null) {  
values = initializeValues(currentThread);  
}  
values.put(this, value);  
}  
3)get
[java] view plain copy 在CODE上查看代码片派生到我的代码片
public T get() {  
 // Optimized for the fast path.  
 Thread currentThread = Thread.currentThread();  
 Values values = values(currentThread);  
 if (values != null) {  
 Object[] table = values.table;  
 int index = hash & values.mask;  
 if (this.reference == table[index]) {  
 return (T) table[index + 1];  
 }  
 } else {  
 values = initializeValues(currentThread);  
 }  
  
 return (T) values.getAfterMiss(this);  
 }  

从ThreadLocal的set和get方法可以看出,他们所操作的对象都是当前线程localValues对象的table数组,因此在不同线程中访问同一个ThreadLocal的set和get方法,他们对ThreadLocal所做的读写操作仅限于各自线程的内部。

3.MessageQueue-消息队列

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


3.1enqueueMessage插入消息

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

3.2 next获取消息

Message next() {  
// Return here if the message loop has already quit and been disposed.  
// This can happen if the application tries to restart a looper after quit  
// which is not supported.  
final long ptr = mPtr;  
if (ptr == 0) {  
return null;  
}  
  
int pendingIdleHandlerCount = -1; // -1 only during first iteration  
int nextPollTimeoutMillis = 0;  
for (;;) {  
if (nextPollTimeoutMillis != 0) {  
Binder.flushPendingCommands();  
}  
  
nativePollOnce(ptr, nextPollTimeoutMillis);  
  
synchronized (this) {  
// Try to retrieve the next message. Return if found.  
final long now = SystemClock.uptimeMillis();  
Message prevMsg = null;  
Message msg = mMessages;  
if (msg != null && msg.target == null) {  
// Stalled by a barrier. Find the next asynchronous message in the queue.  
do {  
prevMsg = msg;  
msg = msg.next;  
} while (msg != null && !msg.isAsynchronous());  
}  
if (msg != null) {  
if (now < msg.when) {  
// Next message is not ready. Set a timeout to wake up when it is ready.  
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);  
} else {  
// Got a message.  
mBlocked = false;  
if (prevMsg != null) {  
prevMsg.next = msg.next;  
} else {  
mMessages = msg.next;  
}  
msg.next = null;  
if (DEBUG) Log.v(TAG, "Returning message: " + msg);  
msg.markInUse();  
return msg;  
}  
} else {  
// No more messages.  
nextPollTimeoutMillis = -1;  
}  
  
// Process the quit message now that all pending messages have been handled.  
if (mQuitting) {  
dispose();  
return null;  
}  
  
// If first time idle, then get the number of idlers to run.  
// Idle handles only run if the queue is empty or if the first message  
// in the queue (possibly a barrier) is due to be handled in the future.  
if (pendingIdleHandlerCount < 0  
&& (mMessages == null || now < mMessages.when)) {  
pendingIdleHandlerCount = mIdleHandlers.size();  
}  
if (pendingIdleHandlerCount <= 0) {  
// No idle handlers to run. Loop and wait some more.  
mBlocked = true;  
continue;  
}  
  
if (mPendingIdleHandlers == null) {  
mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];  
}  
mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);  
}  
  
// Run the idle handlers.  
// We only ever reach this code block during the first iteration.  
for (int i = 0; i < pendingIdleHandlerCount; i++) {  
final IdleHandler idler = mPendingIdleHandlers[i];  
mPendingIdleHandlers[i] = null; // release the reference to the handler  
  
boolean keep = false;  
try {  
keep = idler.queueIdle();  
} catch (Throwable t) {  
Log.wtf(TAG, "IdleHandler threw exception", t);  
}  
  
if (!keep) {  
synchronized (this) {  
mIdleHandlers.remove(idler);  
}  
}  
}  
  
// Reset the idle handler count to 0 so we do not run them again.  
pendingIdleHandlerCount = 0;  
  
// While calling an idle handler, a new message could have been delivered  
// so go back and look again for a pending message without waiting.  
nextPollTimeoutMillis = 0;  
}  
}  

next方法是一个无限循环的方法,如果消息队列中没有消息,那么next方法会一直堵塞在这里。当有新消息到来时,next方法会返回这条消息并将其从链表中移除

4.Message- 消息实体

需要注意Message的一些成员变量
Handler target; //对应的Handler
Runnable callback; //对应的回调
Message next;//单链表引用

5.Looper-消息循环

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



Looper处理prepare方法外,还提供了prepareMainLooper方法,这个方法主要是给主线程也就是ActivityThread创建Looper使用的,其本质也是通过prepare方法来实现。由于主线程的Looper比较特殊,所以Looper提供一个getMainLooper方法,通过它可以在任何地方获取主线程的Looper。Looper也是可以退出的,Looper提供勒quit和quitSafely来退出一个Looper。quit会直接退出Looper,而quitSafely只是设定一个退出标记,然后把消息队列的已有消息处理完毕后才安全退出。Looper退出后,通过Handler发送的消息会失败,这个时候Handler的send方法会返回false。在子线程,如果手动为其创建了Looper,那么所有的事情完成以后应该调用quit方法来终止消息循环,否则这个子线程就会一直处理等待的状态。
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();  
}  
}  

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

6.Handle-消息处理

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


6.1 创建

使用Handler必须要有Looper,不然会报异常

public Handler(Callback callback) {  
  this(callback, false);  
  }  
  
  /** 
  * Use the provided {@link Looper} instead of the default one. 
  * 
  * @param looper The looper, must not be null. 
  */  
  public Handler(Looper looper) {  
  this(looper, 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;  
  } 

6.2 发送

Handler发送消息的过程仅仅是向消息队列中插入了一条消息

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

6.3 接收

当消息队列插入消息后,MessageQueue的next方法就会返回这条消息给Looper,Looper收到消息后就开始处理了,最终消息由Looper交由Handler处理

public interface Callback {  
 public boolean handleMessage(Message msg);  
 }  
  
 /** 
 * Subclasses must implement this to receive messages. 
 */  
 public void handleMessage(Message msg) {  
 }  
  
 /** 
 * Handle system messages here. 
 */  
 public void dispatchMessage(Message msg) {  
 if (msg.callback != null) {  
 handleCallback(msg);  
 } else {  
 if (mCallback != null) {  
 if (mCallback.handleMessage(msg)) {  
 return;  
 }  
 }  
 handleMessage(msg);  
 }  
 }  

7.主线程的消息循环

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

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

主线程的消息循环开始以后,ActivityThread还需要一个Handler来和消息队列进行交互,这个Handler就是ActivityThread.H,他的内部定义了一组消息类型,主要管理Activity的生命周期及四大组件的启动和停止过程等

 private class H extends Handler {  
  public static final int LAUNCH_ACTIVITY = 100;  
  public static final int PAUSE_ACTIVITY = 101;  
  public static final int PAUSE_ACTIVITY_FINISHING= 102;  
  public static final int STOP_ACTIVITY_SHOW = 103;  
  public static final int STOP_ACTIVITY_HIDE = 104;  
  public static final int SHOW_WINDOW = 105;  
  public static final int HIDE_WINDOW = 106;  
  public static final int RESUME_ACTIVITY = 107;  
  public static final int SEND_RESULT = 108;  
  public static final int DESTROY_ACTIVITY = 109;  
  public static final int BIND_APPLICATION = 110;  
  public static final int EXIT_APPLICATION = 111;  
  public static final int NEW_INTENT = 112;  
  public static final int RECEIVER = 113;  
  public static final int CREATE_SERVICE = 114;  
  public static final int SERVICE_ARGS = 115;  
  public static final int STOP_SERVICE = 116;  
  
  public static final int CONFIGURATION_CHANGED = 118;  
  public static final int CLEAN_UP_CONTEXT = 119;  
  public static final int GC_WHEN_IDLE = 120;  
  public static final int BIND_SERVICE = 121;  
  public static final int UNBIND_SERVICE = 122;  
  public static final int DUMP_SERVICE = 123;  
  public static final int LOW_MEMORY = 124;  
  public static final int ACTIVITY_CONFIGURATION_CHANGED = 125;  
  public static final int RELAUNCH_ACTIVITY = 126;  
  public static final int PROFILER_CONTROL = 127;  
  public static final int CREATE_BACKUP_AGENT = 128;  
  public static final int DESTROY_BACKUP_AGENT = 129;  
  public static final int SUICIDE = 130;  
  public static final int REMOVE_PROVIDER = 131;  
  public static final int ENABLE_JIT = 132;  
  public static final int DISPATCH_PACKAGE_BROADCAST = 133;  
  public static final int SCHEDULE_CRASH = 134;  
  public static final int DUMP_HEAP = 135;  
  public static final int DUMP_ACTIVITY = 136;  
  public static final int SLEEPING = 137;  
  public static final int SET_CORE_SETTINGS = 138;  
  public static final int UPDATE_PACKAGE_COMPATIBILITY_INFO = 139;  
  public static final int TRIM_MEMORY = 140;  
  public static final int DUMP_PROVIDER = 141;  
  public static final int UNSTABLE_PROVIDER_DIED = 142;  
  public static final int REQUEST_ASSIST_CONTEXT_EXTRAS = 143;  
  public static final int TRANSLUCENT_CONVERSION_COMPLETE = 144;  
  public static final int INSTALL_PROVIDER = 145;  
  public static final int ON_NEW_ACTIVITY_OPTIONS = 146;  
  public static final int CANCEL_VISIBLE_BEHIND = 147;  
  public static final int BACKGROUND_VISIBLE_BEHIND_CHANGED = 148;  
  public static final int ENTER_ANIMATION_COMPLETE = 149;  
}  

另外经常使用的runOnUIThread(Runable action),通过源码分析也是使用了mHandler,而mHandler的Looper也是使用的UI线程的mainLooper。

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

猜你喜欢

热点阅读