Looper,Message,Handler概述

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相关的那个线程,初始化为null
Thread 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 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.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);
        }
    }







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值