资讯专栏INFORMATION COLUMN

Android异步消息机制

王晗 / 3049人阅读

摘要:在子线程中发送消息,主线程接受到消息并且处理逻辑。也称之为消息队列,特点是先进先出,底层实现是单链表数据结构得出结论方法初始话了一个对象并关联在一个对象,并且一个线程中只有一个对象,只有一个对象。

目录介绍

1.Handler的常见的使用方式

2.如何在子线程中定义Handler

3.主线程如何自动调用Looper.prepare()

4.Looper.prepare()方法源码分析

5.Looper中用什么存储消息

6.Handler发送消息如何运作

7.Looper.loop()方法源码分析

8.runOnUiThread如何实现子线程更新UI

9.Handler的post方法和view的post方法

10.得出部分结论

好消息

博客笔记大汇总【16年3月到至今】,包括Java基础及深入知识点,Android技术博客,Python学习笔记等等,还包括平时开发中遇到的bug汇总,当然也在工作之余收集了大量的面试题,长期更新维护并且修正,持续完善……开源的文件是markdown格式的!同时也开源了生活博客,从12年起,积累共计47篇[近20万字],转载请注明出处,谢谢!

链接地址:https://github.com/yangchong2...

如果觉得好,可以star一下,谢谢!当然也欢迎提出建议,万事起于忽微,量变引起质变!

00.Android异步消息机制

如何在子线程中定义Handler,主线程如何自动调用Looper.prepare(),Looper.prepare()方法源码分析,Looper中用什么存储消息,Looper.loop()方法源码分析,runOnUiThread如何实现子线程更新UI等等

01.Handler消息机制

为什么不允许在子线程中访问UI,Handler消息机制作用,避免子线程手动创建looper,ActivityThread源码分析,ActivityThread源码分析,Looper死循环为什么不会导致应用卡死,会消耗大量资源吗?

1.Handler的常见的使用方式

handler机制大家都比较熟悉呢。在子线程中发送消息,主线程接受到消息并且处理逻辑。如下所示

一般handler的使用方式都是在主线程中定义Handler,然后在子线程中调用mHandler.sendXx()方法,这里有一个疑问可以在子线程中定义Handler吗?

</>复制代码

  1. public class MainActivity extends AppCompatActivity {
  2. private TextView tv ;
  3. /**
  4. * 在主线程中定义Handler,并实现对应的handleMessage方法
  5. */
  6. public static Handler mHandler = new Handler() {
  7. @Override
  8. public void handleMessage(Message msg) {
  9. if (msg.what == 101) {
  10. Log.i("MainActivity", "接收到handler消息...");
  11. }
  12. }
  13. };
  14. @Override
  15. protected void onCreate(Bundle savedInstanceState) {
  16. super.onCreate(savedInstanceState);
  17. setContentView(R.layout.activity_main);
  18. tv = (TextView) findViewById(R.id.tv);
  19. tv.setOnClickListener(new View.OnClickListener() {
  20. @Override
  21. public void onClick(View v) {
  22. new Thread() {
  23. @Override
  24. public void run() {
  25. // 在子线程中发送异步消息
  26. mHandler.sendEmptyMessage(1);
  27. }
  28. }.start();
  29. }
  30. });
  31. }
  32. }

2.如何在子线程中定义Handler

直接在子线程中创建handler,看看会出现什么情况?

运行后可以得出在子线程中定义Handler对象出错,难道Handler对象的定义或者是初始化只能在主线程中?其实不是这样的,错误信息中提示的已经很明显了,在初始化Handler对象之前需要调用Looper.prepare()方法

</>复制代码

  1. tv.setOnClickListener(new View.OnClickListener() {
  2. @Override
  3. public void onClick(View v) {
  4. new Thread() {
  5. @Override
  6. public void run() {
  7. Handler mHandler = new Handler() {
  8. @Override
  9. public void handleMessage(Message msg) {
  10. if (msg.what == 1) {
  11. Log.i(TAG, "在子线程中定义Handler,接收并处理消息");
  12. }
  13. }
  14. };
  15. }
  16. }.start();
  17. }
  18. });

如何正确运行。在这里问一个问题,在子线程中可以吐司吗?答案是可以的,只不过又条件,详细可以看这篇文章02.Toast源码深度分析

这样程序已经不会报错,那么这说明初始化Handler对象的时候我们是需要调用Looper.prepare()的,那么主线程中为什么可以直接初始化Handler呢?难道是主线程创建handler对象的时候,会自动调用Looper.prepare()方法的吗?

</>复制代码

  1. tv.setOnClickListener(new View.OnClickListener() {
  2. @Override
  3. public void onClick(View v) {
  4. new Thread() {
  5. @Override
  6. public void run() {
  7. Looper.prepare();
  8. Handler mHandler = new Handler() {
  9. @Override
  10. public void handleMessage(Message msg) {
  11. if (msg.what == 1) {
  12. Log.i(TAG, "在子线程中定义Handler,接收并处理消息");
  13. }
  14. }
  15. };
  16. Looper.loop();
  17. }
  18. }.start();
  19. }
  20. });
3.主线程如何自动调用Looper.prepare()

首先直接可以看在App初始化的时候会执行ActivityThread的main方法中的代码,如下所示

可以看到Looper.prepare()方法在这里调用,所以在主线程中可以直接初始化Handler了。

</>复制代码

  1. public static void main(String[] args) {
  2. //省略部分代码
  3. Looper.prepareMainLooper();
  4. ActivityThread thread = new ActivityThread();
  5. thread.attach(false);
  6. if (sMainThreadHandler == null) {
  7. sMainThreadHandler = thread.getHandler();
  8. }
  9. if (false) {
  10. Looper.myLooper().setMessageLogging(new
  11. LogPrinter(Log.DEBUG, "ActivityThread"));
  12. }
  13. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
  14. Looper.loop();
  15. throw new RuntimeException("Main thread loop unexpectedly exited");
  16. }

并且可以看到还调用了:Looper.loop()方法,可以知道一个Handler的标准写法其实是这样的

</>复制代码

  1. Looper.prepare();
  2. Handler mHandler = new Handler() {
  3. @Override
  4. public void handleMessage(Message msg) {
  5. if (msg.what == 101) {
  6. Log.i(TAG, "在子线程中定义Handler,并接收到消息");
  7. }
  8. }
  9. };
  10. Looper.loop();

4.Looper.prepare()方法源码分析

源码如下所示

可以看到Looper中有一个ThreadLocal成员变量,熟悉JDK的同学应该知道,当使用ThreadLocal维护变量时,ThreadLocal为每个使用该变量的线程提供独立的变量副本,所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本。

</>复制代码

  1. public static void prepare() {
  2. prepare(true);
  3. }
  4. private static void prepare(boolean quitAllowed) {
  5. if (sThreadLocal.get() != null) {
  6. throw new RuntimeException("Only one Looper may be created per thread");
  7. }
  8. sThreadLocal.set(new Looper(quitAllowed));
  9. }

思考:Looper.prepare()能否调用两次或者多次

如果运行,则会报错,并提示prepare中的Excetion信息。由此可以得出在每个线程中Looper.prepare()能且只能调用一次

</>复制代码

  1. //这里Looper.prepare()方法调用了两次
  2. Looper.prepare();
  3. Looper.prepare();
  4. Handler mHandler = new Handler() {
  5. @Override
  6. public void handleMessage(Message msg) {
  7. if (msg.what == 1) {
  8. Log.i(TAG, "在子线程中定义Handler,并接收到消息。。。");
  9. }
  10. }
  11. };
  12. Looper.loop();

5.Looper中用什么存储消息

先看一下下面得源代码

看Looper对象的构造方法,可以看到在其构造方法中初始化了一个MessageQueue对象。MessageQueue也称之为消息队列,特点是先进先出,底层实现是单链表数据结构

</>复制代码

  1. private static void prepare(boolean quitAllowed) {
  2. if (sThreadLocal.get() != null) {
  3. throw new RuntimeException("Only one Looper may be created per thread");
  4. }
  5. sThreadLocal.set(new Looper(quitAllowed));
  6. }
  7. private Looper(boolean quitAllowed) {
  8. mQueue = new MessageQueue(quitAllowed);
  9. mThread = Thread.currentThread();
  10. }

得出结论

Looper.prepare()方法初始话了一个Looper对象并关联在一个MessageQueue对象,并且一个线程中只有一个Looper对象,只有一个MessageQueue对象。

6.Handler发送消息如何运作

首先看看构造方法

可以看出在Handler的构造方法中,主要初始化了一下变量,并判断Handler对象的初始化不应再内部类,静态类,匿名类中,并且保存了当前线程中的Looper对象。

</>复制代码

  1. public Handler(Callback callback, boolean async) {
  2. if (FIND_POTENTIAL_LEAKS) {
  3. final Class klass = getClass();
  4. if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
  5. (klass.getModifiers() & Modifier.STATIC) == 0) {
  6. Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
  7. klass.getCanonicalName());
  8. }
  9. }
  10. mLooper = Looper.myLooper();
  11. if (mLooper == null) {
  12. throw new RuntimeException(
  13. "Can"t create handler inside thread that has not called Looper.prepare()");
  14. }
  15. mQueue = mLooper.mQueue;
  16. mCallback = callback;
  17. mAsynchronous = async;
  18. }

看handler.sendMessage(msg)方法

关于下面得源码,是步步追踪,看enqueueMessage这个方法,原来msg.target就是Handler对象本身;而这里的queue对象就是我们的Handler内部维护的Looper对象关联的MessageQueue对象。

</>复制代码

  1. handler.sendMessage(message);
  2. //追踪到这一步
  3. public final boolean sendMessage(Message msg){
  4. return sendMessageDelayed(msg, 0);
  5. }
  6. public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
  7. MessageQueue queue = mQueue;
  8. if (queue == null) {
  9. RuntimeException e = new RuntimeException(
  10. this + " sendMessageAtTime() called with no mQueue");
  11. Log.w("Looper", e.getMessage(), e);
  12. return false;
  13. }
  14. return enqueueMessage(queue, msg, uptimeMillis);
  15. }
  16. private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
  17. msg.target = this;
  18. if (mAsynchronous) {
  19. msg.setAsynchronous(true);
  20. }
  21. return queue.enqueueMessage(msg, uptimeMillis);
  22. }

看MessageQueue对象的enqueueMessage方法

看到这里MessageQueue并没有使用列表将所有的Message保存起来,而是使用Message.next保存下一个Message,从而按照时间将所有的Message排序

</>复制代码

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

7.Looper.loop()方法源码分析

看看里面得源码,如下所示

看到Looper.loop()方法里起了一个死循环,不断的判断MessageQueue中的消息是否为空,如果为空则直接return掉,然后执行queue.next()方法

</>复制代码

  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. Binder.clearCallingIdentity();
  8. final long ident = Binder.clearCallingIdentity();
  9. for (;;) {
  10. Message msg = queue.next(); // might block
  11. if (msg == null) {
  12. // No message indicates that the message queue is quitting.
  13. return;
  14. }
  15. // This must be in a local variable, in case a UI event sets the logger
  16. final Printer logging = me.mLogging;
  17. if (logging != null) {
  18. logging.println(">>>>> Dispatching to " + msg.target + " " +
  19. msg.callback + ": " + msg.what);
  20. }
  21. final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
  22. final long traceTag = me.mTraceTag;
  23. if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
  24. Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
  25. }
  26. final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
  27. final long end;
  28. try {
  29. msg.target.dispatchMessage(msg);
  30. end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
  31. } finally {
  32. if (traceTag != 0) {
  33. Trace.traceEnd(traceTag);
  34. }
  35. }
  36. if (slowDispatchThresholdMs > 0) {
  37. final long time = end - start;
  38. if (time > slowDispatchThresholdMs) {
  39. Slog.w(TAG, "Dispatch took " + time + "ms on "
  40. + Thread.currentThread().getName() + ", h=" +
  41. msg.target + " cb=" + msg.callback + " msg=" + msg.what);
  42. }
  43. }
  44. if (logging != null) {
  45. logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
  46. }
  47. // Make sure that during the course of dispatching the
  48. // identity of the thread wasn"t corrupted.
  49. final long newIdent = Binder.clearCallingIdentity();
  50. if (ident != newIdent) {
  51. Log.wtf(TAG, "Thread identity changed from 0x"
  52. + Long.toHexString(ident) + " to 0x"
  53. + Long.toHexString(newIdent) + " while dispatching to "
  54. + msg.target.getClass().getName() + " "
  55. + msg.callback + " what=" + msg.what);
  56. }
  57. msg.recycleUnchecked();
  58. }
  59. }

看queue.next()方法源码

大概的实现逻辑就是Message的出栈操作,里面可能对线程,并发控制做了一些限制等。获取到栈顶的Message对象之后开始执行:msg.target.dispatchMessage(msg)

</>复制代码

  1. Message next() {
  2. // Return here if the message loop has already quit and been disposed.
  3. // This can happen if the application tries to restart a looper after quit
  4. // which is not supported.
  5. final long ptr = mPtr;
  6. if (ptr == 0) {
  7. return null;
  8. }
  9. int pendingIdleHandlerCount = -1; // -1 only during first iteration
  10. int nextPollTimeoutMillis = 0;
  11. for (;;) {
  12. if (nextPollTimeoutMillis != 0) {
  13. Binder.flushPendingCommands();
  14. }
  15. nativePollOnce(ptr, nextPollTimeoutMillis);
  16. synchronized (this) {
  17. // Try to retrieve the next message. Return if found.
  18. final long now = SystemClock.uptimeMillis();
  19. Message prevMsg = null;
  20. Message msg = mMessages;
  21. if (msg != null && msg.target == null) {
  22. // Stalled by a barrier. Find the next asynchronous message in the queue.
  23. do {
  24. prevMsg = msg;
  25. msg = msg.next;
  26. } while (msg != null && !msg.isAsynchronous());
  27. }
  28. if (msg != null) {
  29. if (now < msg.when) {
  30. // Next message is not ready. Set a timeout to wake up when it is ready.
  31. nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
  32. } else {
  33. // Got a message.
  34. mBlocked = false;
  35. if (prevMsg != null) {
  36. prevMsg.next = msg.next;
  37. } else {
  38. mMessages = msg.next;
  39. }
  40. msg.next = null;
  41. if (DEBUG) Log.v(TAG, "Returning message: " + msg);
  42. msg.markInUse();
  43. return msg;
  44. }
  45. } else {
  46. // No more messages.
  47. nextPollTimeoutMillis = -1;
  48. }
  49. // Process the quit message now that all pending messages have been handled.
  50. if (mQuitting) {
  51. dispose();
  52. return null;
  53. }
  54. // If first time idle, then get the number of idlers to run.
  55. // Idle handles only run if the queue is empty or if the first message
  56. // in the queue (possibly a barrier) is due to be handled in the future.
  57. if (pendingIdleHandlerCount < 0
  58. && (mMessages == null || now < mMessages.when)) {
  59. pendingIdleHandlerCount = mIdleHandlers.size();
  60. }
  61. if (pendingIdleHandlerCount <= 0) {
  62. // No idle handlers to run. Loop and wait some more.
  63. mBlocked = true;
  64. continue;
  65. }
  66. if (mPendingIdleHandlers == null) {
  67. mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
  68. }
  69. mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
  70. }
  71. // Run the idle handlers.
  72. // We only ever reach this code block during the first iteration.
  73. for (int i = 0; i < pendingIdleHandlerCount; i++) {
  74. final IdleHandler idler = mPendingIdleHandlers[i];
  75. mPendingIdleHandlers[i] = null; // release the reference to the handler
  76. boolean keep = false;
  77. try {
  78. keep = idler.queueIdle();
  79. } catch (Throwable t) {
  80. Log.wtf(TAG, "IdleHandler threw exception", t);
  81. }
  82. if (!keep) {
  83. synchronized (this) {
  84. mIdleHandlers.remove(idler);
  85. }
  86. }
  87. }
  88. // Reset the idle handler count to 0 so we do not run them again.
  89. pendingIdleHandlerCount = 0;
  90. // While calling an idle handler, a new message could have been delivered
  91. // so go back and look again for a pending message without waiting.
  92. nextPollTimeoutMillis = 0;
  93. }
  94. }

那么msg.target是什么呢?通过追踪可以知道就是定义的Handler对象,然后查看一下Handler类的dispatchMessage方法:

可以看到,如果我们设置了callback(Runnable对象)的话,则会直接调用handleCallback方法

在初始化Handler的时候设置了callback(Runnable)对象,则直接调用run方法。

</>复制代码

  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. }
  13. private static void handleCallback(Message message) {
  14. message.callback.run();
  15. }

8.runOnUiThread如何实现子线程更新UI

看看源码,如下所示

如果msg.callback为空的话,会直接调用我们的mCallback.handleMessage(msg),即handler的handlerMessage方法。由于Handler对象是在主线程中创建的,所以handler的handlerMessage方法的执行也会在主线程中。

在runOnUiThread程序首先会判断当前线程是否是UI线程,如果是就直接运行,如果不是则post,这时其实质还是使用的Handler机制来处理线程与UI通讯。

</>复制代码

  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. }
  13. @Override
  14. public final void runOnUiThread(Runnable action) {
  15. if (Thread.currentThread() != mUiThread) {
  16. mHandler.post(action);
  17. } else {
  18. action.run();
  19. }
  20. }

9.Handler的post方法和view的post方法

Handler的post方法实现很简单,如下所示

</>复制代码

  1. mHandler.post(new Runnable() {
  2. @Override
  3. public void run() {
  4. }
  5. });
  6. public final boolean post(Runnable r){
  7. return sendMessageDelayed(getPostMessage(r), 0);
  8. }

view的post方法也很简单,如下所示

可以发现其调用的就是activity中默认保存的handler对象的post方法

</>复制代码

  1. public boolean post(Runnable action) {
  2. final AttachInfo attachInfo = mAttachInfo;
  3. if (attachInfo != null) {
  4. return attachInfo.mHandler.post(action);
  5. }
  6. ViewRootImpl.getRunQueue().post(action);
  7. return true;
  8. }
  9. public void post(Runnable action) {
  10. postDelayed(action, 0);
  11. }
  12. public void postDelayed(Runnable action, long delayMillis) {
  13. final HandlerAction handlerAction = new HandlerAction(action, delayMillis);
  14. synchronized (this) {
  15. if (mActions == null) {
  16. mActions = new HandlerAction[4];
  17. }
  18. mActions = GrowingArrayUtils.append(mActions, mCount, handlerAction);
  19. mCount++;
  20. }
  21. }

10.得出部分结论

得出得结论如下所示

1.主线程中定义Handler对象,ActivityThread的main方法中会自动创建一个looper,并且与其绑定。如果是子线程中直接创建handler对象,则需要手动创建looper。不过手动创建不太友好,需要手动调用quit方法结束looper。这个后面再说

2.一个线程中只存在一个Looper对象,只存在一个MessageQueue对象,可以存在N个Handler对象,Handler对象内部关联了本线程中唯一的Looper对象,Looper对象内部关联着唯一的一个MessageQueue对象。

3.MessageQueue消息队列不是通过列表保存消息(Message)列表的,而是通过Message对象的next属性关联下一个Message从而实现列表的功能,同时所有的消息都是按时间排序的。

关于其他内容介绍 01.关于博客汇总链接

1.技术博客汇总

2.开源项目汇总

3.生活博客汇总

4.喜马拉雅音频汇总

5.其他汇总

02.关于我的博客

我的个人站点:www.yczbj.org,www.ycbjie.cn

github:https://github.com/yangchong211

知乎:https://www.zhihu.com/people/...

简书:http://www.jianshu.com/u/b7b2...

csdn:http://my.csdn.net/m0_37700275

喜马拉雅听书:http://www.ximalaya.com/zhubo...

开源中国:https://my.oschina.net/zbj161...

泡在网上的日子:http://www.jcodecraeer.com/me...

邮箱:yangchong211@163.com

阿里云博客:https://yq.aliyun.com/users/a... 239.headeruserinfo.3.dT4bcV

segmentfault头条:https://segmentfault.com/u/xi...

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/71907.html

相关文章

  • Android异步消息机制

    摘要:在子线程中发送消息,主线程接受到消息并且处理逻辑。子线程往消息队列发送消息,并且往管道文件写数据,主线程即被唤醒,从管道文件读取数据,主线程被唤醒只是为了读取消息,当消息读取完毕,再次睡眠。 目录介绍 1.Handler的常见的使用方式 2.如何在子线程中定义Handler 3.主线程如何自动调用Looper.prepare() 4.Looper.prepare()方法源码分析 5....

    blair 评论0 收藏0

发表评论

0条评论

王晗

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<