App启动流程

2022-05-15  本文已影响0人  小城哇哇

1.概述

前面两篇文章(Zygote工作流程SystemServer工作流程)分析了ZygoteSystemServer的启动流程,在Zygote和SystemServer启动完成之后Android系统就算已经开机运行起来了,这时候通过点击桌面Launcher上的图标就可以触发app的启动了。 App的启动流程其实可以整体分为两部分,一部分是点击Launcher上的app图标,Launcher通过AMS向Zygote请求孵化应用进程,随后ActivityThread的main方法就启动了。第二部分是ActivityThread(App的进程)启动之后,App进程通过AMS创建Application和Activity,最后执行Activity的生命周期。
简要概括的话就是两个流程:
1)Launcher -> AMS -> Zygote -> ActivityThead
2)ActivityThread -> AMS -> (Application/Activity
鉴于整体上App的启动流程非常复杂,涉及的代码量很大,代码分析流程中只列举关键点,梳理出大体流程。

2.创建App进程

2.1 从Launcher到AMS

Launcher其实就是我们Android手机上的桌面,我们安装的App会在桌面上展示应用图标,点击桌面上的图标就可以启动我们的App,Launcher相当于是启动App的入口,本质上Launcher也是一个Activity界面,类似于系统的主Activity。

Launcher.java //继承于Activity
public void onClick(View v) {
    ....
    onClickAppShortcut(v);
    ....
}
protected void onClickAppShortcut(final View v) {
    ....
    startAppShortcutOrInfoActivity(v);
}
private void startAppShortcutOrInfoActivity(View v) {
    ....
    boolean success = startActivitySafely(v, intent, item);
    ....
}
public boolean startActivitySafely(View v, Intent intent, ItemInfo item) {
    ......
    //关键的点是要创建一个新的任务栈
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    ......
    //调用startActivity方法
    startActivity(intent, optsBundle);
    ......
}

由于Launcher其实也是一个Activity,所以点击Launcher上的图标经历一系列方法调用,最终其实还是调用到Activity的startActivity方法中。

public void startActivity(Intent intent, @Nullable Bundle options) {
    if (options != null) {
        startActivityForResult(intent, -1, options);
    } else {
        startActivityForResult(intent, -1);
    }
}
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
        @Nullable Bundle options) {
    if (mParent == null) {
        //App启动流程会调用到这里
        ....
        //关键点在Instrumentation的execStartActivity方法
        Instrumentation.ActivityResult ar =
            mInstrumentation.execStartActivity(
                this, mMainThread.getApplicationThread(), mToken, this,
                intent, requestCode, options);
        if (ar != null) {
            mMainThread.sendActivityResult(
                mToken, mEmbeddedID, requestCode, ar.getResultCode(),
                ar.getResultData());
        }
        ....
    } else {
        if (options != null) {
            mParent.startActivityFromChild(this, intent, requestCode, options);
        } else {
            mParent.startActivityFromChild(this, intent, requestCode);
        }
    }
}

可以看到,方法调用经过startActivity->startActivityForResult->execStartActivity,这里就涉及到了Instrumentation,它既负责Activity的创建,也负责Application的创建。

Instrumentation#execStartActivity
public ActivityResult execStartActivity(
    Context who, IBinder contextThread, IBinder token, String target,
    Intent intent, int requestCode, Bundle options) {
    IApplicationThread whoThread = (IApplicationThread) contextThread;
    ....
    try {
        ....
        //通过AMS启动Activity
        int result = ActivityManager.getService()
            .startActivity(whoThread, who.getBasePackageName(), intent,
                    intent.resolveTypeIfNeeded(who.getContentResolver()),
                    token, target, requestCode, 0, null, options);
        checkStartActivityResult(result, intent);
    } catch (RemoteException e) {
        throw new RuntimeException("Failure from system", e);
    }
    return null;
}

方法调用到了ActivityManager.getService的startActivity方法,getService获取到的是AMS的代理对象。

public static IActivityManager getService() {
    return IActivityManagerSingleton.get();
}

private static final Singleton<IActivityManager> IActivityManagerSingleton =
        new Singleton<IActivityManager>() {
            @Override
            protected IActivityManager create() {
                //通过ServiceManager获取AMS代理对象,拿到的是一个Binder
                final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
                final IActivityManager am = IActivityManager.Stub.asInterface(b);
                return am;
            }
        };

通过AMS的代理对象调用startActivity方法执行,启动阶段来到了AMS中。

2.2从AMS到Zygote

下面来到了AMS的startActivity方法。

public final int startActivity(IApplicationThread caller, String callingPackage,
        Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
        int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
    return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
            resultWho, requestCode, startFlags, profilerInfo, bOptions,
            UserHandle.getCallingUserId());
}

//中途会经过多个startActivityAsUser的重载方法
public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
        Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
        int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
        boolean validateIncomingUser) {
    ....
    //通过mActivityStartController设置多个参数
    return mActivityStartController.obtainStarter(intent, "startActivityAsUser")
            .setCaller(caller)
            .setCallingPackage(callingPackage)
            .setResolvedType(resolvedType)
            .setResultTo(resultTo)
            .setResultWho(resultWho)
            .setRequestCode(requestCode)
            .setStartFlags(startFlags)
            .setProfilerInfo(profilerInfo)
            .setActivityOptions(bOptions)
            .setMayWait(userId) //设置了MayWait
            .execute(); //关键点是execute方法
}

方法调用到了ActivityStarter的execute方法。

int execute() {
    try {      
        if (mRequest.mayWait) {
           //由于上方设置了MayWait,所以调用到了startActivityMayWait
            return startActivityMayWait(mRequest.caller, mRequest.callingUid,
                    mRequest.callingPackage, mRequest.intent, mRequest.resolvedType,
                    mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
                    mRequest.resultWho, mRequest.requestCode, mRequest.startFlags,
                    mRequest.profilerInfo, mRequest.waitResult, mRequest.globalConfig,
                    mRequest.activityOptions, mRequest.ignoreTargetSecurity, mRequest.userId,
                    mRequest.inTask, mRequest.reason,
                    mRequest.allowPendingRemoteAnimationRegistryLookup);
        } else {
           ....
        }
    } finally {
        onExecutionComplete();
    }
}

从execute方法开始调用流程就十分的长了,这里就只列出来方法的调用栈了。

ActivityStarter:
startActivityMayWait()
startActivity() //重载1
startActivity() //重载2
startActivity() //重载3
startActivityUnchecked()
ActivityStackSupervisor:
resumeFocusedStackTopActivityLocked()
ActivityStack:
resumeTopActivityUncheckedLocked()
resumeTopActivityInnerLocked()
ActivityStackSupervisor:
startSpecificActivityLocked()

ActivityStackSupervisor的startSpecificActivityLocked方法会对Activity的启动是否需要创建新的进程做一个区分,

void startSpecificActivityLocked(ActivityRecord r,
        boolean andResume, boolean checkConfig) {
    //获取进程
    ProcessRecord app = mService.getProcessRecordLocked(r.processName,
            r.info.applicationInfo.uid, true);
    if (app != null && app.thread != null) {
       //存在进程
        try {
            ....
            //启动Activity
            realStartActivityLocked(r, app, andResume, checkConfig);
            return;
        } catch (RemoteException e) {
            Slog.w(TAG, "Exception when starting activity "
                    + r.intent.getComponent().flattenToShortString(), e);
        }
    }
    //不存在进程,调用AMS的startProcessLocked方法创建新的进程
    mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
            "activity", r.intent.getComponent(), false, false, true);
}

启动流程又回到了AMS中的startProcessLocked方法,startProcessLocked方法仍然涉及到多个重载的调用,最终会执行到AMS的startProcess方法。在调用的过程中有一个很关键的地方会是设置一个entryPoint参数为android.app.ActivityThread,这个值代表着进程fork成功后,进程会执行到ActivityThread的main方法。

private ProcessStartResult startProcess(String hostingType, String entryPoint,
        ProcessRecord app, int uid, int[] gids, int runtimeFlags, int mountExternal,
        String seInfo, String requiredAbi, String instructionSet, String invokeWith,
        long startTime) {
            ....
            //通过Process.start方法来创建应用进程,entryPoint参数的值为android.app.ActivityThread
            startResult = Process.start(entryPoint,
                    app.processName, uid, uid, gids, runtimeFlags, mountExternal,
                    app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
                    app.info.dataDir, invokeWith,
                    new String[] {PROC_START_SEQ_IDENT + app.startSeq});
           ....
        return startResult;
}

Process#start
public static final ProcessStartResult start(final String processClass,
                              final String niceName,
                              int uid, int gid, int[] gids,
                              int runtimeFlags, int mountExternal,
                              int targetSdkVersion,
                              String seInfo,
                              String abi,
                              String instructionSet,
                              String appDataDir,
                              String invokeWith,
                              String[] zygoteArgs) {
           //向名字为zygote的socket发送消息                   
    return zygoteProcess.start(processClass, niceName, uid, gid, gids,
                runtimeFlags, mountExternal, targetSdkVersion, seInfo,
                abi, instructionSet, appDataDir, invokeWith, zygoteArgs);
}

ZygoteProcess.java
public final Process.ProcessStartResult start(final String processClass,
                                              final String niceName,
                                              int uid, int gid, int[] gids,
                                              int runtimeFlags, int mountExternal,
                                              int targetSdkVersion,
                                              String seInfo,
                                              String abi,
                                              String instructionSet,
                                              String appDataDir,
                                              String invokeWith,
                                              String[] zygoteArgs) {
    try {
        //如果需要,则打开Socket,用来和zygote通讯
        return startViaZygote(processClass, niceName, uid, gid, gids,
                runtimeFlags, mountExternal, targetSdkVersion, seInfo,
                abi, instructionSet, appDataDir, invokeWith, false /* startChildZygote */,
                zygoteArgs);
    } catch (ZygoteStartFailedEx ex) {
    }
}

private static Process.ProcessStartResult zygoteSendArgsAndGetResult(
        ZygoteState zygoteState, ArrayList<String> args)
        throws ZygoteStartFailedEx {
    try {
        int sz = args.size();
        for (int i = 0; i < sz; i++) {
            if (args.get(i).indexOf('\n') >= 0) {
                throw new ZygoteStartFailedEx("embedded newlines not allowed");
            }
        }
        writer.write(Integer.toString(args.size()));
        writer.newLine();
        for (int i = 0; i < sz; i++) {
            String arg = args.get(i);
            writer.write(arg);
            writer.newLine();
        }
        writer.flush();
        result.pid = inputStream.readInt();
        result.usingWrapper = inputStream.readBoolean();
        if (result.pid < 0) {
            throw new ZygoteStartFailedEx("fork() failed");
        }
        return result;
    } catch (IOException ex) {
        zygoteState.close();
        throw new ZygoteStartFailedEx(ex);
    }
}

经过了上述一连串的调用,这时候启动流程就走到了Zygote阶段。

2.3 从Zygote到ActivityThread

Zygote的初始化流程就不描述了,这里只从Zygote收到fork应用进程的请求开始分析。Zygote收到AMS发送的创建应用进程请求后回执行到ZygoteConnection的processOneCommand方法。

Runnable processOneCommand(ZygoteServer zygoteServer) {
    String args[];
    Arguments parsedArgs = null;
    FileDescriptor[] descriptors;
    ....
    //fork一个新的进程
    pid = Zygote.forkAndSpecialize(parsedArgs.uid, parsedArgs.gid, parsedArgs.gids,
            parsedArgs.runtimeFlags, rlimits, parsedArgs.mountExternal, parsedArgs.seInfo,
            parsedArgs.niceName, fdsToClose, fdsToIgnore, parsedArgs.startChildZygote,
            parsedArgs.instructionSet, parsedArgs.appDataDir);

    try {
        if (pid == 0) {
            ....
            //执行子进程相关操作
            return handleChildProc(parsedArgs, descriptors, childPipeFd,
                    parsedArgs.startChildZygote);
        } else {
            ....
        }
    } finally {
        IoUtils.closeQuietly(childPipeFd);
        IoUtils.closeQuietly(serverPipeFd);
    }
}

private Runnable handleChildProc(Arguments parsedArgs, FileDescriptor[] descriptors,
        FileDescriptor pipeFd, boolean isZygote) {
    ....
    if (parsedArgs.invokeWith != null) {
        WrapperInit.execApplication(parsedArgs.invokeWith,
                parsedArgs.niceName, parsedArgs.targetSdkVersion,
                VMRuntime.getCurrentInstructionSet(),
                pipeFd, parsedArgs.remainingArgs);
    } else {
        if (!isZygote) {
            //AMS发送过来的请求isZygote为false
            return ZygoteInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs,
                    null /* classLoader */);
        } else {
            return ZygoteInit.childZygoteInit(parsedArgs.targetSdkVersion,
                    parsedArgs.remainingArgs, null /* classLoader */);
        }
    }
}

这里最终执行到了ZygoteInit.zygoteInit方法,这个方法在Zygote工作流程中分析过了,唯一的区别是这里执行到的是ActivityThread的main方法。

3.启动App主线程(ActivityThread)

3.1 从ActivityThread到AMS

Zygote创建进程成功之后会调用到ActivtyThread的main方法,这里也就是我们App的主线程。

public static void main(String[] args) {
    ....
    Looper.prepareMainLooper(); //创建主线程Looper
    ....
    ActivityThread thread = new ActivityThread();
    thread.attach(false, startSeq); //启动流程的关键点在attach方法 
    
    if (sMainThreadHandler == null) {
        sMainThreadHandler = thread.getHandler(); //创建主线程的Handler
    }
    ....
    Looper.loop(); //开启主线程Looper的轮询
    ....
}

private void attach(boolean system, long startSeq) {
    if (!system) { //system为false,代码会执行到这里。
        ....
        //获取AMS代理对象
        final IActivityManager mgr = ActivityManager.getService();
        try {
            //AMS和ApplicationThread建立绑定
            mgr.attachApplication(mAppThread, startSeq);
        } catch (RemoteException ex) {
            throw ex.rethrowFromSystemServer();
        }
        ....
    } else {
        ....
    }
    ....
}

public final void attachApplication(IApplicationThread thread, long startSeq) {
    synchronized (this) {
        //获取一些id信息
        int callingPid = Binder.getCallingPid();
        final int callingUid = Binder.getCallingUid();
        final long origId = Binder.clearCallingIdentity();
        //绑定ApplicationThread对象
        attachApplicationLocked(thread, callingPid, callingUid, startSeq);
        Binder.restoreCallingIdentity(origId);
    }
}

private final boolean attachApplicationLocked(IApplicationThread thread,
        int pid, int callingUid, long startSeq) {
        ....
            //调用到ApplicationThread的方法
            thread.bindApplication(processName, appInfo, providers,
                    app.instr.mClass,
                    profilerInfo, app.instr.mArguments,
                    app.instr.mWatcher,
                    app.instr.mUiAutomationConnection, testMode,
                    mBinderTransactionTrackingEnabled, enableTrackAllocation,
                    isRestrictedBackupMode || !normalMode, app.persistent,
                    new Configuration(getGlobalConfiguration()), app.compat,
                    getCommonServicesLocked(app.isolated),
                    mCoreSettingsObserver.getCoreSettingsLocked(),
                    buildSerial, isAutofillCompatEnabled);
    ....
    if (normalMode) {
        try {
            //检查需要启动的Activity
            if (mStackSupervisor.attachApplicationLocked(app)) {
                didSomething = true;
            }
        } catch (Exception e) {
            badApp = true;
        }
    }
    ....
}

ActivityThread执行attach方法之后调用到AMS的attachApplication方法,最终调用到attachApplicationLocked。调用到这里会有两条关键代码执行路径:
1)执行ApplicationThread的bindApplication方法,这条路径就是来创建Application的。
2)执行ActivityStackSupervisor的attachApplicationLocked方法,这条路径是用来创建Activity的。

3.2.1 从AMS到Application

AMS的attachApplicationLocked方法会调用到ApplicationThread的bindApplication方法。

public final void bindApplication(String processName, ApplicationInfo appInfo,
        List<ProviderInfo> 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,
        String buildSerial, boolean autofillCompatibilityEnabled) {
    ....
    //设置一些App的参数信息
    AppBindData data = new AppBindData();
    data.processName = processName;  //设置进程名称
    data.appInfo = appInfo;
    data.providers = providers;
    data.instrumentationName = instrumentationName;
    data.instrumentationArgs = instrumentationArgs;
    data.instrumentationWatcher = instrumentationWatcher;
    data.instrumentationUiAutomationConnection = instrumentationUiConnection;
    data.debugMode = debugMode;
    data.enableBinderTracking = enableBinderTracking;
    data.trackAllocation = trackAllocation;
    data.restrictedBackupMode = isRestrictedBackupMode;
    data.persistent = persistent;
    data.config = config;
    data.compatInfo = compatInfo;
    data.initProfilerInfo = profilerInfo;
    data.buildSerial = buildSerial;
    data.autofillCompatibilityEnabled = autofillCompatibilityEnabled;
    sendMessage(H.BIND_APPLICATION, data);//发送一条Message给主线程的Handler进行Application的创建
}

//ActivityThread中的Handler类‘H’的方法
public void handleMessage(Message msg) {
    switch (msg.what) {
        case BIND_APPLICATION:
            AppBindData data = (AppBindData)msg.obj;
            handleBindApplication(data); //处理Application的创建
            break;
        ......
    }
}

ApplicationThread会向ActivityThread中的Handler发送一条创建Application的消息来处理Application的创建,最后会调用handleBindApplication方法。

private void handleBindApplication(AppBindData data) {
    ....
    if (ii != null) {
        ApplicationInfo instrApp;
        instrApp = getPackageManager().getApplicationInfo(ii.packageName, 0,
                UserHandle.myUserId());
        //构建ContextImpl
        final ContextImpl instrContext = ContextImpl.createAppContext(this, pi);
        //获取其classLoader
        final ClassLoader cl = instrContext.getClassLoader();
        //构建Instrumentation 
        mInstrumentation = (Instrumentation)
            cl.loadClass(data.instrumentationName.getClassName()).newInstance();
    } else {
        mInstrumentation = new Instrumentation();
        mInstrumentation.basicInit(this);
    }
    ....
    Application app;
    //构建Application
    app = data.info.makeApplication(data.restrictedBackupMode, null);
    ....
   if (!data.restrictedBackupMode) {
      if (!ArrayUtils.isEmpty(data.providers)) {
        //判断是否有ContentProvider,如果存在ContentProvider会优先执行ContentProvider
        installContentProviders(app, data.providers);
        ...
      }
   }
    ....
    //调用Application的onCreate方法
    mInstrumentation.callApplicationOnCreate(app);
    ....
}

handleBindApplication方法会创建Instrumentation对象,用这个对象来处理Application的创建和生命周期方法的执行,这里还涉及到一个知识点,app的ContentProvider会优先Application创建,至此Application的创建就完成了。

3.2.2 从AMS到Activity

AMS的attachApplicationLocked方法会调用到ActivityStackSupervisor的attachApplicationLocked方法。

boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
    final String processName = app.processName;
    boolean didSomething = false;
    for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
        final ActivityDisplay display = mActivityDisplays.valueAt(displayNdx);
        for (int stackNdx = display.getChildCount() - 1; stackNdx >= 0; --stackNdx) {
            final ActivityStack stack = display.getChildAt(stackNdx); //查找Activity栈
            if (!isFocusedStack(stack)) {
                continue;
            }
            stack.getAllRunningVisibleActivitiesLocked(mTmpActivityList);
            final ActivityRecord top = stack.topRunningActivityLocked();
            final int size = mTmpActivityList.size();
            for (int i = 0; i < size; i++) {
                final ActivityRecord activity = mTmpActivityList.get(i);
                if (activity.app == null && app.uid == activity.info.applicationInfo.uid
                        && processName.equals(activity.processName)) {
                    try {
                        //定位到需要启动的Activity
                        if (realStartActivityLocked(activity, app,
                                top == activity /* andResume */, true /* checkConfig */)) {
                            didSomething = true;
                        }
                    } catch (RemoteException e) {
                       ....
                    }
                }
            }
        }
    }
    ....
}

查找到需要启动的Activity后会执行realStartActivityLocked方法,方法代码比较多,核心流程是创建Activity事务交给AMS来发送创建Activity请求。

final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
        boolean andResume, boolean checkConfig) throws RemoteException {
            ...
            //创建Activity事务
            final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread,
                    r.appToken);
            //构建LaunchActivityItem对象,并传入clientTransaction中,用作callback        
            clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
                    System.identityHashCode(r), r.info,
                    mergedConfiguration.getGlobalConfiguration(),
                    mergedConfiguration.getOverrideConfiguration(), r.compat,
                    r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,
                    r.persistentState, results, newIntents, mService.isNextTransitionForward(),
                    profilerInfo));
            final ActivityLifecycleItem lifecycleItem;
            if (andResume) {
                lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward());
            } else {
                lifecycleItem = PauseActivityItem.obtain();
            }
            //给事务设置生命周期
            clientTransaction.setLifecycleStateRequest(lifecycleItem);         
            //通过AMS来获取ClientLifecycleManager对象来执行事务
           mService.getLifecycleManager().scheduleTransaction(clientTransaction);
    .....
}

ClientLifecycleManager#scheduleTransaction
void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
    //获取ApplicationThread
    final IApplicationThread client = transaction.getClient();
    //执行事务
    transaction.schedule();
}

ClientTransaction#schedule
public void schedule() throws RemoteException {
    //这里的mClient是ApplicationThread
    mClient.scheduleTransaction(this);
}

ApplicationThread#scheduleTransaction
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
    //ActivityThread是继承自ClientTransactionHandler的,scheduleTransaction方法在ClientTransactionHandler里面
    ActivityThread.this.scheduleTransaction(transaction);
}

ClientTransactionHandler#scheduleTransaction
void scheduleTransaction(ClientTransaction transaction) {
    transaction.preExecute(this);
    //这里也是向ActivityThread里面的'H'这个Handler发送了一个EXECUTE_TRANSACTION的消息,并且将ClientTransaction对象也传了进去
    sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}

ClientTransactionHandler会向ActivityThread中的Handler发送一条执行事务的消息,收到消息执行创建Activity的事务。

class H extends Handler {
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case EXECUTE_TRANSACTION:
                //首先取出ClientTransaction对象
                final ClientTransaction transaction = (ClientTransaction) msg.obj;
                //将ClientTransaction传入execute方法
                mTransactionExecutor.execute(transaction);
        }
    }
}

TransactionExecutor#execute
public void execute(ClientTransaction transaction) {
    final IBinder token = transaction.getActivityToken();
    executeCallbacks(transaction);
    executeLifecycleState(transaction);
    mPendingActions.clear();
}

TransactionExecutor#executeCallbacks
public void executeCallbacks(ClientTransaction transaction) {
    //取出ClientTransaction对象里面的callback,即上面的LaunchActivityItem
    final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
    final int size = callbacks.size();
    for (int i = 0; i < size; ++i) {
        final ClientTransactionItem item = callbacks.get(i);
        final int postExecutionState = item.getPostExecutionState();
        final int closestPreExecutionState = mHelper.getClosestPreExecutionState(r,
                item.getPostExecutionState());
        item.execute(mTransactionHandler, token, mPendingActions);
        item.postExecute(mTransactionHandler, token, mPendingActions);
    }
}

LaunchActivityItem#execute
public void execute(ClientTransactionHandler client, IBinder token,
        PendingTransactionActions pendingActions) {
    //调用ActivityThread的handleLaunchActivity方法
    client.handleLaunchActivity(r, pendingActions, null);
}

ActivityThread#handleLaunchActivity
public Activity handleLaunchActivity(ActivityClientRecord r,
        PendingTransactionActions pendingActions, Intent customIntent) {
    ....
    //performLaunchActivity方法最终会来到Activity的创建和onCreate方法的执行
    final Activity a = performLaunchActivity(r, customIntent);
    ....
    return a;
}

最终方法调用到了ActivityThread的handleLaunchActivity方法,进而执行到performLaunchActivity方法,最后就可以完成Activity的创建了。

4.总结

经过以上分析可以知道App的启动流程可以大体总结为几个阶段:
1)桌面Launcher进程请求AMS。
2) AMS请求Zygote创建应用进程。
3) Zygote孵化进程后执行ActivityThread的main方法。
4)ActivityThread请求AMS。
5)AMS发送创建Application请求。
6)AMS发送创建Activity请求。

上一篇下一篇

猜你喜欢

热点阅读