所以Looper属于Handler,由创建Handler的线程创建和使用,MessageQueue属于Looper,通过创建Handler的线程调用Looper的loop()方法进行轮询。
当我们将Handler对象在主线程(UI线程)中创建的时候,Handler对象会关联一个Looper对象,这个Looper对象不是我们创建的,是早就由Activity中的ActivityThread这个类在main函数中创建好的(整个Android应用的入口函数就是这个main函数),如下:
public static void main(String[] args) {
SamplingProfilerIntegration.start();
// CloseGuard defaults to true and can be quite spammy. We
// disable it here, but selectively enable it later (via
// StrictMode) on debug builds, but using DropBox, not logs.
CloseGuard.setEnabled(false);
Environment.initForCurrentUser();
// Set the reporter for event logging in libcore
EventLogger.setReporter(new EventLoggingReporter());
Security.addProvider(new AndroidKeyStoreProvider());
// Make sure TrustedCertificateStore looks in the right place for CA certificates
final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
TrustedCertificateStore.setDefaultUserDirectory(configDir);
Process.setArgV0("<pre-initialized>");
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}从上面的代码我们可以看见Looper对象是通过Looper.prepareMainLooper()来创建的,而调用loop()开始消息的轮询是在最后:Looper.loop()。通过源码我们可以看见loop()内部是一个for(;;){}的死循环,这个就是整个应用程序的main thread loop。我们开发window应用的时候都知道这个应用就是一个大的死循环,称为main thread loop,而Android应用的main thread loop就在这里。这下我们就知道我们的消息究竟是怎样被轮询和处理了的吧!找到主循环,一切都迎刃而解了!
谈谈我对Android中的消息机制的理解之Handler,Looper和MessageQueue的解释
原文:http://blog.csdn.net/andyhan_1001/article/details/46570297