首页 文章 精选 留言 我的

精选列表

搜索[异步],共10004篇文章
优秀的个人博客,低调大师

Android 异步消息分发机制

Android的消息机制–主要是指 Handler 的运行机制 和 MessageQueue 、 looper 的工作过程。 MessageQueueMessageQueue 消息队列,用来存储消息,虽然称为消息队列,但是它的存储结构是采用 单链表的数据结构来存储消息队列的。 包含两个操作插入(enqueueMessage) 和 读取(next) enqueueMessage :往消息链表 中插入一条信息 next:从消息列表中读取一天消息,并将其从消息队列中移除,next方法是一个无限循环的方法,如果消息列表里没有消息,那么会一直阻塞在这里。 LooperLooper 消息循环,用来处理消息。 Looper 会不停的从 MessageQueue 中查看是否有新的消息,如果有新消息就会立即处理Looper.java private Looper(boolean quitAllowed) { mQueue = new MessageQueue(quitAllowed); mThread = Thread.currentThread(); } 在 Looper 的构造方法会创建一个MessageQueue,消息队列,然后将当前线程的对象保存起来。 public static @Nullable Looper myLooper() { return sThreadLocal.get(); } 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)); } 问题 为什么Looper.prepare() 不能被调用两次?答:因为每次调用 Looper.prepare() 的时候的都会判断 ThreadLocal是否已经存储当前的 Looper 对象,如果已经存在就会抛出异常。 /** * Run the message queue in this thread. Be sure to call * {@link #quit()} to end the 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 final Printer logging = me.mLogging; if (logging != null) { logging.println(">>>>> Dispatching to " + msg.target + " " + msg.callback + ": " + msg.what); } final long traceTag = me.mTraceTag; if (traceTag != 0 && Trace.isTagEnabled(traceTag)) { Trace.traceBegin(traceTag, msg.target.getTraceName(msg)); } try { msg.target.dispatchMessage(msg); } finally { if (traceTag != 0) { Trace.traceEnd(traceTag); } } 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 方法为空,即queue.next() 为空。Looper 调用 quit 方法或者 quitSafely 方法,通知消息队列退出,会使 MessageQueue 的 next 方法 返回为空。 loop 调用 MessageQueue 的 next 方法获取新的消息,如果 没有消息,next 方法会一直阻塞在那里,导致 loop 方法也会一直阻塞在那里。 如果 next 方法返回了新的消息,Looper 就会处理新的消息,调用 msg.target.dispatchMessage(msg),msg.target 就是发送这条消息的 Handler 对象(Handler 中有讲解)。这样就把代码逻辑切换到指定线程去执行了。 3. ThreadLocal线程内部的数据存储类, 通过它可以在指定的线程存储数据,而且存储后,只能在指定线程获取存储的数据,其他线程无法获取。 应用:当某些数据是以线程为作用域,并且不同线程具有不同数据 存在Looper中,并不是线程,作用是在每个线程中存储数据 问题:Handler内部是如何获取当前线程的 Looper 的?Handler.java 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; } 答:Handler 通过 ThreadLocal 获取每个线程的 Looper. ThreadLocal 可以在不同线程中互不干扰的存储并提供数据。 在调用 Looper.prepare() 的时候 “sThreadLocal.set(new Looper(quitAllowed));” - 创建了一个 Looper 实例并将一个Looper的实例放入了ThreadLocal 存储。然后在 Handler 中 调用“mLooper = Looper.myLooper();”-从 sThreadLocal.get() 获取到 Looper 对象。 问题:主线程中为什么可以默认使用Handler?答: 线程默认是没有Looper 的 ,如果要使用 Handler ,就必须为线程创建 Looper. 但是主线程,也就是 UI 线程,它就是 ActivityThread, ActivityThread 被创建的时候默认会初始化 Looper,当前UI线程调用了Looper.prepare()和Looper.loop()方法. Handler主要工作:发送和接收消息; public final boolean sendMessage(Message msg) { return sendMessageDelayed(msg, 0); } public final boolean sendMessageDelayed(Message msg, long delayMillis) { if (delayMillis < 0) { delayMillis = 0; } return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis); } 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 收到消息,通过msg.target.dispatchMessage(msg) 交给 Handler 处理。 上面 enqueueMessage 方法首先 “msg.target = this;” 会把 this 赋值给 msg.target ,也就是说 把Handler 赋值给 msg的 target 属性。 public void dispatchMessage(Message msg) { if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); } } 首先会检查 Message的 callback 是否为 null,不为空就处理通过 handleCallback 来处理消息。 callback 是一个 Runnable 接口,就是 Handler 的 post 方法传递的 Runnable 参数 private static void handleCallback(Message message) { message.callback.run(); } 举个栗子 第一种handler 的使用方式,post方法 Handler mHandler = new handler(); mHandler.post(new Runnable() { @Override public void run() { Log.e("TAG", Thread.currentThread().getName()); mTxt.setText("yoxi"); } }); 其次 查看 mCallback 是否为空,mCallback 是个接口 public interface Callback { public boolean handleMessage(Message msg); } Callback 提供另一种使用 Handler 的方式,不想派生Handler的子类,可以通过 Callback 来实现。 举个栗子 第二种使用 Handler 的方式 private Handler mHandler = new Handler() { public void handleMessage(android.os.Message msg) { switch (msg.what) { case value: break; default: break; } }; }; 最后,调用 Handler的 handleMessage 方法来处理消息。 原文发布时间为:2018-08-25本文来自云栖社区合作伙伴“Android开发中文站”,了解相关信息可以关注“Android开发中文站”。

资源下载

更多资源
Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

腾讯云软件源

腾讯云软件源

为解决软件依赖安装时官方源访问速度慢的问题,腾讯云为一些软件搭建了缓存服务。您可以通过使用腾讯云软件源站来提升依赖包的安装速度。为了方便用户自由搭建服务架构,目前腾讯云软件源站支持公网访问和内网访问。

Nacos

Nacos

Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。

Sublime Text

Sublime Text

Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等。还可自定义键绑定,菜单和工具栏。Sublime Text 的主要功能包括:拼写检查,书签,完整的 Python API , Goto 功能,即时项目切换,多选择,多窗口等等。Sublime Text 是一个跨平台的编辑器,同时支持Windows、Linux、Mac OS X等操作系统。

用户登录
用户注册