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

android异步处理,分析Handle消息机制

2016-07-12 18:05 369 查看

android异步处理,分析Handle消息机制

首先看下handle比较常用的用法

子线程使用主线程的handle发送一条消息到主线程,这个消息会被加到MessageQueue里。

这样就有了loop的概念。looper会不停的从MessageQueue中取消息,发现消息后会调用msg的dispatchMessage方法,就可以在handleMessage的回调中接收到来处理这个消息进行UI操作。

首先看下handle的构造方法

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


Looper.myLooper();获取当前线程的looper实例

mQueue = mLooper.mQueue;拿到looper里的消息队列

callback 是looper发现消息队列里有消息的时候调用dispatchMessage然后回调handleMessage

接下来看looper

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实例。将looper放到sThreadLocal中,那sThreadLocal又是什么呢。ThreadLocal类为每一个线程都维护了自己独有的变量拷贝。每个线程都拥有了自己独立的一个变量,那就没有任何必要对这些线程进行同步,它们也能最大限度的由CPU调度,并发执行。所以sThreadLocal是一个存放looper的变量,looper.myLooper()也就是从sThreadLocal取的。

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


首先取出当前线程的looper然后拿到消息队列开始无限循环,进行遍历发现有消息就进行处理调用msg.target.dispatchMessage(msg); 也就是handle的dispatchMessage方法,没有消息就return。

那Looper是怎样关联MessageQueue呢。

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


looper的构造方法中会创建一个消息队列。

博主水平有限,如有错误的地方,希望大家能指出。谢谢。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android 线程 异步 handle