相信每一个app都要用上Handler,但是你对他又有多少理解呢?
最初,我们做欢迎界面的时候特别喜欢用Handler延时3秒进入主界面。我们也喜欢用Hanlder更新UI。但是你真的认识理解Handler吗?
今天我们就从我们熟悉的地方来重新认识这个老朋友,废话讲完,上代码
public class WelcomeActivity extends Activity{
Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
Intent intent = new Intent(WelcomeActivity.this,MainActivity.class);
startActivity(intent);
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
handler.sendEmptyMessageDelayed(0, 3000);
}
}
很简单的代码,三秒后自动跳动MainActivity。我们看sendEmptyMessageDelayed()到底做了什么?
我们接着走
继续
最终
是不是发现不管我们调用哪一种send方法,最后都走的是sendMessageAtTime();
我们接着追踪queue.enqueueMessage(msg, uptimeMillis),不搞清楚我们誓不罢休。
我们转战MessageQueue类,在此之前要先说一说Message类
主要的参数和方法就是 arg1,arg2,obj,what,Message(),obtain().相信我们在平时使用的时候也用过,
- arg1和arg2用来传递int类型的数据
- what : User-defined message code so that the recipient can
identify 作为标识符的 - obj 传递各种类型参数
- int flags;
- long when; 时间要发生的准确时间
- Bundle data; 可以 传递大量的 数据
- Handler target;这个下面会下次介绍
- Runnable callback;回调函数
- Message next;有时我们存储这些Message 的链接列表
我们回头看MessageQueue
MessageQueue这个类是Message的一个容器,我一直认为他是个数组或者集合之类。我们看源码看它是否如我假设的那样。
这是对外接口,
根据名称我们可以看出可以增加和删除IdleHandler
那我们的Message的增加删除在哪里呢?
我们来看addIdleHandler()
/**
* Add a new {@link IdleHandler} to this message queue. This may be
* removed automatically for you by returning false from
* {@link IdleHandler#queueIdle IdleHandler.queueIdle()} when it is
* invoked, or explicitly removing it with {@link #removeIdleHandler}.
*
* <p>This method is safe to call from any thread.
*
* @param handler The IdleHandler to be added.
*/
public void addIdleHandler(@NonNull IdleHandler handler) {
if (handler == null) {
throw new NullPointerException("Can't add a null IdleHandler");
}
synchronized (this) {
mIdleHandlers.add(handler);
}
}
enqueueMessage()函数如下
boolean enqueueMessage(Message msg, long when) {
//msg.target target的类型是Handler 每一个Message 都必须有这个target
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) {
//当Thread挂掉后 也是无法发送消息的 mag会被回收
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已经被使用
msg.markInUse();
//赋值绝对时间 给msg
msg.when = when;
Message p = mMessages;
//是否需要被唤醒
boolean needWake;
//从下面就可以看出messge的存储是链表的形式
这样我们就把Message存储起来了
//如果messgae p 设定的时间为0 或者或者新添加的消息的执行时间比消息队列头的消息的执行时间还早,就把消息添加到消息队列头
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;
}
我们通过enqueueMessage把我们发送的Message存储起来后,这些Message又是什么时候被调用出来的呢?
这就需要我们分析Looper源码了。
在这里先简单给大家理清楚Looper 、Message 、MessageQueue、Handler的关系了,借用网上的一张图
Looper可以循环从MessageQueue(Message池)中读取消息Message。Handler向MessageQueue里添加 Messge。那么Handler怎么Messge通信呢?因为Messge里target这个属性来存放handler,Handler可以通过回到函数msg.target.dispatchMessage进行处理HandlerMessage方法里的任务。
那我们接着分析Looper源码,来来来接着干~~~
首先是 prepare()、
public static void prepare() {
prepare(true);
}
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
#//sThreadLocal 他相当与一个容器 把Thread 和对应Looper信息保存起来
sThreadLocal.set(new Looper(quitAllowed));
}
//Looper 需要 一个线程对象和 MessgeQueue对象,这里也就和我们的MessageQueue联系起来了
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
sThreadLocal.set(new Looper(quitAllowed));
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
我们可以看到 sThreadLocal 把Loooper信息保存起来了。
接着是Looper.loop();
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
public static void loop() {
//looper对象
final Looper me = myLooper();
if (me == null) {
//从sThreadLocal里面取出Looper如果没有 则报错
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
//从me 获取得到 MessageQueue
final MessageQueue queue = me.mQueue;
//确保thread 在localprocess里的唯一性
// 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();
//looper 不断的从MessageQueue 中获取Message
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();
}
}
在此处理系统消息,我们可以看到他调用了handleCallback回调函数
/**
* Handle system messages here.
*/
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
//这个就是我们平时重写的handleMessage()函数
public void handleMessage(Message msg) {
}
//这里这个callback ,我们会发现我们平时没有怎么见过 其实这个是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;
}
我们发现 确实 平时的CallBack为null,那么我们来看一下Callback 类,Handler的内部接口
public interface Callback {
public boolean handleMessage(Message msg);
}
那我们就写一个简单的demo来看一下
Handler handlre = new Handler(new Callback() {
@Override
public boolean handleMessage(Message msg) {
Intent intent = new Intent(WelcomeActivity.this,MainActivity.class);
startActivity(intent);
return false;
}
});
注意下 这个handleMessage是有返回值的根据上面的返回值判断,如果为FALSE那么依然会调用 handleMessage(msg);
通过以上我们讲了一圈的调用,可是不知道大家发现没有还有一个很重要的问题没有将,那就是怎么根据时间来取Message。那就需要 Looper类里Message msg = queue.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;
}
}
好了,终于把这个流程走完了。
那么我们说一下 一个特别容易忽视的问题,我们Handler都必须有,且能有一个Looper,那么我们平时并没有用到looper,那是因为 Ui线程及ActivityThread已经在Main函数里给我们做好了。所以如果我们想要在别的线程用Handler必须有Looper。代码如下
new Thread()
{
private Handler handler;
public void run()
{
Looper.prepare();
handler = new Handler()
{
public void handleMessage(android.os.Message msg)
{
Log.e("TAG",Thread.currentThread().getName());
};
};
其实Handler不仅可以更新UI,也可以在一个子线程中去创建一个Handler,然后使用这个handler实例在任何其他线程中发送消息,最终处理消息的代码都会在你创建Handler实例的线程中运行。
最后还有一个问题就是ThreadLocal,ThreadLocal可以在多个线程中互不干扰地存储和修改数据,我这里做了一个小demo
public class MainActivity extends Activity {
private static String TAG = "handler";
private ThreadLocal<Boolean> mBOoleanThreadLocal = new ThreadLocal<Boolean>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBOoleanThreadLocal.set(true);
Log.e(TAG,"UI-Thread"+ mBOoleanThreadLocal.get()+"");
new Thread("Thread1"){
public void run() {
mBOoleanThreadLocal.set(true);
Log.e(TAG, "Thread1"+mBOoleanThreadLocal.get()+"");
// handler.sendEmptyMessageDelayed(what, delayMillis);
};
}.start();
new Thread("Thread2"){
public void run() {
mBOoleanThreadLocal.set(false);
Log.e(TAG, "Thread2"+mBOoleanThreadLocal.get()+"");
};
}.start();
Log.e(TAG,"UI-Thread"+ mBOoleanThreadLocal.get()+"");
}
}
我们按照我们最初的步骤,从Handlle 分析到MessageQueue 然后分析Message,然后返回来分析Looper,根据关系图我们了解了他们之间的关系。其实原理很简单,Looper一直在循环的从MessageQueue
里面拿出Message,然后通过调用回调方法,执行HandMessage函数,就是我们自己实现的方法。Handler把Message向MessageQueue里面。再把这张神图贴出来。很简单吧。当然肯定有不懂的地方,但是我们主要的目的是了解Handler的机制,及源码的分析。有不懂的地方及时百度,反复阅读源码,没什么能难得住一个想学的人的。下一篇我们分析Binder机制,敬请期待。。。