Activity启动流程(下)

创建线程从ActivityThread.main开始

public static void main(String[] args){
    ...
    Looper.prepareMainLooper(); 
    //初始化Looper
    ...
    ActivityThread thread = new ActivityThread();
    //实例化一个ActivityThread
    thread.attach(false);
    //这个方法最后就是为了发送出创建Application的消息
    ... 
    Looper.loop();
    //主线程进入无限循环状态,等待接收消息
}

然后 attach Application

public void attach(boolean system){
    ...
    final IActivityManager mgr = ActivityManagerNative.getDefault();  
    //获得IActivityManager实例,ActivityManager
    try {
        mgr.attachApplication(mAppThread);
    } catch (RemoteException ex) {
        throw ex.rethrowFromSystemServer();
    }
    ...
}
public final void attachApplication(IApplicationThread thread, long startSeq) {
    synchronized (this) {
        int callingPid = Binder.getCallingPid();
        final int callingUid = Binder.getCallingUid();
        final long origId = Binder.clearCallingIdentity();
        attachApplicationLocked(thread, callingPid, callingUid, startSeq);
        Binder.restoreCallingIdentity(origId);
    }
}

public void attachApplicationLocked(IApplicationThread app){
  ...
// Find the application record that is being attached
 thread.bindApplication(processName, appInfo, providers, null, profilerInfo,
                        null, null, null, testMode,
                        mBinderTransactionTrackingEnabled, enableTrackAllocation,
                        isRestrictedBackupMode || !normalMode, app.persistent,
                        new Configuration(getGlobalConfiguration()), app.compat,
                        getCommonServicesLocked(app.isolated),
                        mCoreSettingsObserver.getCoreSettingsLocked(),
                        buildSerial, isAutofillCompatEnabled);
  ...
 // See if the top visible activity is waiting to run in this process...
   if (normalMode) {
        try {
           // 这里会去 launch activity
            if (mStackSupervisor.attachApplicationLocked(app)) {
                didSomething = true;
            }
        } catch (Exception e) {
            Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
           badApp = true;
        }
   }
}
 // ApplicationThread
public final void bindApplication(String processName, 
    ApplicationInfo appInfo,
    List providers, 
    ComponentName instrumentationName,
    ProfilerInfo profilerInfo, 
    Bundle instrumentationArgs,
    IInstrumentationWatcher instrumentationWatcher,
    IUiAutomationConnection instrumentationUiConnection, 
    int debugMode,
    boolean enableBinderTracking, 
    boolean trackAllocation,
    boolean isRestrictedBackupMode, 
    boolean persistent, 
    Configuration config,
    CompatibilityInfo compatInfo, 
    Map services, 
    Bundle coreSettings){

    ...
    sendMessage(H.BIND_APPLICATION, data);
}

private void handleBindApplication(AppBindData data) {
    ...
    mInstrumentation = (Instrumentation)
        cl.loadClass(data.instrumentationName.getClassName())
        .newInstance();
    //通过反射初始化一个Instrumentation
    ...
    Application app = data.info.makeApplication(data.restrictedBackupMode, null);
    //通过LoadedApp命令创建Application实例
    mInitialApplication = app;
    ...
    mInstrumentation.callApplicationOnCreate(app);
    //让仪器调用Application的onCreate()方法
    ...
}

public Application makeApplication(boolean forceDefaultAppClass,
    Instrumentation instrumentation) {
    ...
    String appClass = mApplicationInfo.className;
    //Application的类名。明显是要用反射了。
    ...
    ContextImpl appContext = ContextImpl.createAppContext(mActivityThread
        , this);
    //留意下Context
    app = mActivityThread.mInstrumentation
        .newApplication( cl, appClass, appContext);
    //通过Instrumentation创建Application
    ...
}

static public Application newApplication(Class clazz
    , Context context) throws InstantiationException
    , IllegalAccessException
    , ClassNotFoundException {
        Application app = (Application)clazz.newInstance();
        //反射创建,简单粗暴
        app.attach(context);
        //关注下这里,Application被创建后第一个调用的方法。
        //目的是为了绑定Context。
        return app;
    }

在 Activity启动流程(上) 中,这一段过程是在40-41之间执行的,创建完 ApplicationThread 后,经过层层调用,生成 LaunchActivityItem 来发送 LAUNCH_ACTIVITY 消息

private void handleLaunchActivity(ActivityClientRecord r
 , Intent customIntent
 , String reason) {
 ...
 Activity a = performLaunchActivity(r, customIntent);
 ...
 if (a != null) {
     ...
     handleResumeActivity(r.token
     , false
     , r.isForward
     ,!r.activity.mFinished && !r.startsNotResumed
     , r.lastProcessedSeq, reason);
     //Activity创建成功就往onResume()走了!
     ...
 }
}

private Activity performLaunchActivity(ActivityClientRecord r
 , Intent customIntent) {
 ...
ContextImpl appContext = createBaseContextForActivity(r);
java.lang.ClassLoader cl = appContext.getClassLoader();
 activity = mInstrumentation.newActivity(
      cl, component.getClassName(), r.intent);
 //通过仪表来创建Activity
 ...
  Application app = r.packageInfo.makeApplication(false
  , mInstrumentation);
  //前面说过,是在获取Application
 ...
 activity.attach(appContext
     , this
     , getInstrumentation()
     , r.token
     ,.ident
     , app
     , r.intent
     , r.activityInfo
     , title
     , r.parent
     , r.embeddedID
     , r.lastNonConfigurationInstances
     , config
     ,r.referrer
     , r.voiceInteractor
     , window);
 ...
 if (r.isPersistable()) {
     mInstrumentation.callActivityOnCreate(
       activity, r.state, r.persistentState);
 } else {
     mInstrumentation.callActivityOnCreate(activity, r.state);
 }
 //根据是否可持久化选择onCreate()方法。
 ...
}

public Activity newActivity(ClassLoader cl, String className,
         Intent intent)
         throws InstantiationException
         , IllegalAccessException,
         ClassNotFoundException {
     return (Activity)cl.loadClass(className).newInstance();
     //反射实例化Activity而已
 }

你可能感兴趣的:(Activity启动流程(下))