您的位置:首页 > 移动开发 > Android开发

Android 从源码分析Handler消息机制

2017-10-25 17:40 447 查看
说起Handler,就不得不提Looper以及Message。我们在使用Handler发送消息时,就是将Message发送到MessageQueue消息队列中,然后通过Looper.loop()方法对MessageQueue消息队列中的消息进行轮询,利用Handler.dispatchMessage(msg)对消息派发,最后复写handleMessage(msg)根据不同的消息进行不同操作。接下来我们开始在源码上进行分析。

Looper

首先对于Looper来说,主要的是Looper.prepare()以及Looper.loop()这两个方法,让我们先看一看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));
}


从这里我们可以看到,在prepare()方法了,创建了Looper对象并将其添加到了sThreadLocal对象里,关于sThreadLocal,它是一个ThreadLocal对象,可以在线程中储存变量。同时第二行对sThreadLocat.get()判断是否为空,以抛出异常的方式,避免再次创建Looper对象,这样就保证一个线程中最多只有一个Looper对象和一个MessageQueue消息队列,接下来我们看下Looper的构造函数。

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


在Looper构造函数中,创建了MessageQueue(消息队列)。

所以,在Looper.prepare()函数中,主要是创建了Looper对象并储存到sThreadLocal里,在创建Looper的同时,创建了MessageQueue这个消息队列。

然后我们看下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();

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


刚开始我们从myLooper()方法中获取到之前储存在sThreadLocal中的Looper对象,然后判断是否为空。从这里可以看出来,在调用Looper.loop()方法前,一定要先调用Looper.prepare()方法,否则会抛出异常。而我们的主线程,在程序启动的时候就已经调用了Looper.prepare()方法。

public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}


继续往下看,可以知道在loop()方法中我们获取到了MessageQueue这个消息队列,然后通过无限循环对消息进行轮询,如果有消息则取出消息,通过msg.target.dispatchMessage(msg)对消息进行处理,而从Message源码得知msg.target就是Handler这个对象。

所以,从loop()方法中我们获取了储存在sThreadLocal的Looper对象,然后通过它得到MessageQueue消息队列,接下来从MessageQueue中取出消息,如果不为空,则通过msg.target.dispatchMessage(msg)进行处理,最后通过 msg.recycleUnchecked()对消息进行回收。

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 that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}


Handler的构造函数比较多,从这个构造函数中我们可以知道,通过Looper.myLooper()这个方法获取到储存在sThreadLocal中的Looper对象,myLooper()方法上面有源码,就不在说了,我们获取到Looper对象后就可以得到Looper中的MessageQueue消息队列,然后Handler通过MessageQueue与Looper对象产生了联系。

所以在Handler构造函数中,主要做了得到Looper对象,然后通过Looper获取MessageQueue消息队列。

既然得到了MessageQueue,我们是不是应该往里面放消息了?接下来我们看下常用的sendMessage(msg)这个方法。

public final boolean sendMessage(Message msg){

a4b7
return sendMessageDelayed(msg, 0);
}


public final boolean sendMessageDelayed(Message msg,    long delayMillis){
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg,      SystemClock.uptimeMillis() + delayMillis);
}


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


最后通过enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis)方法将我们的要发送的消息放到消息队列中。在这个方法里,我们看到了msg.target = this,是不是很眼熟呢,我们在上面Looper.loop()方法中可以看到,每次取出msg都会交给msg.target.dispatchMessage(msg)去处理。然后我们看下dispatchMessage(msg)里做了什么。

public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}


在这个方法里,最后调用了handleMessage(msg)这个方法。

public void handleMessage(Message msg) {
}


这里什么都没有,因为这里是我们收到信息后进行处理的地方。我们在使用Handler时,对消息进行处理一定要复写handleMessage(Message msg)这个方法,根据msg.what进行不同操作。

至此,整个流程已经分析完了,最后我们来做个总结。

Looper

在Looper中,我们主要进行了两个操作

Looper.prepare():

在prepare()中,我们创建了Looper对象,并且在Looper构造函数中创建了MessageQueue这个消息队列,同时将Looper对象储存到sThreadLocal中。值得注意的是,当Looper与线程绑定时,只能存在一个Looper对象,一个MessageQueue队列。

Looper.loop():

在loop()中,首先获取到储存在sThreadLocal中的Looper对象,然后通过Looper对象得到MessageQueue消息队列。接着对消息队列进行无限循环取出每一个Message对象,如果不为空则利用msg.target.dispatchMessage(msg)对消息进行处理。

Handler

在Handler中,首先当我们初始化Handler时,通过myLooper()这个方法获取到Looper对象,从而得到MessageQueue消息队列。然后开始进行发送消息以及处理消息这两个过程。

发送消息:

我们从sendMessage(msg)一步一步观察得知,最后通过enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis)方法将Message放入到MessageQueue中。这是发送消息的过程。

处理消息:

我们知道在Looper.loop()开始对MessageQueue消息队列进行无限循环取出消息,然后通过msg.target.dispatchMessage(msg)对消息进行处理,最后再复写handleMessage(msg)对获取到的消息进行不同操作。这是处理消息的过程。

参考博文:

http://blog.csdn.net/lmj623565791/article/details/38377229/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android handler