Android的消息机制

发布时间 - 2026-01-10 22:49:13    点击率:

一、简介

Android的消息机制主要是指Handler的运行机制,那么什么是Handler的运行机制那?通俗的来讲就是,使用Handler将子线程的Message放入主线程的Messagequeue中,在主线程使用。

二、学习内容

学习Android的消息机制,我们需要先了解如下内容。

  1. 消息的表示:Message
  2. 消息队列:MessageQueue
  3. 消息循环,用于循环取出消息进行处理:Looper
  4. 消息处理,消息循环从消息队列中取出消息后要对消息进行处理:Handler

平常我们接触的大多是Handler和Message,今天就让我们来深入的了解一下他们。

三、代码详解

一般而言我们都是这样使用Handler的

xxHandler.sendEmptyMessage(xxx);

当然还有其他表示方法,但我们深入到源代码中,会发现,他们最终都调用了一个方法

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

sendMessageAtTime()方法,但这依然不是结束,我们可以看到最后一句enqueueMessage(queue, msg, uptimeMillis);按字面意思来说插入一条消息,那么疑问来了,消息插入了哪里。

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

进入源代码,我们发现,我们需要了解一个新类Messagequeue。

虽然我们一般把他叫做消息队列,但是通过研究,我们发下,它实际上是一种单链表的数据结构,而我们对它的操作主要是插入和读取。

看代码33-44,学过数据结构,我们可以轻松的看出,这是一个单链表的插入末尾的操作。

这样就明白了,我们send方法实质就是向Messagequeue中插入这么一条消息,那么另一个问题随之而来,我们该如何处理这条消息。

处理消息我们离不开一个重要的,Looper。那么它在消息机制中又有什么样的作用那?

Looper扮演着消息循环的角色,具体而言它会不停的从MessageQueue中查看是否有新消息如果有新消息就会立刻处理,否则就已知阻塞在那里,现在让我们来看一下他的代码实现。

首先是构造方法

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

可以发现,它将当前线程对象保存了起来。我们继续

Looper在新线程创建过程中有两个重要的方法looper.prepare() looper.loop

new Thread(){
 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));
 }

咦,我们可以看到这里面又有一个ThreadLocal类,我们在这简单了解一下,他的特性,set(),get()方法。

首先ThreadLocal是一个线程内部的数据存储类,通过它可以在指定的线程中存储数据,数据存储后,只有在制定线程中可以获取存储的数据,对于其他线程而言则无法获取到数据。简单的来说。套用一个列子:

private ThreadLocal<Boolean> mBooleanThreadLocal = new  ThreadLocal<Boolean>();//
mBooleanThreadLocal.set(true);
Log.d(TAH,"Threadmain"+mBooleanThreadLocal.get());
new Thread("Thread#1"){
 public void run(){
 mBooleanThreadLocal.set(false);
 Log.d(TAH,"Thread#1"+mBooleanThreadLocal.get());
 }; 
}.start();
new Thread("Thread#2"){
 public void run(){
 Log.d(TAH,"Thread#2"+mBooleanThreadLocal.get());
 }; 
}.start();

上面的代码运行后,我们会发现,每一个线程的值都是不同的,即使他们访问的是同意个ThreadLocal对象。

那么我们接下来会在之后分析源码,为什么他会不一样。现在我们跳回prepare()方法那一步,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()方法,获得这个线程的Looper,若没有抛出异常。再获得新建的Messagequeue,在这里我们有必要补充一下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;
 }
 }

从24-30我们可以看到,他遍历了整个queue找到msg,若是msg为null,我们可以看到50,他把nextPollTimeoutMillis = -1;实际上是等待enqueueMessage的nativeWake来唤醒。较深的源码涉及了native层代码,有兴趣可以研究一下。简单来说next()方法,在有消息是会返回这条消息,若没有,则阻塞在这里。

我们回到loop()方法27msg.target.dispatchMessage(msg);我们看代码

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

msg.target实际上就是发送这条消息的Handler,我们可以看到它将msg交给dispatchMessage(),最后调用了我们熟悉的方法handleMessage(msg);

三、总结

到目前为止,我们了解了android的消息机制流程,但它实际上还涉及了深层的native层方法.

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!


# Android  # 消息机制  # android异步消息机制 从源码层面解析(2)  # android异步消息机制 源码层面彻底解析(1)  # 代码分析Android消息机制  # Android异步消息机制详解  # android线程消息机制之Handler详解  # android利用消息机制获取网络图片  # Android 消息机制详解及实例代码  # Android消息机制Handler的工作过程详解  # 深入剖析Android消息机制原理  # Android 消息机制以及handler的内存泄露  # 从源码角度分析Android的消息机制  # 可以看到  # 这条  # 都是  # 在这里  # 数据结构  # 列子  # 它将  # 源代码  # 运行机制  # 的是  # 数据存储  # 是一个  # 链表  # 新消息  # 就会  # 来了  # 是一种  # 让我们  # 一句  # 在这 


相关栏目: 【 网站优化151355 】 【 网络推广146373 】 【 网络技术251813 】 【 AI营销90571


相关推荐: 详解Android——蓝牙技术 带你实现终端间数据传输  焦点电影公司作品,电影焦点结局是什么?  高防服务器租用指南:配置选择与快速部署攻略  标准网站视频模板制作软件,现在有哪个网站的视频编辑素材最齐全的,背景音乐、音效等?  音乐网站服务器如何优化API响应速度?  laravel怎么配置Redis作为缓存驱动_laravel Redis缓存配置教程  北京企业网站设计制作公司,北京铁路集团官方网站?  Laravel用户密码怎么加密_Laravel Hash门面使用教程  韩国网站服务器搭建指南:VPS选购、域名解析与DNS配置推荐  制作电商网页,电商供应链怎么做?  Laravel Octane如何提升性能_使用Laravel Octane加速你的应用  教你用AI润色文章,让你的文字表达更专业  高性价比服务器租赁——企业级配置与24小时运维服务  HTML 中如何正确使用模板变量为元素的 name 属性赋值  Laravel项目结构怎么组织_大型Laravel应用的最佳目录结构实践  ai格式如何转html_将AI设计稿转换为HTML页面流程【页面】  如何在宝塔面板中修改默认建站目录?  HTML5空格和nbsp有啥关系_nbsp的作用及使用场景【说明】  java中使用zxing批量生成二维码立牌  CSS3怎么给轮播图加过渡动画_transition加transform实现【技巧】  如何自己制作一个网站链接,如何制作一个企业网站,建设网站的基本步骤有哪些?  Laravel如何理解并使用服务容器(Service Container)_Laravel依赖注入与容器绑定说明  Laravel如何实现数据导出到CSV文件_Laravel原生流式输出大数据量CSV【方案】  如何在万网主机上快速搭建网站?  无锡营销型网站制作公司,无锡网选车牌流程?  Laravel如何使用Service Provider注册服务_Laravel服务提供者配置与加载  Laravel怎么写单元测试_PHPUnit在Laravel项目中的基础测试入门  如何在橙子建站中快速调整背景颜色?  Laravel Sail是什么_基于Docker的Laravel本地开发环境Sail入门  清除minerd进程的简单方法  公司门户网站制作流程,华为官网怎么做?  Gemini手机端怎么发图片_Gemini手机端发图方法【步骤】  Laravel Eloquent模型如何创建_Laravel ORM基础之Model创建与使用教程  Windows10电脑怎么查看硬盘通电时间_Win10使用工具检测磁盘健康  如何彻底删除建站之星生成的Banner?  谷歌浏览器下载文件时中断怎么办 Google Chrome下载管理修复  如何快速搭建高效服务器建站系统?  logo在线制作免费网站在线制作好吗,DW网页制作时,如何在网页标题前加上logo?  详解Nginx + Tomcat 反向代理 如何在高效的在一台服务器部署多个站点  如何挑选高效建站主机与优质域名?  香港服务器建站指南:外贸独立站搭建与跨境电商配置流程  深圳网站制作平台,深圳市做网站好的公司有哪些?  如何用搬瓦工VPS快速搭建个人网站?  Laravel怎么实现微信登录_Laravel Socialite第三方登录集成  高防服务器租用首荐平台,企业级优惠套餐快速部署  香港服务器网站测试全流程:性能评估、SEO加载与移动适配优化  Android中AutoCompleteTextView自动提示  Laravel如何记录日志_Laravel Logging系统配置与自定义日志通道  怎么用AI帮你为初创公司进行市场定位分析?  如何在Windows 2008云服务器安全搭建网站?