[转]从源码角度分析java层Handler机制

在Android中,当要更新ui的时候,我们必须要在主线程中进行更新,原因时当主线程被阻塞了5s以上就会出现anr异常,会导致程序崩溃。所以一些耗时的操作必须要放在子线程中,但是在子线程中又不能做更新ui的操作,所以为了解决这个问题,Android设计了handler机制,handler的出现建立起了主线程与子进程之间的通信桥梁,使得ui更新问题得到改善,下面就来剖析一下handlerActivityThread启动了应用程序的主线程,在ActivityThreadmain方法中:

public static final void main(String[] args) {
	...
	Looper.prepareMainLooper();
	if (sMainThreadHandler == null) {
	    sMainThreadHandler = new Handler();
	}
	ActivityThread thread = new ActivityThread();
	thread.attach(false);
	Looper.loop();
	...
}

从上述代码可以看出,首先要执行Looper.prepareMainLooper();操作,然后进入loop进行循环。在prepareMainLooper中,调用prepare方法使用sThreadLocal给当前线程设置一个Looper,如果当前线程中没有,就初始化一个Looper,在Looper的构造方法中顺便创建了一个MessageQueue。细心的读者可能会注意到prepareMainLooperprepare方法都是static的,sThreadLocal也是个静态变量,首先不考虑子线程存在的情况,只考虑主线程,所以无论我们在应用程序的哪个地方调用Looper.prepareMainLooper(),通过sThreadLocal.get()得到的都是同一个looper对象,这样就可以保证一个线程中只有一个Looper对象,那么也就意味着一个线程中只有一个MessageQueue

public static void prepareMainLooper() {
     prepare(false);
     synchronized (Looper.class) {
         if (sMainLooper != null) {
             throw new IllegalStateException("The main Looper has already been prepared.");
         }
         sMainLooper = myLooper();
     }
 }

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

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

执行完 Looper.prepareMainLooper()之后,就是开始Looper.loop()进行消息的循环读取并且进行分发,这个稍后分析完Handler后再分析。

下面我们再分析一下Handler
在代码中我们经常的这样用:

private Handler handler = new Handler(){
    public void handleMessage(Message msg) {
        // process incoming messages here
    }
}

public Handler(Callback callback, boolean async) {
    ......
    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()获取本线程中唯一的一个Looper对象,并且初始化hanlder中的消息队列mQueue,这个mQueueLooper中的一开始初始化的消息队列是同一个。
当调用handler.sendMessage或者sendEmpty方法时,最终要走的方法都是sendMessageAtTime方法:

 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方法中,给当前要加入消息队列的msg设置一个targetthis,这个this也就是当前的handler对象,主要是为了后面的looper循环出消息后,方便知道这个msg向何处分发,该由哪个handler进行处理。接着就调用MessageQueueenqueueMessage方法将msg加入队列中。

boolean enqueueMessage(Message msg, long when) {
    ......
    synchronized (this) {
        ......
        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 {
            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;
        }
        if (needWake) {
            nativeWake(mPtr);
        }
    }
    return true;
}

当消息对列中没有任何msg的时候,当前加入的msg就应该是队列的队头,并且从else语句我们可以看出,整个消息队列是个循环队列。此时消息对列中已经有了msg,那么这个msg应该被接受并进行分发处理,在ActivityThread中调用了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) {
            return;
        }
        Printer logging = me.mLogging;
        .......
        msg.target.dispatchMessage(msg);

        final long newIdent = Binder.clearCallingIdentity();
        if (ident != newIdent) {

        }
        msg.recycle();
    }
}

其中的for循环为死循环,有人可能纳闷了,looper.loop()是运行在主线程中的,而其中有是个死循环,不是说好的主线程中不能做超时的操作吗?呵呵,因为在循环中轮询消息队列中的消息时候,如果没有消息,则会被阻塞。所以这里不用担心anr的问题。通过queue.next()获取出msg后,通过msg.target.dispatchMessage(msg)处理这个消息,这个msg.target就是要处理消息的handle,这也就是为啥在handler中要重写dispatchMessage方法的原因。最后调用recycle释放消息,之所以要recycle一下,是因为Message可以不用new的方式,也可以通过Message.obtain方法从消息池中获取一个,因为消息池中的消息个数有限,如果用完消息后,不及时的recycle的 话,就会造成msg对象不能重复利用。

接下来具体的分析下queue.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;
                    } else {
                        mMessages = msg.next;
                    }
                    msg.next = null;
                    if (false) Log.v("MessageQueue", "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.
            if (mQuitting) {
                dispose();
                return null;
            }
        ...
    }
}

nativePollOnce(mPtr, nextPollTimeoutMillis)当轮询没有消息时,会进行阻塞。消息唤醒和阻塞机制将会在下一篇文章进行介绍,请大家关注。

最后对Handler做一下总结。从消息的分发一直到消息的处理,先后接触到的几个名词有LooperMessageQueueThreadHandlerMessage

  • Looper:负责初始化消息队列,并不断的从消息队列中轮询消息。
  • MessageQueue : 是消息队列,存放在handler发送过来的消息。
  • Thread:当前消息队列和looper所操作的场所或者说运行的环境。
  • Handler:负责消息的发送和处理。
  • Message:一个更新UI的消息,由handler发出,到MessageQueue列队进行处理。

消息处理机制大概的一个处理过程如下:
在这里插入图片描述

关于轮询的时候,阻塞和唤醒机制请看下一篇文章。
从源码角度分析native层消息机制与java层消息机制的关联

补充:在子线程中要更新ui的时候,可以这样处理

class LooperThread extends Thread {
    public Handler mHandler;
	public void run() {
	     Looper.prepare();
	      mHandler = new Handler() {
	          public void handleMessage(Message msg) {
	             // process incoming messages here
	          }
	      };
	      Looper.loop();
	  }
}

参考文章:
https://blog.csdn.net/andywuchuanlong/article/details/48160127

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值