Looper,Message,Handler概述

来源:互联网 发布:沈阳seo新浪博客 编辑:程序博客网 时间:2024/06/08 00:01

Looper:消息循环器,从MessageQueue中取出Message进行处理。

在系统启动时候会创建一个UI线程,里面包含了一个消息循环Looper

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

主要的变量:

//线程本地存储功能的封装,TLS,thread local storage,private static final ThreadLocal sThreadLocal = new ThreadLocal();//消息队列,MessageQueue,看名字就知道是个queue..final MessageQueue mQueue;//和本looper相关的那个线程,初始化为nullThread mThread;//static变量,代表一个UI Process(也可能是service吧,这里默认就是UI)的主线程private static Looper mMainLooper = null;

然后进入loop()函数进行无限循环

<span style="white-space:pre"></span>/** * Run the message queue in this thread. Be sure to call {@link #quit()} to * end the loop. */public static void loop() {//获取线程中的Looper对象final Looper me = myLooper();if (me == null) {throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");}//获取Looper中的消息队列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 blockif (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// loggerPrinter 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.recycle();}}


message:消息,包含了消息的标识,消息的处理对象和数据。

主要变量:

//消息的处理者/*package*/ Handler target;     //消息执行时的回调函数,如果callback不为空时会执行run函数而不分发给target处理/*package*/ Runnable callback;   

获取一个message需要使用obtain方式而不使用new的方式,因为message中有个消息池,用来减少创建时内存的开销

/**     * Return a new Message instance from the global pool. Allows us to     * avoid allocating new objects in many cases.     */    public static Message obtain() {        synchronized (sPoolSync) {            if (sPool != null) {                Message m = sPool;                sPool = m.next;                m.next = null;                sPoolSize--;                return m;            }        }        return new Message();}


Handler:消息的处理者,负责消息发送和处理。

主要变量:

//消息队列,主要让处理者对消息进行添加和移除final MessageQueue mQueue;    //处理者的回调函数,优先于handleMessage函数的处理final Callback mCallback;处理消息方法:

1.      判断消息中callback是否为空,如果不为空直接执行run函数

2.      判断处理者中mCallback是否为空,如果不为空就让mCallback进行处理

3.      判断处理者mCallback是否已经处理,如果返回true说明已经处理不需要Handler自己处理,如果返回false需要调用Handler的handleMessage函数

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







0 0
原创粉丝点击