Android消息机制:Looper,MessageQueue,Message与handler
Android消息机制好多人都讲过,但是自己去翻源码的时候才能明白。
今天试着讲一下,因为目标是讲清楚整体逻辑,所以不追究细节。
Message是消息机制的核心,所以从Message讲起。
1.Message是什么?
看一个从消息池中取出一个msg的方法:
public static Message obtain(Handler h, int what,
int arg1, int arg2, Object obj) {
Message m = obtain();
m.target = h;
m.what = what;
m.arg1 = arg1;
m.arg2 = arg2;
m.obj = obj;
return m;
}
一个Message由下面几个部分构成:
arg1,arg2:用于传递简单整数类型数据时使用
obj:传递的数据对象,也就是内容
what:用户自定义的消息代码,接受者可以了解这个消息的信息,作为这个消息在MessageQueue中的唯一标示。
target:一个handler,顾名思义,这个message是谁的,是handler的,感觉handler很难理解的,可以把handler理解成一个辅助类。
注:也可以使用一个message初始化另外一个message,参数里可以加入message自定义的callback
2.Messsage在哪儿待着?
在MessageQueue中,顾名思义,这是一个Message的队列。我们通过next遍历这个队列来获得msg,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;
}
}
3.Message从何而来?
当我们定义了一个Message后,怎么把它放在MessageQueue里的?
这个时候我们需要一个第三方的帮手,于是handler登场了。
此处,我们需要先了解一下Hanlder的成员:
final MessageQueue mQueue;
final Looper mLooper;
final Callback mCallback;
可以看出,handler与一个MessageQueue和一个Looper相关联,定义一个回调用的的类。
handler的初始化函数:
public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
就是looper和looper对应 的messagequeue非配给了handler.
在Message.java中有这样一个函数:
public void sendToTarget() {
target.sendMessage(this);
}
可见,一个Message是由它的target,也就是一个handler调用sendMessage方法发送到MessageQueue中的,看Handler.java的源码是,会发现有好几种sendMessage方法,但最后都是调用了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);
}
可以看出,handler与一个MessageQueue相关联,如果handler关联的MessageQueue不为空的话,则入队。
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
在将消息入队的时候,通过msg.target = this将msg与handler关联起来。
4.Message去往何处?
这个问题很明显:Message怎么从MessageQueue里出来呀,由Looper从MessageQueue中取出来:
先看看Looper的构成:
public final class Looper {
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
private static Looper sMainLooper; // guarded by Looper.class
final MessageQueue mQueue;
final Thread mThread;
//......
}
可以看到Looper对应一个Thread和一个MessageQueue。
每一个Thread都对应有一个Looper么?是的,但不是默认的,如果不在主线程中,你想使用Looper的话,必须要调用一个函数:
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变量:sThreadLocl,设置属于当前线程的Looper。
这里,prepare方法巧妙地使用了ThreadLocal变量将Thread与一个Looper关联起来。
另外,注意looper中的两个方法:
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
} public static Looper getMainLooper() {
synchronized (Looper.class) {
return sMainLooper;
}
}
myLooper获得当前线程绑定的looper,没有则返回null。
getMainLooper获得主线程的looper,方便与主线程通信。
此时已经获得了一个Looper,准备开始取消息,调用Looper.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();
}
}
我们暂时不关注细节,之关心里面的两个函数的调用
第一个:Message msg = queue.next(),这里表示从MessageQueue中取到一条信息。
第二个:msg.tartget.dispatchMessage(msg)
就是将Messag交给了handler去使用dispatchMessage()去处理,那么我们就看一下这个方法:
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
当msg被从MessageQueue中分发出去后,被送给了handler,这时候handler会调用一个回调方法来处理这个message
(1).如果msg本身有默认的回调方法,则使用该方法处理。
(2).如果handler定义时顶一个默认的回调方法,
(3).如果上面两者都没有,则使用我们在定义Handler时重写的handleMessage方法。
大多数情况下,我们都使用第三种方式来处理信息。
5.两个简单的例子:
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView; public class UIActivity extends AppCompatActivity {
private TextView tv;
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
//因为Message Queue和Looper关系,后台其实是循环的调用handleMessage方法,所以加入swith case判断
switch (msg.what){
case 0:
tv = (TextView) findViewById(R.id.tv);
tv.setText((CharSequence) msg.obj);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ui);
findViewById(R.id.send_text).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//创建一个新的线程
new Thread(
new Runnable() {
@Override
public void run() {
Message msg = new Message();
msg.what = 0 ;
msg.obj = "来自另外一个线程的内容";
handler.sendMessage(msg);
}
}
).start();
}
});
}
}
第二个:
//MainActivity.java
public class MainActivity extends Activity {
public static final String TAG = "Main Acticity";
Button btn = null;
Button btn2 = null;
Handler handler = null;
MyHandlerThread mHandlerThread = null; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.button);
btn2 = (Button)findViewById(R.id.button2);
Log.d("MainActivity.myLooper()", Looper.myLooper().toString());
Log.d("MainActivity.MainLooper", Looper.getMainLooper().toString());
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mHandlerThread = new MyHandlerThread("onStartHandlerThread");
Log.d(TAG, "创建myHandlerThread对象");
mHandlerThread.start();
Log.d(TAG, "start一个Thread");
}
});
btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(mHandlerThread.mHandler != null){
Message msg = new Message();
msg.what = 1;
mHandlerThread.mHandler.sendMessage(msg);
} }
});
}
}
//MyHandlerThread.java
public class MyHandlerThread extends Thread {
public static final String TAG = "MyHT";
public Handler mHandler = null;
@Override
public void run() {
Log.d(TAG, "进入Thread的run");
Looper.prepare();
Looper.prepare();
mHandler = new Handler(Looper.myLooper()){
@Override
public void handleMessage(Message msg){
Log.d(TAG, "获得了message");
super.handleMessage(msg);
}
};
Looper.loop();
}
}
总结:
消息机制的核心是Message,在大多数情况下要放在MessageQueue中。
使用handler将msg发送到相应的Messagequeue中,并将二者关联。
每一个Thread中有一个Looper,Looper管理一个MessageQueue,像水泵一样不断的从MessageQueue中取出msg.
取出后调用msg相关联的handler的回调方法处理message。
这样就完成了进程间的消息机制,可以在不阻塞UI线程的情况下将耗时的操作使用Handler将message传递给子线程去处理。
本文只是大致梳理了一下消息机制的框架,总结一下自己最近看的,很多细节都没有讲,等再研究一段时间后再继续写几篇深入的博客,单独分析一下各个模块。
本文疏漏之处,还望大家指正,谢谢。
参考:
https://hit-alibaba.github.io/interview/Android/basic/Android-handler-thread-looper.html
https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/android/os/MessageQueue.java
https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/android/os/Message.java
https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/android/os/Looper.java
https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/android/os/Handler.java
http://www.cnblogs.com/plokmju/p/android_handler.html
Android消息机制:Looper,MessageQueue,Message与handler的更多相关文章
- Android开发之漫漫长途 ⅥI——Android消息机制(Looper Handler MessageQueue Message)
该文章是一个系列文章,是本人在Android开发的漫漫长途上的一点感想和记录,我会尽量按照先易后难的顺序进行编写该系列.该系列引用了<Android开发艺术探索>以及<深入理解And ...
- Android开发之漫漫长途 Ⅶ——Android消息机制(Looper Handler MessageQueue Message)
该文章是一个系列文章,是本人在Android开发的漫漫长途上的一点感想和记录,我会尽量按照先易后难的顺序进行编写该系列.该系列引用了<Android开发艺术探索>以及<深入理解And ...
- Android消息机制1-Handler(Java层)(转)
转自:http://gityuan.com/2015/12/26/handler-message-framework/ 相关源码 framework/base/core/java/andorid/os ...
- Android消息机制1-Handler(Java层)
一.概述 在整个Android的源码世界里,有两大利剑,其一是Binder IPC机制,,另一个便是消息机制(由Handler/Looper/MessageQueue等构成的). Android有大量 ...
- Android 进阶14:源码解读 Android 消息机制( Message MessageQueue Handler Looper)
不要心急,一点一点的进步才是最靠谱的. 读完本文你将了解: 前言 Message 如何获取一个消息 Messageobtain 消息的回收利用 MessageQueue MessageQueue 的属 ...
- Android消息机制探索(Handler,Looper,Message,MessageQueue)
概览 Android消息机制是Android操作系统中比较重要的一块.具体使用方法在这里不再阐述,可以参考Android的官方开发文档. 消息机制的主要用途有两方面: 1.线程之间的通信.比如在子线程 ...
- Android 消息机制 (Handler、Message、Looper)
综合:http://blog.csdn.net/dadoneo/article/details/7667726 与 http://android.tgbus.com/Android/androidne ...
- Android进阶——Android消息机制之Looper、Handler、MessageQueen
Android消息机制可以说是我们Android工程师面试题中的必考题,弄懂它的原理是我们避不开的任务,所以长痛不如短痛,花点时间干掉他,废话不多说,开车啦 在安卓开发中,常常会遇到获取数据后更新UI ...
- android 进程间通信 messenger 是什么 binder 跟 aidl 区别 intent 进程间 通讯? android 消息机制 进程间 android 进程间 可以用 handler么 messenger 与 handler 机制 messenger 机制 是不是 就是 handler 机制 或 , 是不是就是 消息机制 android messenge
韩梦飞沙 韩亚飞 313134555@qq.com yue31313 han_meng_fei_sha messenger 是什么 binder 跟 aidl 区别 intent 进程间 通讯 ...
随机推荐
- 【转】Cordova文件传输插件fileTransfer
任务要求: 访问手机的目录,选择一个文件,并使用该插件将指定文件传输到远程主机的某个指定目录中. HTML <!DOCTYPE html> <!-- Licensed to the ...
- 文件_ _android从资源文件中读取文件流并显示的方法
======== 1 android从资源文件中读取文件流并显示的方法. 在android中,假如有的文本文件,比如TXT放在raw下,要直接读取出来,放到屏幕中显示,可以这样: private ...
- gerrit: Error in POST /accounts/self/preferences
转载:https://code.google.com/p/gerrit/issues/detail?id=3157 1. Migrated from 2.8.6.1 to 2.10 2. In UI ...
- Spring4.1新特性——Spring MVC增强
目录 Spring4.1新特性——综述 Spring4.1新特性——Spring核心部分及其他 Spring4.1新特性——Spring缓存框架增强 Spring4.1新特性——异步调用和事件机制的异 ...
- Delphi完成的断点续传例子 转
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms ...
- NGUI之UIRoot
原文:http://www.tasharen.com/forum/index.php?topic=6710.0 概述 UIRoot总是放在NGUI UI层级的最上层. 它用来使UI的缩放变得更容易.w ...
- html字符字体转换
- JavaScript笔记杂谈篇(啥都有)
二维码缩放比例以43PX的倍数缩放最为标准. NuGet相关管理http://www.cnblogs.com/dudu/archive/2011/07/15/nuget.html 学习笔记: http ...
- wget cooikes 下载
2.下来用wget带cookie的命令下载,命令如下: wget -c –load-cookies=cookies.txt ”下载地址” -O “文件名” & [文件名处自己命名 ...
- 【JavaScript】前端插件
树形结构: http://www.jeasyui.com/documentation/index.php 网上有对这个插件的说明,总的来说这个插件将selected和checked作为两种状态: 1. ...