看了网上很多文章,发现没人真正解释为什么在主线程中不需要使用Looper.prepare()和Looper.loop()方法。下面我贴一下安卓源码,相信大家就一目了然了,源码的位置是在ActivityThread类中的main函数。大家可以用Source Insight查看。
public static void main(String[] args) {
SamplingProfilerIntegration.start();
CloseGuard.setEnabled(false);
Environment.initForCurrentUser();
// Set the reporter for event logging in libcore
EventLogger.setReporter(new EventLoggingReporter());
Process.setArgV0("<pre-initialized>");
Looper.prepareMainLooper();//这实际就是一个实例化一个looper对象,大家也可以看看prepareMainlooper方法(下方)。
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
Looper.loop();//启动循环器
}
public static void prepareMainLooper() {
prepare(false); //实例化Looper,上篇博文分析过这个方法了,不再赘述
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();//获得Looper对象
}
}