Activity的启动流程

一切从main()方法开始

  在Android中,一个应用程序的开始可以说是从ActivityThread.java中的main()方法开始。在main()方法中,主要做了以下事情:
1 . 初始化主线程的Looper、主Handler。并使主线程进入等待接收Message消息的无限循环状态。
  ActivityThread.java类中代码:

public static void main(String[] args){
    SamplingProfilerIntegration.start();
    CloseGuard.setEnabled(false);
    Environment.initForCurrentUser();
    EventLogger.setReporter(new EventLoggingReporter());
    Security.addProvider(new AndroidKeyStoreProvider());
    final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
    TrustedCertificateStore.setDefaultUserDirectory(configDir);
    Process.setArgV0("<pre-initialized>");
    
    //初始化Looper;
    Looper.prepareMainLooper();
    
    //实例化一个ActivityThread;
    ActivityThread thread = new ActivityThread();
    
    //这个方法最后就是为了发送创建Application的消息;
    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");
}
public final class Looper{

    private static Looper sMainLooper;
    
    public static void prepare()
    public static void prepareMainLooper(){
        prepare(false);
        synchronized(Looper.class){
            if(sMainLooper != null){
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }
}

2 . 用attach()方法,主要是为了发送初始化Application的消息。

private void attach(boolean system){
    ···
    //获取IActivityManager实例;
    final IActivityManager mgr = ActivityManagerNative.getDefault();
    try{
        mgr.attachApplication(mAppThread);
    }catch(RemoteException ex){
        throw ex.rethrowFromSystemServer();
    }
}

  其中的mAppThread这个变量是ApplicationThread,ApplicationThread是ActivityThread中的一个内部类,代码如下:

private class ApplicationThread extend ApplicationThreadNative{
    
}

  IActivityManager是一个接口,当我们调用ActivityManagerNative.getDefault()获得的实际是一个代理类的实例--ActivityManagerProxy,这个东西实现了IActivityManager接口。ActivityManagerProxy是ActivityManagerNative的一个内部类。

public abstract class ActivityManagerNative{
    ···
    static public IActivityManager getDefault(){
        return ActivityManager.getService();
    }
    ···
}
public class ActivityManager{
    public static IActivityManager getService() {
        return IActivityManagerSingleton.get();
    }
}

-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
------------------------last line for now-------------------------