Android中Handler原理详解以及一些想法
- 如何使用
Hander用于的是线程之间得发送消息,主要用于更新UI,因为android中UI是非线程安全的,为什么要这样设计其实我觉得不难想到,如果设计成线程安全,UI是用户交互得最多的地方,所以必须要快速响应,如果线程安全,会在频繁操作时让线程锁住,导致响应缓慢,这是不可容忍的,所以设计成非线性安全,再提供一个Handler来切换线程,显得灵活很多
凡事都是想知道其原理的前提下得先知道它怎么用
首先在主线程中新建一个handler
handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
};
这是在主线程,如果在子线程在创建handler时要先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.set(new Looper(quitAllowed));
}
可知如果sThreadLocal.get()!=null则说明此线程已经存在looper了,好什么是sThreadLocal,其实它是一个ThreadLocal,我把它理解为中央银行,它里面可以保存每个线程的东西,也就是说,这里面保存着每个线程的数据,但是如果一个子线程新建时是不会有looper的,所以看抛得异常我们也知道一个线程只能有一个looper,然后会新建一个looper,好,我们看看looper的构造函数
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
好吧在这里面新建了一个messageQueue,消息队列吗,用于存放消息的嘛然后保存当前的线程,所以我在这里会猜想,Handler能够跨线程与Looper密切相关
ok,在这里我们知道了
Looper.prepare()做了一些什么
首先将looper保存进去了ThreadLocal,其实在looper的构造函数中新建了消息队列和当前线程
其结构如下,相当于我在英航把这个Looper保存了进去,这个Looper有消息队列和当前线程
ok,下一步是新建Handler,我们看下Handler的构造函数
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 " + Thread.currentThread()
+ " that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
ok ,mLooper = Looper.myLooper();让我们看看mLooper = Looper.myLooper();这个方法
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
原来如此,此时它将银行里面的looper取了回来,这是懂了,为什么要先looper.prepare,因为你之前都不把它存进去,那你现在取的肯定为空,就会出现Can’t create handler inside thread " + Thread.currentThread()+ " that has not called Looper.prepare()");这样的错误提示
然后接下来就是,将looper中的MesageQuene取出来
接下来解释hander的发送消息了,一般有post和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);
}
调用enqueueMessage这个方法
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
注意将msg也就是Message的target设置成了Handler,这个在之后会用到,然后调用MessageQuene的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按照时间先来后到入队列
ok走到这里,其实我们已经把消息放进了messagequene中,那要怎么取出来了,其实就是用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();
// Allow overriding a threshold with a system prop. e.g.
// adb shell 'setprop log.looper.1000.main.slow 1 && stop && start'
final int thresholdOverride =
SystemProperties.getInt("log.looper."
+ Process.myUid() + "."
+ Thread.currentThread().getName()
+ ".slow", 0);
boolean slowDeliveryDetected = false;
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;
long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs;
if (thresholdOverride > 0) {
slowDispatchThresholdMs = thresholdOverride;
slowDeliveryThresholdMs = thresholdOverride;
}
final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0);
final boolean logSlowDispatch = (slowDispatchThresholdMs > 0);
final boolean needStartTime = logSlowDelivery || logSlowDispatch;
final boolean needEndTime = logSlowDispatch;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
final long dispatchEnd;
try {
msg.target.dispatchMessage(msg);
dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
if (logSlowDelivery) {
if (slowDeliveryDetected) {
if ((dispatchStart - msg.when) <= 10) {
Slog.w(TAG, "Drained");
slowDeliveryDetected = false;
}
} else {
if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, "delivery",
msg)) {
// Once we write a slow delivery log, suppress until the queue drains.
slowDeliveryDetected = true;
}
}
}
if (logSlowDispatch) {
showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", 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(),同样 queue.next()也是一个同步操作,会在messagequene中返回要处理的消息,这个时候会走到msg.target.dispatchMessage(msg)这里,还记得,msg.target设置为handler的,所以这种时候会处理,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.callback,这是什么了,上面我们跟下来也没发现啊,其实在hanlder.post中有这样一个东西
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
这里有个getPostMessage()方法我们点进去看看
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
哈哈牛逼不,这个message,callback就是我们post进去的runable,这个时候就会执行handleCallback(msg);
private static void handleCallback(Message message) {
message.callback.run();
}
优秀,这样他就执行了,
然后是callback,其实在Hanlder构造函数中你可以传递一个callback,这样他就在可以回调出去了,就先来就是hander的handlemessage方法了
流程
总结 其实不仅仅了解其流程,更重要的是学习一种设计方法,我觉得这种设计模式挺牛逼的,msg.target.dispatMessage,当时看到了就觉得好牛逼的设计