您的位置:首页 > 产品设计 > UI/UE

从源码中分析Handler, Looper, Message, MessageQueue之间的关系

2017-08-02 16:52 501 查看
 从源码中分析Handler, Looper, Message, MessageQueue之间的关系
        android 中耗时任务一般都放在子线程中执行,像数据存储, 文件读写, 网络访问下载等;而android中UI的更新须在主线程中执行,而Handler 则是解决方案之一;相信大家在平时开发中用的很熟练了。 那么本文将从源码中,分析一下其工作原理。

Handler 发送消息

Looper 检测MessageQueue中是否有Message的消息

Message 存放数据或标记的对象

MessageQueue 存放Message的管道,先进先出

一、 Looper :一个线程只有一个Looper, 由ThreadLocal保存

   1. 创建Looper对象有2种方式:

          (1)Looper.prepare()
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));
}


           //application 的主线程中的looper, 由android environment创建, 无需我们创建

           (2)Looper.prepareMainLooper
public static void prepareMainLooper() {
prepare(false);    //此处false 在MessageQueue quit()方法中用到,主线程不能主动退出MessageQueue(移除等待的消息)
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}

   2.返回主线程中的looper对象

public static Looper getMainLooper() {
synchronized (Looper.class) {
return sMainLooper;
}
}


   3. 在prepare中创建Looper对象,并将其放入ThreadLocal中
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));
}


   4.  Looper私有构造方法中,创建了消息队列,并且获取当前线程
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
m
4000
Thread = Thread.currentThread();
}


   5.使用ThreadLocal 存储looper的好处是, 在存储对象时,一个线程对应一个值, 不会影响其他线程.

   6. Looper是用来监听MessageQueue中 有无消息; 当Looper,MessageQueue准备就绪后,调用Looper.Loop() 开启死循环.
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the loop.
*/
public static void loop() {
final Looper me = myLooper();   //获取当前Looper是否为空
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
final MessageQueue queue = me.mQueue;   //获得当前线程中的MessageQueue 消息队列

// 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);   // 此时会调用Handler 中的dispatchMessage, 2种情况post run 以及 handlerMessage

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.recycle();  //释放消息,防止占用内存
}
}


二、 Handler  一般从子线程中发送,而Looper与MessageQueue为主线程的队列,从而可以更新ui

    1. 一般我们使用Handler 会new Handler(), 实现handleMessage方法.
private Handler mainHandler = new MainHandler();
private class MainHandler extends Handler {
@Override
public void handleMessage(Message msg) {
Log.i(TAG, "handleMessage what=" + msg.what);
switch (msg.what) {
}
}
}


   2.Handler.java 中的构造方法
public Handler(Callback callback, boolean async) {
if (FIND_POTENTIAL_LEAKS) {  //代码中默认false
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();  //返回当前Looper对象.按照顺序来讲,应该先创建Looper.prepare  最后调用Looper.Loop()
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;  //获得Looper中创建的消息队列
mCallback = callback;
mAsynchronous = async;
}


   3. Handler发送消息有2种方式

          (1)mHandler.post(new Runnable() {

                     @Override

                       public void run() {

                           //此run方法不是线程,仅仅是一个Runnable方法;实现内容,此处已经是主线程中,可更新UI

                     }

            });

              sendMessageDelayed(getPostMessage(r), long mm)    //此处将Runnable赋值给msg.callback 对象

              private static Message getPostMessage(Runnable r) {

                 Message m = Message.obtain();

                 m.callback = r;

                 return m;

              }

              sendMessageAtTime(Message msg, long mm)

       (2)mHandler.sendMessage(Message msg)                              sendEmptyMessage(int what)

               sendMessageDelayed(Message msg, long mm)              sendEmptyMessageDelayed(int what, long mm);

               sendMessageAtTime(Message msg, long mm)               sendMessageAtTime(Message msg, long mm)

     从上面方法的调用可以看出,不管post 还是send 都会走sendMessageAtTime(); 其他方法是对延时的处理
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
MessageQueue queue = mQueue; //构造方法中通过looper获得的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);
}

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);  //插入消息队列中
}


       //此处就是最终返回给上层实现handler方法
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);  //调用开发者写的Runnable方法进行UI更新等操作
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);    //调用到开发者实现的handleMessage方法进行UI更新等操作
}
}

三、 Message  传递数据的载体

   Message msg = new Message();

   msg.what         //int   一般与switch连用

   msg.object       //传递对象 获得时要强转一下

   msg.arg1         //int

   msg.arg2         //int

   Handler target

   Runnable callback

四、 MessageQueue  消息队列,主要介绍存入enqueueMessage, 取出(next)       

       1.  enqueueMessage

       将消息插入链表中,消息链表是按时间进行排序的,所以主要是在比对Message携带的when信息。消息链表的首个节点对应着最先将被处理的消息,如果Message被插到链表的头部了,就意味着队列的最近唤醒时间也应该被调整了,因此needWake会被设为true,以便代码下方可以走进nativeWake()。

   
boolean enqueueMessage(Message msg, long when) {
if (msg.isInUse()) { //判断当前消息是否在使用
throw new AndroidRuntimeException(msg + " This message is already in use.");
}
if (msg.target == null) {   //判断handler是否为空
throw new AndroidRuntimeException("Message must have a target.");
}

synchronized (this) {
if (mQuitting) {  //正在退出移除消息
RuntimeException e = new RuntimeException(
msg.target + " sending message to a Handler on a dead thread");
Log.w("MessageQueue", e.getMessage(), e);
return false;
}

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;
}


     2.  next

Message next() {
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}

// We can assume mPtr != 0 because the loop is obviously still running.
// The looper will not call this method after the loop quits.
nativePollOnce(mPtr, 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;  //将链表指向msg的下一个,重新设置消息队列的头部
} else {
mMessages = msg.next;
}
msg.next = null;    //此时msg为需为null,因为该msg要被处理
if (false) Log.v("MessageQueue", "Returning message: " + msg);
msg.markInUse();     //设置了正在使用该Message
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);
}
// 处理idle handlers部分
// 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("MessageQueue", "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;
}
}





                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐