1.前言
Handler Message是android中比较常用的异步消息机制,通常我们对UI更新,对异步操作运算,很多时候都采用Handler来实现,现在我们探讨一下Handler,Message以及Looper的消息机制。
2.一般使用方法
通常我们使用Handler的一般流程是:
创建Handler对象,并在handleMessage实现消息接受的具体实现;
private final static int MSG_UPDATE = 0x01;
Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_UPDATE:
//处理逻辑
break;
}
}
};
创建Message对象,并设置Message属性;
Message msg = Message.obtain();
msg.what = MSG_UPDATE;
通过Handler的sendMessage方法发送消息对象。
mHandler.sendMessage(msg);
通过在Activity或者其他类里面创建一个Handler对象后,通过在不同时刻不同需求,通过发消息的形式,对界面进行更新或实现其他的业务逻辑。那Android Framework给开发者提供的这种简单便利的Handler消息异步机制是怎么实现的呢?
3.源码分析
3.1 Handler 部分
在创建Handler对象时候,到底经历了一个什么过程呢?
我们结合android-26源码进行源码分析。
首先,通过代码跟踪,实例化Handler时候,实际上是调用了
public Handler() {
this(null, false);
}
然后实质上是调用了
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;
}
这里我们也看一下myLooper方法
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
从上面的源码可以看出,我们在实例化Handler时候,实际上是从sThreadLocal对象中取出Looper。如果sThreadLocal中有Looper存在就返回Looper;若Looper为空,直接抛出Can’t create handler inside thread that has not called Looper.prepare()的异常。
那为什么我们在创建时候没有报异常,而可以取到Looper对象呢?这是应为我们的Activity里面已经调用了Looper.prepareMainLooper();我们可以通过查看ActivityThread的源码的main入口来看,
public final class ActivityThread {
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
if (activity != null) {
activity.attach(appContext, this, ..., );
public static void main(String[] args) {
// 在这儿调用 Looper.prepareMainLooper, 为应用的主线程创建Looper
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
Looper.loop();
}
}
这里的ActivityThread.main方法也是我们通常说的android应用程序的入口。而Activity的生命周期的开始是在
ActivityThread .attach(false)后开始的,所以我们在Activity里面创建Handler实例时候,就已经有了一个Looper,而且是主线程Looper。通过源码我们可以很清楚看出。
/**
* Initialize the current thread as a looper, marking it as an
* application's main looper. The main looper for your application
* is created by the Android environment, so you should never need
* to call this function yourself. See also: {@link #prepare()}
*/
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
这里ActivityThread.main()中调用 Looper.prepareMainLooper, 为应用的主线程创建Looper。
到这里Handler的主要源码就到此为止,后面有些注意点要补充的。
3.2 Message 部分
Message源码部分比较简单,Message类实现了Parcelable接口,可以理解为比较普通的实体类。
主要属性有:
public final class Message implements Parcelable {
public int what;
public int arg1;
public int arg2;
public Object obj;
...
long when;
Bundle data;
Handler target;
Runnable callback;
Message next;
}
Message类本身没有什么多大探究的,现在我们关系的是Message是怎么发送出去的?
那么我们现在要看看Handler的sendMessage方法了。这里又要到Handler源码里面取查看相关的方法实现。重点是消息的发送的实现。
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
接着查看sendMessageDelayed
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
接着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);
}
从这里看出,获取到当前消息队列queue,然后将msg消息加入到消息队列queue,这里的消息队列其实就是一个单向链表。我们看看enqueueMessage方法
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
这里我们可以清楚看出msg.target就是Handler对象。
此时再看MessageQueue的enqueueMessage方法
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;
}
消息Message通过调用enqueueMessage方法进行入队加入MessageQueue并且将所有的消息按时间来进行排序。
消息的加入算是明白了,但是消息的是怎么取出来,然后进行处理的呢?接下来一起看Looper源码。
3.3 Looper 部分
在上一节分析ActivityThread源码时,我们很清楚发现,main方法里面不仅调用了 Looper.prepareMainLooper,而且也调用了Looper.loop方法。查看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 slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
final long traceTag = me.mTraceTag;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
final long end;
try {
msg.target.dispatchMessage(msg);
end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
if (slowDispatchThresholdMs > 0) {
final long time = end - start;
if (time > slowDispatchThresholdMs) {
Slog.w(TAG, "Dispatch took " + time + "ms on "
+ Thread.currentThread().getName() + ", h=" +
msg.target + " cb=" + msg.callback + " msg=" + msg.what);
}
}
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();
}
}
首先我们通过myLoop获取到当前loop,然后从中拿到MessageQueue实体对象,然后通过for (;;) 循环语句一直循环queue.next()获取下一个Message,若MessageQueue为空,则队列阻塞。
通MessageQueue中拿到Message对象后,通调用 msg.target.dispatchMessage(msg)进行消息分发处理。这里的msg.target就是Handler本身,前面已经讲过了。
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
当msg.callback != null是执行handleCallback;当callback 为空,调用Handler的handleMessage()方法。这也是在实例化Handler里面的回调处理handleMessage方法。至此,整个Handler、Message、Looper源码已经讲完了,下一节我们要进行一些补充和归纳。
4.补充与疑问
4.1 Handler.post方法不一定都主线程运行,但是能更新UI
首先我们查看post方法的具体实现
/**
* Causes the Runnable r to be added to the message queue.
* The runnable will be run on the thread to which this handler is
* attached.
*
* @param r The Runnable that will be executed.
*
* @return Returns true if the Runnable was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting.
*/
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
通过源码的注释可以看出,在调用post方法时候,创建的Runnable实例是在所属的Handler对象线程里面运行的。如果Handler不是主线程,那么post后的runnable对象也不在主线程里面运行。
例如,我们可以这样做个实验
public class MainActivity extends AppCompatActivity {
private final static String TAG = MainActivity.class.getSimpleName();
HandlerThread mHandlerThread = new HandlerThread("MyThread");
Handler mHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHandlerThread.start();
mHandler = new Handler(mHandlerThread.getLooper());
long id = Thread.currentThread().getId();
Log.d(TAG, "Main ThreadName:" + Thread.currentThread().getName() + " ThreadId:" + id);
new Thread(new Runnable() {
@Override
public void run() {
mHandler.post(new Runnable() {
@Override
public void run() {
long id = Thread.currentThread().getId();
Log.d(TAG, "Thread ThreadName:" + Thread.currentThread().getName() + " ThreadId:" + id);
Toast.makeText(MainActivity.this, "nihao", Toast.LENGTH_SHORT).show();
}
});
}
}).start();
}
}
打印结果是:
我们可以很清楚看出,运行在post里面的线程的ThreadId并不是主线程Id=1,也就是说,此时的post运行不在主线程里面。但是Toast能正常显示提示,没有报异常。
那为什么我们经常在Activity里面取调用post更新UI不报错了?
这跟我们在子线程中更新UI的方法一样了,如下面我们常在子线程中更新UI的代码
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
Toast.makeText(MainActivity.this, "nihao", Toast.LENGTH_SHORT).show();
Looper.loop();
}
}).start();
4.2 ThreadLocal
在一个android应用中编程,我们通常需要很多handler消息机制来实现各种功能,但是我们怎样保证handler对应的looper的唯一和handler消息的多线程问题了,这里就引出了ThreadLocal。
ThreadLocal使用场合主要解决多线程中数据因并发产生不一致的问题。ThreadLocal以空间换时间,为每个线程的中并发访问的数据提供一个副本,通过访问副本来运行业务,这样的结果是耗费了内存,但大大减少了线程同步所带来的线程消耗,也减少了线程并发控制的复杂度。
那么我们切换到Looper源码,很容易看到
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
实际上,我们每个线程的Looper都存放到ThreadLocal里面,可以把ThreadLocal看做是一个容器,容器里面存放着属于当前线程的变量。此时这里是存放当前线程的Looper变量。通过ThreadLocal,每个线程的Looper相互不影响而分别工作的。
关于ThreadLocal的详细,可以参考:http://blog.youkuaiyun.com/lufeng20/article/details/24314381
5.总结
看完了Handler、Message、Looper的分析后,我们总结一下三者的工作流程:
如图(ps:网上盗用图片),当我们创建好Handler后,通过Handler.sendMessage方法发送消息,此时将消息加载到MessageQueue,每次将新消息加入消息队列时候,消息队列根据时间进行排序,然后通过调用Looper.loop,里面for循环一直轮训消息队列的消息,如果没有消息,循环阻塞;如果有消息,取出消息后,进行dispatchMessage处理,调用Handler里面的runnable或者handleMessage方法进行UI或者逻辑处理,到达异步消息处理机制。。。