android异步消息机制 源码层面彻底解析(1)

前端之家收集整理的这篇文章主要介绍了android异步消息机制 源码层面彻底解析(1)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Handler、Message、Loopler、MessageQueen

首先看一下我们平常使用Handler的一个最常见用法

  1. Handler handler =new Handler(){
  2. @Override
  3. public void handleMessage(Message msg) {
  4. super.handleMessage(msg);
  5. //这里进行一些UI操作等处理
  6. }
  7.  
  8. new Thread(new Runnable() {
  9. @Override
  10. public void run() {
  11. Message message = Message.obtain();
  12. ........
  13. handler.sendMessage(message);
  14. }
  15. });
  16. };

看一下handler的构造函数的源码

  1. public Handler() {
  2. this(null,false);
  3. }
  4. //他会调用本类中的如下构造函数
  5. public Handler(Callback callback,boolean async) {
  6. if (FIND_POTENTIAL_LEAKS) {
  7. final Class<? extends Handler> klass = getClass();
  8. if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
  9. (klass.getModifiers() & Modifier.STATIC) == 0) {
  10. Log.w(TAG,"The following Handler class should be static or leaks might occur: " +
  11. klass.getCanonicalName());
  12. }
  13. }
  14.  
  15. mLooper = Looper.myLooper();
  16. if (mLooper == null) {
  17. throw new RuntimeException(
  18. "Can't create handler inside thread that has not called Looper.prepare()");
  19. }
  20. mQueue = mLooper.mQueue;
  21. mCallback = callback;
  22. mAsynchronous = async;
  23. }

看到当mLooper == null时会抛一个“Can't create handler inside thread that has not called Looper.prepare()”这个异常,所以我们在创建handler实例前首先需要调用Looper.prepare()

  1. public static void prepare() {
  2. prepare(true);
  3. }
  4. //将looper保存到ThreadLocal中,这里可以把ThreadLocal理解为一个以当前线程为键的Map,所以一个线程中只会有一个looper
  5. private static void prepare(boolean quitAllowed) {
  6. if (sThreadLocal.get() != null) {
  7. throw new RuntimeException("Only one Looper may be created per thread");
  8. }
  9. sThreadLocal.set(new Looper(quitAllowed));
  10. }
  11. //我们看到在new Looper(quitAllowed)中,创建了一个消息队列MessageQueen
  12. private Looper(boolean quitAllowed) {
  13. mQueue = new MessageQueue(quitAllowed);
  14. mThread = Thread.currentThread();
  15. }

接下来我们看handler.sendMessage(message)这个方法,从字面意思就是将信息发送出去。一般sendMessage累的方法最终都会调用sendMessageAtTime(Message msg,long uptimeMillis)这个方法

  1. public boolean sendMessageAtTime(Message msg,long uptimeMillis) {
  2. MessageQueue queue = mQueue;
  3. if (queue == null) {
  4. RuntimeException e = new RuntimeException(
  5. this + " sendMessageAtTime() called with no mQueue");
  6. Log.w("Looper",e.getMessage(),e);
  7. return false;
  8. }
  9. return enqueueMessage(queue,msg,uptimeMillis);
  10. }

我们看到最终会执行enqueueMessage(queue,uptimeMillis)这个方法

  1. private boolean enqueueMessage(MessageQueue queue,Message msg,long uptimeMillis) {
  2. msg.target = this;
  3. if (mAsynchronous) {
  4. msg.setAsynchronous(true);
  5. }
  6. return queue.enqueueMessage(msg,uptimeMillis);
  7. }

最终又会调用MessageQueen中的queue.enqueueMessage(msg,uptimeMillis)这个方法,这里的queue就是looper构造方法中创建的那个消息队列

  1. //MessageQueen的enqueueMessage方法
  2. boolean enqueueMessage(Message msg,long when) {
  3. if (msg.target == null) {
  4. throw new IllegalArgumentException("Message must have a target.");
  5. }
  6. if (msg.isInUse()) {
  7. throw new IllegalStateException(msg + " This message is already in use.");
  8. }
  9.  
  10. synchronized (this) {
  11. if (mQuitting) {
  12. IllegalStateException e = new IllegalStateException(
  13. msg.target + " sending message to a Handler on a dead thread");
  14. Log.w(TAG,e);
  15. msg.recycle();
  16. return false;
  17. }
  18.  
  19. msg.markInUse();
  20. msg.when = when;
  21. Message p = mMessages;
  22. boolean needWake;
  23. if (p == null || when == 0 || when < p.when) {
  24. // New head,wake up the event queue if blocked.
  25. msg.next = p;
  26. mMessages = msg;
  27. needWake = mBlocked;
  28. } else {
  29. // Inserted within the middle of the queue. Usually we don't have to wake
  30. // up the event queue unless there is a barrier at the head of the queue
  31. // and the message is the earliest asynchronous message in the queue.
  32. needWake = mBlocked && p.target == null && msg.isAsynchronous();
  33. Message prev;
  34. for (;;) {
  35. prev = p;
  36. p = p.next;
  37. if (p == null || when < p.when) {
  38. break;
  39. }
  40. if (needWake && p.isAsynchronous()) {
  41. needWake = false;
  42. }
  43. }
  44. msg.next = p; // invariant: p == prev.next
  45. prev.next = msg;
  46. }
  47.  
  48. // We can assume mPtr != 0 because mQuitting is false.
  49. if (needWake) {
  50. nativeWake(mPtr);
  51. }
  52. }
  53. return true;
  54. }

MessageQueen虽然名字是一个队列,但实质上他是一个单向链表,这个结构能快速进行插入和删除操作。从上面源码可以看出来,主要是按照发送消息的时间顺序将msg插入到消息队列中。接下来我们就需要从消息队列中取出msg了。这时候就需要调用Looper.loop()方法

  1. public static void loop() {
  2. final Looper me = myLooper();
  3. if (me == null) {
  4. throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
  5. }
  6. final MessageQueue queue = me.mQueue;
  7.  
  8. // Make sure the identity of this thread is that of the local process,// and keep track of what that identity token actually is.
  9. Binder.clearCallingIdentity();
  10. final long ident = Binder.clearCallingIdentity();
  11.  
  12. for (;;) {
  13. //不断从消息队列中取出msg
  14. Message msg = queue.next(); // might block
  15. if (msg == null) {
  16. // No message indicates that the message queue is quitting.
  17. return;
  18. }
  19.  
  20. // This must be in a local variable,in case a UI event sets the logger
  21. Printer logging = me.mLogging;
  22. if (logging != null) {
  23. logging.println(">>>>> Dispatching to " + msg.target + " " +
  24. msg.callback + ": " + msg.what);
  25. }
  26. //将msg交由handler处理
  27. msg.target.dispatchMessage(msg);
  28.  
  29. if (logging != null) {
  30. logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
  31. }
  32.  
  33. // Make sure that during the course of dispatching the
  34. // identity of the thread wasn't corrupted.
  35. final long newIdent = Binder.clearCallingIdentity();
  36. if (ident != newIdent) {
  37. Log.wtf(TAG,"Thread identity changed from 0x"
  38. + Long.toHexString(ident) + " to 0x"
  39. + Long.toHexString(newIdent) + " while dispatching to "
  40. + msg.target.getClass().getName() + " "
  41. + msg.callback + " what=" + msg.what);
  42. }
  43.  
  44. msg.recycleUnchecked();
  45. }
  46. }

可以看到Looper.loop()方法通过在一个死循环中调用Message msg = queue.next()将消息不断的从消息队列中取出来。queue.next()方法的作用就是从消息队列中取msg,唯一跳出循环的方式是MessageQueen的next方法返回了null。现在msg已经取出来,下一步就是怎样将他传递给handler了对吧。所以在死循环中还有一个方法msg.target.dispatchMessage(msg) ,而msg.target就是handler,在上面handler的enqueueMessage()方法中传入的msg.target = this,this就是handler本身,接下来就看看handler的dispatchMessage()方法

  1. public void dispatchMessage(Message msg) {
  2. if (msg.callback != null) {
  3. handleCallback(msg);
  4. } else {
  5. if (mCallback != null) {
  6. if (mCallback.handleMessage(msg)) {
  7. return;
  8. }
  9. }
  10. handleMessage(msg);
  11. }
  12. }

如果我们采用无参的构造函数创建handler,msg.callback与mCallback均为空,所以我们会调用handleMessage(msg),这样文章开头的那个实例整个流程就走完了,handleMessage(msg)会在handler实例所在的线程中执行。

  1. //当我们通过这种方式创建handler时,dispatchMessage中的mCallback就不为null
  2. public Handler(Callback callback) {
  3. this(callback,false);
  4. }
  5. //Callback是一个接口,里面正好也有我们需要的handleMessage(Message msg),dispatchMessage中的 if (mCallback != null) 语句内的内容,就是我们需要重写的handleMessage(Message msg)方法
  6. public interface Callback {
  7. public boolean handleMessage(Message msg);
  8. }
  1. //当我们调用handler.post()方法执行异步任务时
  2. public final boolean post(Runnable r)
  3. {
  4. return sendMessageDelayed(getPostMessage(r),0);
  5. }
  6. //getPostMessage(r)这个方法中我们看到给m.callback赋值了,就是我们传入的runnable接口
  7. private static Message getPostMessage(Runnable r) {
  8. Message m = Message.obtain();
  9. m.callback = r;
  10. return m;
  11. }
  12. //最后在handleCallback方法中我们执行了它的run方法,这也就解释了为什么在子线程中可以用handler.post(Runnable r)更新UI
  13. private static void handleCallback(Message message) {
  14. message.callback.run();
  15. }

总结

梳理整个执行过程

1.调用Looper.prepare()方法,这是创建handler所必须的。在主线程中由于ActivityThread已经通过Looper.prepareMainLooper()方法创建过looper,所以在主线程中创建handler以前无需创建looper,并通过Looper.loop()来开启主线程的消息循环。

2.通过调用handler.sendMessage(message)方法最终会执行enqueueMessage(queue,uptimeMillis),enqueueMessage又会调用MessageQueen的queue.enqueueMessage(msg,uptimeMillis),这样消息就会被添加到消息队列中。

3.调用Looper.loop()方法在死循环中执行Message msg = queue.next(),不断的将msg从消息队列中取出来,同时执行msg.target.dispatchMessage(msg),将消息传递给handler,由handler来处理,如我们调用的handleMessage就是处理消息的方式之一。

异步处理机制流程图

android异步消息机制 源码层面彻底解析(1)

从子线程进行UI 操作的几种方式

Android 提供了几种途径来从其他线程访问 UI 线程。以下列出了几种有用的方法

• Activity.runOnUiThread(Runnable)
• View.post(Runnable) 这里的view就是我们需要改变的ui控件
• View.postDelayed(Runnable,long)
• Handler.post(Runnable,long)

但是,随着操作日趋复杂,这类代码也会变得复杂且难以维护。 要通过工作线程处理更复杂的交互,可以考虑在工作线程中使用 Handler 处理来自 UI 线程的消息。当然,最好的解决方案或许是扩展 AsyncTask 类,此类简化了与 UI 进行交互所需执行的工作线程任务。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

猜你在找的Android相关文章