//ActivityThread的main方法
public static void main(String[] args) {
...
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
//在attach方法中会完成Application对象的初始化,然后调用Application的onCreate()方法
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
...
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
刚开始,让我困惑的是, 创建Looper不应该在线程里面创建吗,或者说,应该在ActivityThread里面创建。
后来才想到,这个ActivityThread并不是真正的意义上的Thread,它只是一个普通类。 只不过Main()实在一个线程里面执行的而已。与此类似的还有,ApplicationThread , 真是坑爹。
另外, Looper里面getMainLooper()方法返回的sMainLooper是一个静态变量,可以在其他任何地方都可以使用。
public static Looper getMainLooper() { synchronized (Looper.class) { return sMainLooper; } }
private static Looper sMainLooper;
有些框架就是利用这个方法,拿到该sMainLooper,创建Handler。 在非主线程完成任务后,通过Handler 将数据发给主线程,或在主线程完成回调函数的调用工作。