Android的异步消息分发队列之Handler、Message和Lopper之间的调用关系

零零散散做了很多的项目,发现连android的源码都没研究过,消息分发机制都没弄清楚,只是知道怎么用,但是具体的原理没弄清楚,最近又比较闲,导师没安排什么项目,开始自己坑自己的旅程,这也是我的第一篇技术日志,希望能把自己所理解的问题说清楚吧,有兴趣的朋友可以一起讨论讨论。

1.Looper

Looper类用来为一个线程开启一个消息队列,Looper对象通过MessageQueue来存放消息和事件,一个线程只能有一个Looper,对应一个MessageQueue。

1.1Looper的初始化

Looper就使一个普通线程变成Looper线程,就是循环工作的线程,我们经常需要一个线程不断循环,一旦有新任务则执行,执行完继续等待下一个任务。Looper线程的创建方法很简单:


public class LooperThread extends Thread {
@Override
public void run() {
// 将当前线程初始化为Looper线程
Looper.prepare();
// ...其他处理(线程工作体),如实例化handler
。。。。
// 开始循环处理消息队列
Looper.loop();
}
}

就是通过Looper.prepare()和Looper.loop()这两行代码实现了Looper线程。Looper.prepare():初始化消息队列;Looper.loop():让Looper开始工作,从消息队列里取消息,处理消息。我们开始一步步的分析源码,感受google工程师的设计。
首先,我们来看看Looper.prepare()的源码,Looper类是如何初始化的。


/** Initialize the current thread as a looper.

  • This gives you a chance to create handlers that then reference
  • this looper, before actually starting the loop. Be sure to call
  • {@link #loop()} after calling this method, and end it by calling
  • {@link #quit()}.
    */
    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));
}

Looper的初始化调用prepare无参方法,默认传入true的参数,然后调用prepare有参方法,首先判断sThreadLocal中是否已经存在Looper对象,PS:ThreadLocal理解成本地存储变量吧。如果没有就新建一个Looper对象,我们接下来看看Looper的有参构造方法,传入的quitAllowed参数是用于标识主线程和工作线程的Looper,后续讲到终止Looper时会详细说明。


private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}

可见Looper的构造函数就是创建一个MessageQueue(就是一个消息队列,并提供进队和出队的方法)和获得当前线程的实例。可以看出一个Looper对应一个MessageQueue。
接着再看看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();
    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();
    }
    }

首先看看myLooper()方法的源码:


/**

  • Return the Looper object associated with the current thread. Returns
  • null if the calling thread is not associated with a Looper.
    */
    public static @Nullable Looper myLooper() {
    return sThreadLocal.get();
    }

Handler通过myLoop方法得到Looper对象,然后获取Looper的MessageQueue消息队列对象。
接下来看看Message的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.
            //退出消息队列时设置为true,返回消息为空,然后loop()返回退出上述的死循环
            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;
    }
}

请注意上述的mQuitting,下面讲述退出消息队列时会说明。

1.2 Handler出队原理

可以看出就是得到上述过程prepare()中初始化的Looper对象。接着往下看,如果获得的Looper对象是空的,就抛出一个异常,所以新建Looper线程时一定要在调用Loop()方法之前先调用prepare()方法进行Looper的初始化。
往下看是for的死循环,它的出口在队列的Message为空的时候,消息分发是通过dispatchMessage()方法实现的,这是一个回调方法,msg.target在消息入队时进行初始化的,后续详解,我们现在看看Handler的dispatchMessage()的源码:


/**
* 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);
}
}

有三种调用方式:
1.调用handleCallback()方法,实际上就是调用post(Runnable r)Handler
传过来参数r的run()方法,代码如下所示,这里的Runnable并不是一个新启的线程,只是一个普通的类,可能因为它有一个已经定的run方法,所以google工程师才考虑使用它吧。


/**
* 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);
}

//这里进行callback的初始化
private static Message getPostMessage(Runnable r) {
    Message m = Message.obtain();
    m.callback = r;
    return m;
}

private static void handleCallback(Message message) {    
   message.callback.run();
}
mHandler.post(new Runnable() {
   @Override
   public void run() 
       Log.e("RunnableMessage", "RunnableMessage");
       mText.setText("success");
   }

});

2.执行Callback的handleMessage()方法,Callback是Handler类中的一个接口:


/**
* Callback interface you can use when instantiating a Handler to avoid
* having to implement your own subclass of Handler.
* @param msg A {@link android.os.Message Message} object
* @return True if no further handling is desired
*/
public interface Callback {
public boolean handleMessage(Message msg);
}

在Handler构造方法中传入已经实现了的Callback:


/**
* Constructor associates this handler with the {@link Looper} for the
* current thread and takes a callback interface in which you can handle
* messages.
*
* If this thread does not have a looper, this handler won't be able to receive messages
* so an exception is thrown.
*
* @param callback The callback interface in which to handle messages, or null.
*/
public Handler(Callback callback) {
this(callback, false);
}

public Handler(Callback callback, boolean async) {
    if (FIND_POTENTIAL_LEAKS) {
        final Class 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;
    //初始化callback
    mCallback = callback;
    mAsynchronous = async;
}

具体实现如下代码:


public class MyHandlerThread extends HandlerThread implements Handler.Callback{
public MyHandlerThread(String name) {
super(name);
}

    @Override
    public boolean handleMessage(Message msg) {
        Log.e("handlermessageThread",Thread.currentThread().getName());
        return true;
    }
}
private MyHandlerThread myHandlerThread;
myHandlerThread = new MyHandlerThread("RoyalThread");
myHandlerThread.start();
//传入callback,执行其handleMessage方法
Handler handler = new Handler(myHandlerThread.getLooper(),myHandlerThread);handler.sendEmptyMessage(0);

3.执行Handler的handleMessage()方法,直接在主线程中重写Handler的handleMessage()方法:


private Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
Log.e("HandlerMessage","HandlerMessage");
mText.setText("failed");
}
};

1.3 Handler入队分析

通过Handler进行入队操作,有两种形式:1.通过post()方法(post(Runnable), postAtTime(Runnable, long), postDelayed(Runnable, long))向MessageQueue中发送消息;2.通过sendXXMessage(sendEmptyMessage(int),sendMessage(Message),sendMessageAtTime(Message,long)和sendMessageDelayed(Message, long))方法。不过除了sendMessageAtFrontOfQueue()方法之外这两种方法最终执行的是sendMessageAtTime(Message msg,long uptimeMills)方法。


public final boolean sendMessageAtFrontOfQueue(Message msg) {
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, 0);
}

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);
}
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,这是注册回调方法,出队操作时可以调用其钩子方法(回调方法)dispatchMessage()方法,调用的是enqueueMessage(queue, msg, uptimeMillis)方法,最终调用的是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;
}

通过上面遍历等next操作可以看出来,MessageQueue消息队列对于消息排队是通过类似c语言的链表来存储这些有序的消息的。其中的mMessages对象表示当前待处理的消息;可以看出,消息插入队列的实质就是将所有的消息按时间(uptimeMillis参数)进行排序。所以还记得上面sendMessageAtFrontOfQueue方法吗?它的实质就是把消息添加到MessageQueue消息队列的头部(uptimeMillis为0,上面有分析)。
到此Handler的发送消息及发送的消息如何存入到MessageQueue消息队列的逻辑分析完成。

1.4 Looper退出,结束MessageQueue源码分析


public void quit() {
mQueue.quit(false);
}
void quit(boolean safe) {
if (!mQuitAllowed) {
throw new IllegalStateException("Main thread not allowed to quit.");
}

    synchronized (this) {
        if (mQuitting) {
            return;
        }
        mQuitting = true;

        if (safe) {
            removeAllFutureMessagesLocked();
        } else {
            removeAllMessagesLocked();
        }

        // We can assume mPtr != 0 because mQuitting was previously false.
        nativeWake(mPtr);
    }
}

首先看看mQuitAllowed参数,这个参数哪里来的呢?不急,我们看看Looper初始化的源码,prepare()方法,默认传入一个ture。可以看出如果这个参数的值是false,将会抛出一个异常:主线程不允许退出。主线程顾名思义就是UI线程,UI线程我们并没有看Looper的字样啊,我们看看UI线程的源码:

  public static void main(String[] args) {
    SamplingProfilerIntegration.start();
    // CloseGuard defaults to true and can be quite spammy.  We
    // disable it here, but selectively enable it later (via
    // StrictMode) on debug builds, but using DropBox, not logs.
    CloseGuard.setEnabled(false);
    Environment.initForCurrentUser();
    // Set the reporter for event logging in libcore
    EventLogger.setReporter(new EventLoggingReporter());
    Security.addProvider(new AndroidKeyStoreProvider());
    // Make sure TrustedCertificateStore looks in the right place for CA certificates
    final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
    TrustedCertificateStore.setDefaultUserDirectory(configDir);
    Process.setArgV0("");
    Looper.prepareMainLooper();
    ActivityThread thread = new ActivityThread();
    thread.attach(false);
    if (sMainThreadHandler == null) {
        sMainThreadHandler = thread.getHandler();
    }
    if (false) {
        Looper.myLooper().setMessageLogging(new
                LogPrinter(Log.DEBUG, "ActivityThread"));
    }
    Looper.loop();
    throw new RuntimeException("Main thread loop unexpectedly exited");
}
public static void prepareMainLooper() {
    prepare(false);
    synchronized (Looper.class) {
        if (sMainLooper != null) {
            throw new IllegalStateException("The main Looper has already been prepared.");
        }
        sMainLooper = myLooper();
    }
}

代码中可以看出调用了Looper.prepareMainLooper();接着看其源码,发现调用了prepare(false)方法,对主线程的Looper进行初始化,传入的参数是false,这就可以解释上述的异常了。
回到quit方法继续看,可以发现实质就是对mQuitting标记置位,这个mQuitting标记在MessageQueue的阻塞等待next方法中用做了判断条件,所以可以通过quit方法退出整个当前线程的loop循环。
这就解决了android最经典的不能在其他非主线程中更新UI的问题。android的主线程也是一个looper线程(looper在android中运用很广),我们在其中创建的handler默认将关联主线程MQ。因此,利用handler的一个solution就是在activity中创建handler并将其引用传递给worker thread,worker thread执行完任务后使用handler发送消息通知activity更新UI。如下图所示:

Android的异步消息分发队列之Handler、Message和Lopper之间的调用关系_第1张图片
Handler更新UI机制
Android的异步消息分发队列之Handler、Message和Lopper之间的调用关系_第2张图片
iPhone

你可能感兴趣的:(Android的异步消息分发队列之Handler、Message和Lopper之间的调用关系)