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

Android消息机制------Handler机制的原理(超详细)

2016-03-29 10:53 579 查看
一:Handler,Message 与Looper

1.Handler是androihd消息机制的上层接口,他的主要作用就是将一个任务切换到handler所在的线程去执行,它的内部主要依赖MessageQueue和Looper工作

2.大概流程 :当handler的send方法调用时,它会调用MessageQueue的enqueueMessage方法将这个消息放在消息队列中,然后Looper发现有新消息到来时,就会处理这个消息(Looper运行在handler所在的线程),随 后切换到handler所在的线程

3.消息队列的工作原理
MessageQueue 消息队列,是一个单链表的数据集合,以队列的形式对外提供插入和删除的工作
消息队列MessageQueue 主要包含两个操作,插入和读取,读取也伴随着删除,enqueueMessage() next()

4.Looper的工作原理
Looper 专门用于处理消息队列中的消息,是一个无限循环,handler在创建对象的时候通过ThreadLocal获取到当前线程的Looper(线程默认是没 有Looper的)
不停的查看消息队列是否有新消息
Looper的一些方法:
Looper.prepare() 为当前线程创建一个Looper
Looper.loop() 来开启消息循环 会调用MessageQueue的next() 方法 Looper是运行在Handler的线程中,所以它也起到了将任务切换到 handler线程的作用
getMainLooper() 通过它可以在任何地方获取到主线程的Looper()
quit() quitSafely() Looper退出,前者是直接退出,后者是设定一个退出标志,任务结束后退出
在 子线程中,如果手动为其创建了Loope() 那么在所有的事情结束后应该调用quit()方法终止消息循环,否则这个子线程就会一直处于等待的状态

5.ThreadLocal 的工作原理
ThreadLocal 是一个线程内部的数据存储类,当某些数据是以线程为作用域,并且不同的线程有着
不同数据版本的时候可以考虑使用ThreadLocal ,通过这个功能也可以轻松使用Looper在线程中的获取
Thread的第二个作用就是,采用ThreadLocal可以让监听器作为线程内的全局对象而存在,在线程内部通过get就可以得到监听器

6.Handler的工作流程(详细)
Handler的工作主要包含消息的发送和接收过程,消息的发送可以通过Post的一系列方法以及send的一系列的方法,post的一系类方法最终还是通 过send的一系列方法进行
1. 在sendMessage(Message msg)中调用 sendMessageDelayed(msg,0);

public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}

2. sendMessageDelayed(msg,0)中调用sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);


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

3.sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis)调用enqueueMessage(queue, msg, uptimeMillis)

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

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


5.然后Loop的loop方法开始调用(前提Loop已经存在) 消息队列的next()(取出删除),随后调用msg.target.dispatchMessage(msg)(这一步,将任务切换到了指定的线程(looper所在的线程)中去执行了);

/**
* 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);
}
//这一步,将任务切换到了指定的线程(looper所在的线程)中去执行了
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();
}
}

6. msg.target.dispatchMessage(msg);


/**
* Handle system messages here.
*/
public void dispatchMessage(Message msg) {

if (msg.callback != null) {
/**
* 如果用的handler.post方法会执行这个方法,直接在handler所在的线程中执行这个run方法
*/
handleCallback(msg);
} else {
if (mCallback != null) {
/**
* 如果在创建handler对象的时候重写了callback,
*/
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}



7.如果 使用 Handler.post(Run)方法

handler.post(Runnable) 最终会调用handler().send()方法
详细代码如下

 详细的代码如下:
* public final boolean post(Runnable r){
*    return  sendMessageDelayed(getPostMessage(r), 0);
* }
*
*
* private final Message getPostMessage(Runnable r) {
*    Message m = Message.obtain();
*    m.callback = r;
*    return m;
* }

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

handler机制的流程图:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: