Android 消息处理源码分析(2)

Android 消息处理源码分析(1)点击打开链接

继续接着分析剩下的类文件

Looper.javapublic final class Looper {final MessageQueue mQueue; //消息队列final Thread mThread; //Looper联系的线程public static void prepare() {prepare(true);}private static void prepare(boolean quitAllowed) { //先会检查是否有Looper,若有则抛出异常,没有的话则创建一个Looper实例保存起来if (sThreadLocal.get() != null) {throw new RuntimeException("Only one Looper may be created per thread");}sThreadLocal.set(new Looper(quitAllowed));}public static void prepareMainLooper() {prepare(false);synchronized (Looper.class) {if (sMainLooper != null) {throw new IllegalStateException("The main Looper has already been prepared.");}sMainLooper = myLooper();}} //在这个线程中运行消息队列,调用quit()停止 public static void loop() {…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(); // 从消息队列中取出一条消息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 loggerPrinter logging = me.mLogging;if (logging != null) {logging.println(">>>>> Dispatching to " + msg.target + " " +msg.callback + ": " + msg.what);}msg.target.dispatchMessage(msg); //交给msg的handler分发消息处理… }//取出当前线程的Looper,返回空则表示当前线程没有Looperpublic static Looper myLooper() {return sThreadLocal.get();}}Handler.javapublic class Handler {//定义Callback接口public interface Callback {public boolean handleMessage(Message msg);}//子类要实现的消息处理方法public void handleMessage(Message msg) {}* Handle system messages here.*/public void dispatchMessage(Message msg) {//分发信息if (msg.callback != null) {//若指定了msg.callback,则由它处理handleCallback(msg);} else {if (mCallback != null) {//若指定了Handler.mCallback,则由它处理if (mCallback.handleMessage(msg)) { //调用mCallback接口的实现方法return;}}handleMessage(msg); 最后才调用Handler自身重载的handleMessage方法}}分发消息函数中,消息先会检查自身有没有处理自身的回调Runnable,若有则由它处理,若没有则会检查该handler有无自身的回调处理,若有则调用,若没有则调用自身重载的handleMessage方法//Handler的生成总是和它当前所处线程有关的,如果当前线程中没有一个Looper,则会报错,UI线程中默认有产生Looper的函数public Handler() {this(null, false);}//使用指定的Looper(可以处理那个Looper线程中的消息),不用默认的从当前线程中取出Looperpublic Handler(Looper looper) {this(looper, null, false);} …}

版权声明:本文为博主原创文章,未经博主允许不得转载。

,就会犯错误,就会有无数次让自己跌倒的机会出现,

Android 消息处理源码分析(2)

相关文章:

你感兴趣的文章:

标签云: