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