android消息机制原理详解
android消息机制原理详解
Android消息机制概述
说到Android的消息机制,Android初级工程师(不包括那些初学者)肯定会想到Handler。是的,Android的消息机制主要是指Handler的运行机制以及Handler所附带的MessageQueue和Looper的工作过程。当我们工作的时候我们只要接触到Handler就可以了。
为什么要有Android消息机制?
我们知道Handler的主要作用是将一个任务切换到某个指定的线程去执行,比如Android规定访问UI只能在主线程中进行,如果在子线程中访问那么程序会抛异常,如下所示:
void checkThread(){ if(mThread != Thread.currentThread()){ throw new CalledFromWrongThreadException( "Only the original thread that created a view hierarchy can touch its views."); } }
这个时候就需要通过Handler来把这个任务从子线程切换到主线程中来执行,这样程序就不会抛异常。再延伸一下,为什么系统不允许在子线程中访问UI呢?这是因为Android的UI控件不是线程安全的,如果在多线程中访问UI控件则会导致不可预期的状态。那为什么不对UI控件访问加锁呢?缺点有两个:首先加锁会让UI控件的访问的逻辑变的复杂;其次,锁机制会降低UI的访问效率。那我们不用线程来操作不就行了吗?但这是不可能的,因为Android的主线程不能执行耗时操作,否则会出现ANR(不知道ANR的自己去百度吧)。所以,从各方面来说,Android消息机制是为了解决在子线程中无法访问UI的矛盾。
系统为什么不允许子线程访问UI线程?这是因为UI线程里面的控件都是非线程安全的,如果在多线程并发访问可能会导致UI控件处于不可预期的状态。那么为什么不给控件访问加上锁呢?首先,加锁之后会导致访问逻辑变得复杂,其次锁机制会降低UI访问的效率,因为锁机制会阻塞某些线程的执行。
android消息机制分析
我们知道,Android的消息机制主要包括Handler、MessageQueue和Looper,为了更好的理解Looper的工作原理,这里先介绍一下ThreadLocal。
ThreadLocal工作原理
ThreadLocal是一个线程内部的数据存储类,通过它可以在指定的线程中存储数据,而且只有在指定的线程里才能获取到存储的数据,对于其他线程来说是获取不到的。
消息机制为什么要用到这个呢?因为对于Handler来说,要获取到当前线程的Looper,而Looper的作用域是当前线程,并且不同线程有不同的Looper,这个时候就可以很方便的通过ThreadLocal对Looper进行存取。
从上面的分析我们可以指定ThreadLocal在使用时只用到了存和取功能,也就set和get方法。我们来看看它的set方法的实现过程是怎样的
public void set(T value){ Thread currentThread = Thread.currentThread(); Values values = values(currentThread); if(values == null){ values = initializeValues(currentThread); } values.put(this, value);}
从上面的源代码中我们可以知道,首先是获取到当前使用这个ThreadLocal对象的线程,然后根据当前线程来找到对应的Values对象,如果没有Values对象则通过初始化来创建一个这样的Values对象,然后则把要保存的数据存储进去。
在Thread类的内部有一个protected属性的ThreadLocal.Values的成员用于存储线程的ThreadLocal的数据,所以values(currentThread)方法就是直接返回currentThread的这个属性。当这个属性为空的时候则通过new一个Values对象来赋值给currentThread。而Values的put方法就是用来保存数据的。Values类是ThreadLocal类的一个静态内部类,而在Values的内部有一个Object的数组:private Object[] table,ThreadLocal存储的值就保存在这个数组里。
/** * Sets entry for given ThreadLocal to given value, creating an * entry if necessary. */ 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; } } }
从上面的源码可以看出ThreadLocal的值在table数组中的存储位置总是为ThreadLocal的reference字段所标识的对象的下一个位置。这也就是它的存储规则。
看了set方法现在再来看一下get方法:
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); }
从上面的源码可以看出来,也是通过currentThread来获取到Values对象,然后判断reference属性是否等于Object数组index位置的对象,等于的时候则获取index下一个位置的对象,这个对象就是之前保存的数据。如果没有Values则使用默认的值,默认情况下为null。
ThreadLocal总结:从ThreadLocal的set和get方法可以看出,它们所操作的都是当前对象的Values对象中的Object数组table,因此不同的线程访问同一个ThreadLocal的set和get方法,它们对ThreadLocal所做的读写仅限于各自线程内部。
MessageQueue工作原理
MessageQueue是消息队列,主要包含两个操作:插入和读取,而读取也包含了删除操作,即每读取一个消息就会从MessageQueue中删除掉这个已读的消息。插入和读取所对应的方法分别是enqueueMessage和next,先来看看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) { // 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; }
首先先判断Message是否绑定了一个Handler对象,即msg.target对象,然后再判断当前消息是否正在使用,当都满足条件的时候则锁定MessageQueue对象,然后判断这个消息是否正在退出,如果正在退出则回收当前消息并且返回false;当以上条件都通过后,则设置当前消息为正在使用,以及配置一些信息。Message p = mMessages;当第一次执行到这里时,mMessages是为空的,所以后面是执行if里面的代码,即把当前消息赋值到mMessages中,然后把当前消息的next(也是一个Message)置为空();注:when == 0 || when < p.when说明上一个消息已经执行完毕或者是当前消息比上一个消息先执行,所以相当于是第一次执行到这里。当消息队列里还有消息的时候就执行else里面的代码,首先循环找到最后一个message,通过判断message.next返回的值是否为空来判断是否是最后一个,因为当是最后一个消息时,此值必定为null,那个时候就跳出循环。因为p已经是null了,所以给当前要处理的message的next置为null,确定这是最后一个消息;同时,因为prev经过赋值已经是mMessages,即之前插入到消息队列的消息,只是还未处理而已;然后把当前传入的messge放到mMessages消息的后面。而且,在else代码里都未对mMessages进行重新赋值,这是因为mMessages还没有读取,当执行next方法的时候才会重新对mMessages赋值。
从这个实现上来看,MessageQueue虽然叫消息队列,但是里面的实现是通过单链表的数据结构来维护消息列表的(当前对象保留下一个对象的地址引用)。插入消息的实现过程只是对单链表的插入操作。下面来看一下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; } }
从最外面的for循环我们可以看出来这是一个无限循环的过程,当消息队列里有消息时,则会取出这个message,即mMessages。当满足条件时,则取出这个mMessages(通过Message msg = mMessages赋值后返回msg),然后把mMessages赋值为msg.next,即把下一个消息赋值成mMessages。通过这个过程就把当前消息处理完了,并且把处理过的消息删除掉了。
这个就是MessageQueue大概的工作原理。
Looper的工作原理
Looper在消息机制里扮演着消息循环的角色,它不停的从消息队列里查看是否有新消息,如果有,则立即处理新消息,没有则一直阻塞在那里。当需要为一个线程创建一个Looper的时候,需要调用Looper的两个静态方法就可以给这个线程创建一个Looper对象了,这两个方法是Looper.prepare();和Looper.loop();
new Thread(){ @override public void run(){ Looper.prepare(); Handler handler = new Handler(); Looper.loop(); }}.start();
现在来看一下这两个方法里都做了些什么,先看prepare的,这个很简单,代码如下:
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));}
prepare方法里调用的是这个方法,所以看这个方法就行了,从这个源码就可以看出,就是把一个Looper对象保存到ThreadLocal里面,然后没有其他的了。
接下来看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(); } }
首先是获取到当前线程的Looper对象和绑定到Looper对象的这个消息队列,接着就是一个死循环了。当消息队列没有消息时,则跳出循环,loop结束;当有消息时,则把这个消息通过Handler(msg.target是一个Handler对象)的dispatchMessage方法来处理这个消息,这也就到了Handler里面去执行了,这样就成功地将代码逻辑切换到指定的线程中去了。
如果当这个loop执行到一半的时候要退出怎么办呢?Looper有一个quit方法,此方法被调用时,Looper会调用MessageQueue的quit或者quitSafely方法来通知消息队列退出,并标识为退出状态,当消息队列被标记为退出状态时,next方法就会返回null,这样loop里面的死循环就跳出去了。
上述通过prepare方法和loop方法只是对普通线程来说的,对于主线程来说,由于主线程情况比较复杂,所以提供了prepareMainLooper来给ActivityThread创建Looper对象,但是其本质也是通过prepare来实现的,这个可以自己去看源码。同时,也可以通过getMainLooper方法在其他任何地方获取到主线程的Looper对象。
注:
1.当Looper退出后,通过Handler发送的消息会失败,这个时候Handler的send方法会返回false;
2. 在子线程中,如果手动为其创建了Looper,那么在所有消息处理完成之后应该调用quit方法来终止消息循环,否则这个子线程就会一直处于等待状态,而如果退出Looper以后,这个线程就会立刻终止,因此建议不需要的时候终止Looper。
Handler的工作原理
Handler主要包括消息的发送和接收,也就是相当于Handler给自己发送了一条消息,只是消息经过了消息队列以及Looper,最后才到Handler的handleMessage方法里。Handler的消息的发送主要由post一系列方法以及send的一系列方法来实现,post的一系列方法最终都是通过send的一系列方法来实现的。而send一系列方法最后都是通过sendMessageAtTime方法来实现的。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); } private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) { msg.target = this; if (mAsynchronous) { msg.setAsynchronous(true); } return queue.enqueueMessage(msg, uptimeMillis); }
从上面代码可以看出,发送消息其实就是往消息队列里面插入一个消息。当Handler把消息插入到消息队列里后,MessageQueue就通过next方法把这个消息返回给Looper,而Looper则通过loop方法调用Handler的dispatchMessage方法(msg.target.dispatchMessage(msg);)。来看看dispatchMessage方法的实现过程:
public void dispatchMessage(Message msg) { if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); } } private static void handleCallback(Message message) { message.callback.run(); }
首先就是判断Message对象是否有callback对象,如果有,则调用callback的run方法,就是下面的这个方法,callback其实是一个实现了Runnable的对象,实际上是通过Handler的post方法所传递的。如果Message对象没有callback对象,则跑到else代码块里,mCallback的handlerMessage方法和后面的那个handlerMessage方法其实是一样的,第一个是通过实现mCallback接口来得到的一个方法,而第二个是Handler的方法,两个方法都是空实现,当处理消息时都要重写这个两个方法中的一个,只是创建Handler时的构造方法不一样而已。
主线程消息循环
ActivityThread是Android的主线程,主线程的入口方法为ActivityThread.java类中的main方法,main代码如下:
public static final void main(String[] args) { SamplingProfilerIntegration.start(); Process.setArgV0("" ); Looper.prepareMainLooper(); if (sMainThreadHandler == null) { sMainThreadHandler = new Handler(); } ActivityThread thread = new ActivityThread(); thread.attach(false); if (false) { Looper.myLooper().setMessageLogging(new LogPrinter(Log.DEBUG, "ActivityThread")); } Looper.loop(); if (Process.supportsProcesses()) { throw new RuntimeException("Main thread loop unexpectedly exited"); } thread.detach(); String name = (thread.mInitialApplication != null) ? thread.mInitialApplication.getPackageName() : "" ; Slog.i(TAG, "Main thread of " + name + " is now exiting"); }
从源码中可以看到,通过Looper.prepareMainLooper来给主线程创建了一个Looper对象以及MessageQueue对象,然后通过Looper.loop();来开启消息循环。其中,主线程的Handler是mH这个变量,mH是ActivityThread.H的一个实例,它内部定义了一组消息,主要包含了四大组建的启动和停止。
private final 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 REQUEST_THUMBNAIL = 117; 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; String codeToString(int code) { if (DEBUG_MESSAGES) { switch (code) { case LAUNCH_ACTIVITY: return "LAUNCH_ACTIVITY"; case PAUSE_ACTIVITY: return "PAUSE_ACTIVITY"; case PAUSE_ACTIVITY_FINISHING: return "PAUSE_ACTIVITY_FINISHING"; case STOP_ACTIVITY_SHOW: return "STOP_ACTIVITY_SHOW"; case STOP_ACTIVITY_HIDE: return "STOP_ACTIVITY_HIDE"; case SHOW_WINDOW: return "SHOW_WINDOW"; case HIDE_WINDOW: return "HIDE_WINDOW"; case RESUME_ACTIVITY: return "RESUME_ACTIVITY"; case SEND_RESULT: return "SEND_RESULT"; case DESTROY_ACTIVITY: return "DESTROY_ACTIVITY"; case BIND_APPLICATION: return "BIND_APPLICATION"; case EXIT_APPLICATION: return "EXIT_APPLICATION"; case NEW_INTENT: return "NEW_INTENT"; case RECEIVER: return "RECEIVER"; case CREATE_SERVICE: return "CREATE_SERVICE"; case SERVICE_ARGS: return "SERVICE_ARGS"; case STOP_SERVICE: return "STOP_SERVICE"; case REQUEST_THUMBNAIL: return "REQUEST_THUMBNAIL"; case CONFIGURATION_CHANGED: return "CONFIGURATION_CHANGED"; case CLEAN_UP_CONTEXT: return "CLEAN_UP_CONTEXT"; case GC_WHEN_IDLE: return "GC_WHEN_IDLE"; case BIND_SERVICE: return "BIND_SERVICE"; case UNBIND_SERVICE: return "UNBIND_SERVICE"; case DUMP_SERVICE: return "DUMP_SERVICE"; case LOW_MEMORY: return "LOW_MEMORY"; case ACTIVITY_CONFIGURATION_CHANGED: return "ACTIVITY_CONFIGURATION_CHANGED"; case RELAUNCH_ACTIVITY: return "RELAUNCH_ACTIVITY"; case PROFILER_CONTROL: return "PROFILER_CONTROL"; case CREATE_BACKUP_AGENT: return "CREATE_BACKUP_AGENT"; case DESTROY_BACKUP_AGENT: return "DESTROY_BACKUP_AGENT"; case SUICIDE: return "SUICIDE"; case REMOVE_PROVIDER: return "REMOVE_PROVIDER"; case ENABLE_JIT: return "ENABLE_JIT"; case DISPATCH_PACKAGE_BROADCAST: return "DISPATCH_PACKAGE_BROADCAST"; case SCHEDULE_CRASH: return "SCHEDULE_CRASH"; } } return "(unknown)"; }
ActivityThread通过ApplicationThread和AMS(ActivityManagerService)进行进程间通信,AMS以进程间通信的方式完成ActivityThread的请求后会回调ApplicationThread中的Binder方法,然后ApplicationThread会向H发送消息,H收到消息后会将ApplicationThread中的逻辑切换到ActivityThread中去执行,即切换到主线程去执行。
总结
Android的消息机制的总体流程就是:Handler向MessageQueue发送一条消息(即插入一条消息),MessageQueue通过next方法把消息传给Looper,Looper收到消息后开始处理,然后最终交给Handler自己去处理。换句话说就是:Handler给自己发送了一条消息,然后自己的handleMessage方法处理消息,只是中间过程经过了MessageQueue和Looper。调用的方法过程如下:Handler.sendMessage方法–>Handler.enqueueMessage–>MessageQueue.next–>Looper.loop–>handler.dispatchMessage–>Handler.handleMessage(或者Runnable的run方法或者Callback.handleMessage)。
更多相关文章
- Android异步处理一:使用Thread+Handler实现非UI线程更新UI界面
- Android的布局方法
- Android消息循环实现原理分析
- Android深入四大组件(一)应用程序启动过程
- Android菜鸟的成长笔记(17)—— 再看Android中的Unbounded Service
- (二)Android事件分发机制 - ViewGroup篇
- Android(安卓)与web的相互调用
- Android设置颜色的几种方法
- Android设置颜色的几种方法