[Android源代码分析]Android消息机制,Handler,Message,Looper,MessageQueue

最近准备把Android源码大致过一遍,不敢私藏,写出来分享给大家,顺便记录一下自己的学习感悟。里面一定有一些错误的地方,希望广大看客理解理解。

网上也有不少分析文章,这里我尽量分析的更加细致详尽。不留死角。

一.核心循环体:Looper.loop();

我们知道,在线程run()中Looper.prepare();Looper.looper()。之后这个线程就是一个HandlerThread了。我们可以通过Handler在另外一个线程中(自己也可以)向这个线程发送消息,在这个线程中处理消息。

简单来说,Looper.loop(),就是一个循环体,循环着从MessageQueue中取消息,处理消息。现在存在几个问题。这就是整个消息处理框架的核心所在。框架所有的Api(消息的增删改查)都是为了这个循环体服务的。当然简单的for(;;)是远远不够的,框架需要考虑到以下问题:

1. 线程安全问题:消息的增删改查是多线程环境,所以要保证整个消息队列的线程安全。

2. 线程阻塞问题:当队列中没有到期需要处理的消息时,怎样避免线程空转浪费性能。

3. 与native层交互问题:我们知道,Android框架层分java和native层,基本我们平时常用在java层常用的核心框架,在native层都有另外一套与之匹配的“分身”,而且java层的众多功能实现都要依赖native层。

4. 性能问题:比如说Message对象的生灭在这个框架中非常频繁,可以使用对象缓冲池来提高性能,减轻gc压力。

1.Looper.looper()的源码(Android 6.0)

Looper.java(frameworks/base/core/java/android/os/Looper.java)

/**
 * Run the message queue in this thread. Be sure to call
 * {@link #quit()} to end the loop.
 */
public static void loop() {
//1.指向static final ThreadLocal<Looper> sThreadLocal.get()
//相当于一个Map key是Thread.currentThread()
//ThreadLocal知识:http://www.iteye.com/topic/103804
//只是一个本线程持有的变量表而已,随线程生灭,
//这里只是取出当前线程对应的looper对象
final Looper me = myLooper();
//2.如果这个线程没有对应的looper对象,即没有Looper.prepare();则抛出异常
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn‘t called on this thread.");
    }

//3.从Looper中取出MessageQueue,一个Looper持有一个MessageQueue
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.
//确保这个线程是本地的,因为Handler Message可用于IPC(猜测)
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity();
    //4.循环体
for (;;) {
    //5.循环取出下一条消息来处理,会在这里阻塞住,这里可以猜到消息队列时一个链表结构,先剧透一下上面说的线程阻塞,防止空转也是在这个函数里实现的。下面会具体分析。
    Message msg = queue.next(); // might block
    //没有message即返回
    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);
        }
        //6.消息分发处理,处理消息,最终调用用户实现的handlerMessage()的地方。下面分析
        msg.target.dispatchMessage(msg);

if (logging != null) {
            logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
        }
        //7.翻译过来就是:确保在调度过程中的线程的身份没有被损坏,下面再细说
// 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);
        }
        //将处理完的Message对象回收,以备下次obtain重复使用。
        msg.recycleUnchecked();
    }
}

Looper.prepare()最终调用

private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
    }
//为当前线程创建Looper对象,塞进ThreadLocal中
sThreadLocal.set(new Looper(quitAllowed));
}

此外列出Looper类的成员变量

   private static final String TAG = "Looper";

    // sThreadLocal.get() will return null unless you‘ve called prepare().
    //每个线程对应一个Looper,对应多个handler。当在某个线程中调用Looper.Mylooper()时,
    //调用sThreadLocal.get()返回对应该线程的Looper。
    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
    //全局唯一的主线程对应的MainLooper
    private static Looper sMainLooper;  // guarded by Looper.class
    //每个Looper管理一个MessageQueue
    final MessageQueue mQueue;
    final Thread mThread;

    private Printer mLogging;

Looper.java基本结束。

下面通过Message的增删查处理的顺序分析整个框架。

1).下面先说Message的增

api:增的api对应有Handler.sendMessageXXXX,postXXXX,等。

Handler.java(frameworks/base/core/java/android/os/Handler.java)

a.首先得说Handler的初始化:

Handler3个构造函数最终调用两个版本。

public Handler(Callback callback, boolean async) {
        //如果为真,则检查内存泄漏,就是判断自身是否为static类型
if (FIND_POTENTIAL_LEAKS) {
final Class<? extends Handler> klass = getClass();
if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
                (klass.getModifiers() & Modifier.STATIC) == 0) {
            Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
                klass.getCanonicalName());
        }
    }

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

注意这个参数

/*

* Set this flag to true to detect anonymous, local or member classes

* that extend this Handler class and that are not static. These kind

* of classes can potentially create leaks.

*/

private static final boolean FIND_POTENTIAL_LEAKS = false;

这个参数用来检查可能的内存泄漏,设置这个为true的话,在构造方法中会检查,自身是否是静态的内部类,klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&(klass.getModifiers() & Modifier.STATIC,如果不是就抛出异常。关于内存泄漏,参看我另一篇文章链接

剩下的就是简单的赋值了。

public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
    msg.target = this;
if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
return queue.enqueueMessage(msg, uptimeMillis);
}

还要注意的是async参数,如果你传入true,在最后向MessageQueue塞Message的时候会把这个Message设置为异步消息。

什么是异步消息?先剧透一下,后面要说到一个“同步屏障”的概念,Message链表一旦被插入一个“同步屏障”,那么屏障之后的所有同步消息将不会被处理,哪怕已经到期了。而异步消息则不受影响。

插入动作最后会通过setAsynchronous调用到MessageQueue方法的enqueueSyncBarreir(long when)方法,我们在下面分析。



b.现在拿到Handler对象了,看一下Handler这几个核心成员变量,可以看到Handler持有一个MessageQueue的引用,一个Looper的引用,这里的callback,有点像Thread和Runnable的关系,常见的设计模式,指向了用户handlerMessage的具体实现。

final MessageQueue mQueue;
final Looper mLooper;
//对应handlerMessage的具体实现
final Callback mCallback;
final boolean mAsynchronous;
//IPC相关
IMessenger mMessenger;

说一说IMessenger,IPC相关,相信大家也看的出来,Handler也关联了Binder提供的IPC服务,Messenger关联一个可以发送消息的Handler。通过指定一Handler对象创建一个Messenger可以实现基于消息的夸进程通信。

线程和进程主要的差别无非是进程有独立的内存空间,一旦一个进程将Message通过Binder发送给另外一个进程中的线程的MessageQueue中,那么,这个Message一样可以和普通的Message统一处理了。可以说没毛病。

这方面在后面会具体讨论,现在先简单说一下。



c.handler有了,我们需要获得一个Message对象,上面说过了,对于Message这种大量朝生夕灭的对象,需要使用对象缓冲池,或者原型模式这些来优化性能,gc最烦的就是这种大量的“生的快,死的早”的对象。我们来看一下Message具体是怎么做的。

先看一下Message的成员变量,基本上都是熟悉的面孔

Message.java(frameworks/base/core/java/android/os/Message.java)

public int what;
public int arg1;
public int arg2;
public Object obj;
public Messenger replyTo;

public int sendingUid = -1;

 */
/*package*/ static final int FLAG_IN_USE = 1 <<0;

/*package*/ static final int FLAG_ASYNCHRONOUS = 1 <<1;

/** Flags to clear in the copyFrom method */
/*package*/ static final int FLAGS_TO_CLEAR_ON_COPY_FROM = FLAG_IN_USE;

/*package*/ int flags;

/*package*/ long when;

/*package*/ Bundle data;

/*package*/ Handler target;

/*package*/ Runnable callback;

// sometimes we store linked lists of these things
/*package*/ Message next;

private static final Object sPoolSync = new Object();
private static Message sPool;
private static int sPoolSize = 0;

private static final int MAX_POOL_SIZE = 50;

private static boolean gCheckRecycle = true;

rePlyto是Messenger对象,和上面提到的IPC相关,是IPC的信使。

When这个比较重要,他代表了这个Message在什么时间需要被处理。

sPool就是Message对象缓冲池的链表头。

sPoolSync是同步块的标志,空对象。

MAX_POOL_SIZE,缓冲池对象最大数量

gCheckRecycle,好像没什么用,api大于等于21的时候,非法recycle Message对象的时候会多抛一个异常。



Message对象的获取,同步方法,需要保证Message链表的线程安全。

public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {
            Message m = sPool;
sPool = m.next;
            m.next = null;
            m.flags = 0; // clear in-use flag
sPoolSize--;
return m;
        }
    }
    //缓冲池用完即new新对象
return new Message();
}

回收方法,较简单就不细说了,这里注意isInUse标志,在Message.next() 中会被置为true,表示Message正在使用,不能回收。

public void recycle() {
if (isInUse()) {
if (gCheckRecycle) {
throw new IllegalStateException("This message cannot be recycled because it "
+ "is still in use.");
        }
return;
    }
    recycleUnchecked();
}

/**
 * Recycles a Message that may be in-use.
 * Used internally by the MessageQueue and Looper when disposing of queued Messages.
 */
//回收Message并清除里面的旧数据以备用。
void recycleUnchecked() {
// Mark the message as in use while it remains in the recycled object pool.
    // Clear out all other details.
flags = FLAG_IN_USE;
what = 0;
arg1 = 0;
arg2 = 0;
obj = null;
replyTo = null;
sendingUid = -1;
when = 0;
target = null;
callback = null;
data = null;

synchronized (sPoolSync) {
if (sPoolSize <MAX_POOL_SIZE) {
next = sPool;
sPool = this;
sPoolSize++;
        }
    }
}


d.现在Message对象拿到手了,下面分析Handler.sendMessage(msg)

Handler.java

无论是post(),sendXXX还是等等。都会封装到Message,计算时间后最终调用到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);
}

最终调用MessageQueue的enqueueMessage方法

when在前面已经计算出来了,非常好算,加一下就好了

MessageQueue.java(frameworks/base/core/java/android/os/Message.java)

boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {
throw new IllegalArgumentException("Message must have a target.");
    }
//确保msg不是正在使用的
if (msg.isInUse()) {
throw new IllegalStateException(msg + " This message is already in use.");
    }
//同步方法,因为MessageQueue和Handler是1对N的关系,也就是说,会有多个线程可能同时调用该方法,所以需要同步处理一下。
synchronized (this) {
    //mQuitting是队列退出的标志,调用quit方法退出队列将此标志置为true,接着looper就会退出,HandlerThread结束。
if (mQuitting) {
            IllegalStateException e = new IllegalStateException(
                    msg.target + " sending message to a Handler on a dead thread");
            Log.w(TAG, e.getMessage(), e);
            msg.recycle();
return false;
        }
        //标记msg对象开始使用
        msg.markInUse();
        msg.when = when;
        Message p = mMessages;
boolean needWake;
//当when=0/null或者when早于最前面一个msg的when的时候,将此msg插到队列最前面。这里的消息队列是按照when顺序排列的。如果这时队列是阻塞的话,即唤醒队列。
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 {
// Inserted within the middle of the queue.  Usually we don‘t have to wake
            // up the event queue unless there is a barrier at the head of the queue
            // and the message is the earliest asynchronous message in the queue.
    //只有现在队列阻塞中并且,message对应的handler为空,并且Message为前面说的异步消息的时候,需要唤醒队列
needWake = mBlocked && p.target == null && msg.isAsynchronous();
    //遍历队列根据when大小找到合适的地点插入。
            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;
        }
        //根据结果判断是否唤醒队列(线程),nativeWake是一个native方法,具体后面分析,mPtr是指向native层对应的MessageQueue对象的指针。
// We can assume mPtr != 0 because mQuitting is false.
if (needWake) {
nativeWake(mPtr);
        }
    }
return true;
}


2.下面说说Message的查,即MessageQueue.next()方法,队列在这里阻塞,非常重要。

MessageQueue.java(frameworks/base/core/java/android/os/Message.java)

Message next() {
// Return here if the message loop has already quit and been disposed.
    // This can happen if the application tries to restart a looper after quit
    // which is not supported.
//娶到native层的MessageQueue对象指针
final long ptr = mPtr;
if (ptr == 0) {
return null;
    }

int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
    //去除所有在当前线程在内核中挂起的Binder命令,这个调用可能是有用的在做一个可能会阻塞线程很长一段时间的操作情况下,这是为了确保任何挂起的对象引用已被释放,以防止进程为保持对象的时间比它需要得长。
       //简单的来说,下面当前线程就要调用nativePollOnce进入长时间的阻塞状态了,必须通知内核释放掉该进程在Binder驱动中挂起的对象,不然Binder将长时间无法获得来自该线程的通知对这些对象进行操作,造成Binder驱动的拥塞。
            Binder.flushPendingCommands();
        }

        //阻塞函数,MessageQueue阻塞于此,实现延时阻塞的真正函数,这是个native函数,下面具体分析
        nativePollOnce(ptr, nextPollTimeoutMillis);
        //同步块,和上面enqueueMessage里的那个对应,保证Message链表结构的线程安全。
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.
//遍历Message链表找到一个非空并且不是异步的Message
do {
                    prevMsg = msg;
                    msg = msg.next;
                } while (msg != null && !msg.isAsynchronous());
            }
if (msg != null) {
//如果现在的时间早于Message需要被处理的时间
if (now < msg.when) {
// Next message is not ready.  Set a timeout to wake up when it is ready.
//确定需要延时的时长,即msg的when-现在的时间,和Integer最大值的最大值
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                } else {
//不需要延时则可以直接获得Message,处理一下链表,标记Message的使用状态,返回Message给loop()去处理。
// Got a message.
mBlocked = false;
if (prevMsg != null) {
                        prevMsg.next = msg.next;
                    } else {
mMessages = msg.next;
                    }
                    msg.next = null;
if (DEBUG) Log.v(TAG, "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.
//检查用户是否将MessageQueue退出了。
if (mQuitting) {
//这里的销毁函数nativeDestroy(mPtr),mPtr = 0;销毁native层的MessageQueue,并且将其在java层的指针清空。
                dispose();
return null;
            }

// If first time idle, then get the number of idlers to run.
            // Idle handles only run if the queue is empty or if the first message
            // in the queue (possibly a barrier) is due to be handled in the future.

//方法走到这里了,代表MessageQueue内暂时没有需要处理的Message对象,那么,这时如果用户设置了idlehandler的话,线程就会“忙里偷闲”抽空处理一下这个idleHandler。
if (pendingIdleHandlerCount <0
&& (mMessages == null || now <mMessages.when)) {
                pendingIdleHandlerCount = mIdleHandlers.size();
            }
if (pendingIdleHandlerCount <= 0) {
// No idle handlers to run.  Loop and wait some more.
mBlocked = true;
continue;
            }

if (mPendingIdleHandlers == null) {
mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
            }
mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
        }

//到这里表示用户却是设置了IdleHandler,下面就是遍历列表,挨个取出处理,并把处理完的丢掉。
// Run the idle handlers.
        // We only ever reach this code block during the first iteration.
for (int i = 0; i < pendingIdleHandlerCount; i++) {
final IdleHandler idler = mPendingIdleHandlers[i];
mPendingIdleHandlers[i] = null; // release the reference to the handler

boolean keep = false;
try {
                keep = idler.queueIdle();
            } catch (Throwable t) {
                Log.wtf(TAG, "IdleHandler threw exception", t);
            }

if (!keep) {
synchronized (this) {
mIdleHandlers.remove(idler);
                }
            }
        }

// Reset the idle handler count to 0 so we do not run them again.
pendingIdleHandlerCount = 0;

// While calling an idle handler, a new message could have been delivered
        // so go back and look again for a pending message without waiting.
nextPollTimeoutMillis = 0;
    }
}


3.然后是消息的删除,这个倒是没什么好说的,比较简单

void removeMessages(Handler h, int what, Object object) {
if (h == null) {
return;
    }

synchronized (this) {
        Message p = mMessages;

// Remove all messages at front.
while (p != null && p.target == h&& p.what == what
&& (object == null || p.obj == object)) {
            Message n = p.next;
mMessages = n;
            p.recycleUnchecked();
            p = n;
        }

// Remove all messages after front.
while (p != null) {
            Message n = p.next;
if (n != null) {
if (n.target == h&& n.what == what
&& (object == null || n.obj == object)) {
                    Message nn = n.next;
                    n.recycleUnchecked();
                    p.next = nn;
continue;
                }
            }
            p = n;
        }
    }
}

最后,这一篇基本完成了,可能我的理解会有些错误,欢迎指正,下面一篇就是分析native层中的这几个函数。

private native static long nativeInit();
private native static void nativeDestroy(long ptr);
private native void nativePollOnce(long ptr, int timeoutMillis); /*non-static for callbacks*/
private native static void nativeWake(long ptr);
private native static boolean nativeIsPolling(long ptr);
private native static void nativeSetFileDescriptorEvents(long ptr, int fd, int events);
时间: 2024-08-06 07:57:42

[Android源代码分析]Android消息机制,Handler,Message,Looper,MessageQueue的相关文章

Android消息机制Handler、Looper、MessageQueue源码分析

1. Handler Looper MessageQueue的关系 2.源码分析 下图表示了Handler.Looper.MessageQueue.Message这四个类之间的关系. Handler必须与一个Looper关联,相关Looper决定了该Handler会向哪个MessageQueue发送Message 每一个Looper中都包含一个MessageQueue Handler中的mQueue引用的就是与之关联的Looper的MessageQueue 不管Handler在哪个线程发送Mes

Android Framework 分析---2消息机制Native层

在Android的消息机制中.不仅提供了供Application 开发使用的java的消息循环.事实上java的机制终于还是靠native来实现的.在native不仅提供一套消息传递和处理的机制,还提供了自己定义文件描写叙述符的I/O时间的监听机制.以下我们从详细代码中分析一下. Native层的关键类: Looper.cpp.该类中提供了pollOnce 和wake的休眠和唤醒机制. 同一时候在构造函数中也创建 管道 并增加epoll的机制中.来监听其状态变化. Looper::Looper(

Android Handler处理机制 ( 二 ) ——Handler,Message,Looper,MessageQueue

Android是消息驱动的,实现消息驱动有几个要素: 消息的表示:Message 消息队列:MessageQueue 消息循环,用于循环取出消息进行处理:Looper 消息处理,消息循环从消息队列中取出消息后要对消息进行处理:Handler 平时我们最常使用的就是Message与Handler了,如果使用过HandlerThread或者自己实现类似HandlerThread的东 西可能还会接触到Looper,而MessageQueue是Looper内部使用的,对于标准的SDK,我们是无法实例化并

Android Handler处理机制 ( 三 ) ——Handler,Message,Looper,MessageQueue

在android中提供了一种异步回调机制Handler,使用它,我们可以在完成一个很长时间的任务后做出相应的通知 handler基本使用: 在主线程中,使用handler很简单,new一个Handler对象实现其handleMessage方法,在handleMessage中 提供收到消息后相应的处理方法即可,这里不对handler使用进行详细说明,在看本博文前,读者应该先掌握handler的基本使用,我这里主要深入描述handler的内部机制 .现在我们首先就有一个问题,我们使用myThread

android源代码分析 android toast使用具体解释 toast自己定义

在安卓开发过程中.toast使我们常常使用的一个类.当我们须要向用户传达一些信息,可是不须要和用户交互时,该方式就是一种十分恰当的途径. 我们习惯了这样使用toast:Toast.makeText(Context context, String info, int duration).show();该方法是 系统为我们提供的一个方便的创建toast对象的静态方法,其内部依旧是调用toast的相关方法完毕.以下 就从其源代码对该类的实现做一个分析 在toast类中,最重要的用于显示该toast的s

Android消息机制Handler的实现原理解析

Android的主线程为什么可以一直存在? 线程是一个动态执行的过程,从产生到死亡包括五个状态:新建.就绪.运行.死亡和堵塞.只要线程没有执行完毕或者没有被其它线程杀死,线程就不会进入死亡状态.Android中的主线程一直存在是因为主线程中一直在监听消息,从而使线程无法被执行完毕. 线程的五种状态: 新建new Thread 当创建Thread类的一个实例对象时,此线程进入新建状态未被启动. 就绪runnable 线程已经被启动,正在等待被分配给CPU时间片,也就是说此时线程正在就绪队列中排队等

从Handler+Message+Looper源代码带你分析Android系统的消息处理机制

PS一句:不得不说CSDN同步做的非常烂.还得我花了近1个小时恢复这篇博客. 引言 [转载请注明出处:http://blog.csdn.net/feiduclear_up CSDN 废墟的树] 作为Android开发人员,相信非常多人都使用过Android的Handler类来处理异步任务. 那么Handler类是怎么构成一个异步任务处理机制的呢?这篇 博客带你从源代码分析Android的消息循环处理机制.便于深入的理解. 这里不得不从"一个Bug引发的思考"開始研究Android的消息

Android的消息机制以及Message/MessageQueue/Handler/Looper

概览 * Message:消息.消息里面可包含简单数据.Object和Bundle,还可以包含一个Runnable(实际上可看做回调). * MessageQueue:消息队列,供Looper线程消费消息. * Looper:用于循环处理Message,一个Thread结合一个Looper来实现消息循环处理.Android App的主线程包含了Looper. * Handler:负责向当前Looper线程发送Message,并实现如何处理消息的回调,回调可放到Callback接口的实现中,也可以

从Handler+Message+Looper源码带你分析Android系统的消息处理机制

引言 [转载请注明出处:从Handler+Message+Looper源码带你分析Android系统的消息处理机制 CSDN 废墟的树] 作为Android开发者,相信很多人都使用过Android的Handler类来处理异步任务.那么Handler类是怎么构成一个异步任务处理机制的呢?这篇 博客带你从源码分析Android的消息循环处理机制,便于深入的理解. 这里不得不从"一个Bug引发的思考"开始研究Android的消息循环处理机制.说来话长,在某一次的项目中,原本打算开启一个工作线