Activity启动流程(Android 10源码分析)

目录

一、启动进程start目标Activity

二、进入AMS进程启动目标Activity

三、进入APP进程创建Activity

四、创建新的目标进程

五、进入新创建的目标APP进程

六、进入AMS进程执行Application初始化和启动Activity

七、回到目标APP进程初始化Application

八、从AMS进程启动Activity

九、总结


流程图:

下面的源码分析,将按照上图的流程图一步一步分析

一、启动进程start目标Activity

启动Activity先从startActivity开始,点进startActivity进入ContextWrapper类中,↓

    @Override
    public void startActivity(Intent intent) {
        mBase.startActivity(intent);
    }

上图中mBase对象是Context,Context的实现类为ContextImpl,进入ContextImpl的startActivity方法看下,↓

    @Override
    public void startActivity(Intent intent, Bundle options) {
        final int targetSdkVersion = getApplicationInfo().targetSdkVersion;
        //mMainThread为ActivityThread,获取的getInstrumentation()为Instrumentation
        mMainThread.getInstrumentation().execStartActivity(
                getOuterContext(), mMainThread.getApplicationThread(), null,
                (Activity) null, intent, -1, options);
    }

上图中代码最后一句为重点,已经加了说明,就是调用了 Instrumentation 的 execStartActivity() 方法,Instrumentation为仪表盘,管理着Activity和Application的生命周期,一个进程对应着一个Instrumentation。接着进入Instrumentation类看下,↓

public ActivityResult execStartActivity(Context who, IBinder contextThread, IBinder token, Activity target,
                    Intent intent, int requestCode, Bundle options) {
        IApplicationThread whoThread = (IApplicationThread) contextThread;
        //......部分代码省略
        try {
            intent.migrateExtraStreamToClipData();
            intent.prepareToLeaveProcess(who);
            //重点:这里获取了ATMS代理对象IActivityTaskManager,拿到ATMS代理对象就可以跨进程调用AMS的startActivity
            int result = ActivityTaskManager.getService()
                .startActivity(whoThread, who.getBasePackageName(), intent,
                        intent.resolveTypeIfNeeded(who.getContentResolver()),
                        token, target != null ? target.mEmbeddedID : null,
                        requestCode, 0, null, options);
            checkStartActivityResult(result, intent);
        }
        return null;
    }

上图中加了注释处通过ActivityTaskManager.getService()获取了ATMS代理对象IActivityTaskManager,该IActivityTaskManager代理对象是一个接口,实现类为ActivityTaskManagerService,获取后即可调用ActivityTaskManagerService(ATMS)的startActivity方法,这里就是跨进程操作AMS的入口(第一次跨进程)。

注意:该ActivityTaskManagerService(ATMS)和ActivityManagerService(AMS)同属一个进程,他们之间的通信交互使用的是handler,该类是在10.0开始新加的一个类,这一处代码和10.0之前的有所不同。接下来就进入AMS进程中ATMS类的startActivity方法继续分析。↓

二、进入AMS进程启动目标Activity

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) {
        userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
                Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
        //看这里
        return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
                .setCaller(caller)
                .setCallingPackage(callingPackage)
                .setResolvedType(resolvedType)
                .setResultTo(resultTo)
                .setResultWho(resultWho)
                .setRequestCode(requestCode)
                .setStartFlags(startFlags)
                .setProfilerInfo(profilerInfo)
                .setActivityOptions(bOptions)
                .setMayWait(userId)
                .execute();
    }

分析上图代码,在ATMS类中,经过了多个方法调用,最终走到startActivityAsUser方法里,在这个方法return中getActivityStartController().obtainStarter方法返回的是一个ActivityStarter对象,然后调用了该对象的execute()方法,接着进入ActivityStarter类中继续分析。↓

int execute() {
        try {
            if (mRequest.mayWait) {
                return startActivityMayWait(mRequest.caller, mRequest.callingUid,
                        mRequest.callingPackage, mRequest.realCallingPid, mRequest.realCallingUid,
                        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,
                        mRequest.originatingPendingIntent, mRequest.allowBackgroundActivityStart);
            }
        } finally {
            onExecutionComplete();
        }
    }

上图中,ActivityStarter的execute()方法中,mRequest.mayWait返回为true,设置为true的地方在上上图中的setMayWait(userId)处,因此这里会走startActivityMayWait()方法,继续分析startActivityMayWait()方法。↓

private int startActivityMayWait(IApplicationThread caller, int callingUid,
            String callingPackage, int requestRealCallingPid, int requestRealCallingUid,......) {
            //.......省略部分代码
            final ActivityRecord[] outRecord = new ActivityRecord[1];
            int res = startActivity(caller, intent, ephemeralIntent, resolvedType, aInfo, rInfo,
                    voiceSession, voiceInteractor, resultTo, resultWho, requestCode, callingPid,
                    callingUid, callingPackage, realCallingPid, realCallingUid, startFlags, options,
                    ignoreTargetSecurity, componentSpecified, outRecord, inTask, reason,
                    allowPendingRemoteAnimationRegistryLookup, originatingPendingIntent,
                    allowBackgroundActivityStart);

            Binder.restoreCallingIdentity(origId);
            //.......省略部分代码
}

上图中,在startActivityMayWait()方法调用了startActivity()方法,继续分析startActivity()方法。↓

private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
            String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,......) {
        //.......省略部分代码
        mLastStartActivityResult = startActivity(caller, intent, ephemeralIntent, resolvedType,
                aInfo, rInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode,
                callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
                options, ignoreTargetSecurity, componentSpecified, mLastStartActivityRecord,
                inTask, allowPendingRemoteAnimationRegistryLookup, originatingPendingIntent,
                allowBackgroundActivityStart);       
        //.......省略部分代码
        return getExternalResult(mLastStartActivityResult);
    }

上图中,在startActivity()方法里调用了名称相同但参数个数不同的startActivity()方法,继续分析startActivity()方法。↓

private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,String resolvedType,......) {
        //......省略部分代码

        final int res = startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
                true /* doResume */, checkedOptions, inTask, outActivity, restrictedBgActivity);
        mSupervisor.getActivityMetricsLogger().notifyActivityLaunched(res, outActivity[0]);
        return res;
    }
}

上图中,这段代码很长,但只需要找到这个方法里最末处,在这里调用了一个startActivity(),又是一个名称相同但参数个数不同的startActivity()方法,继续进入分析。↓

private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
                IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
                int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
                ActivityRecord[] outActivity, boolean restrictedBgActivity) {
        int result = START_CANCELED;
        final ActivityStack startedActivityStack;
        try {
            mService.mWindowManager.deferSurfaceLayout();
            result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
                    startFlags, doResume, options, inTask, outActivity, restrictedBgActivity);
        }
}

上图中,在startActivity()方法里调用了startActivityUnchecked(),进入startActivityUnchecked()方法继续分析。↓

private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
            IVoiceInteractionSession voiceSession,......) {

        //计算启动 Activity 的 Flag 值
        computeLaunchingTaskFlags();
        //......省略部分代码

        //处理 Task 和 Activity 的进栈操作
        mTargetStack.startActivityLocked(mStartActivity, topFocused, newTask, mKeepCurTransition,mOptions);
        if (mDoResume) {
            final ActivityRecord topTaskActivity = mStartActivity.getTaskRecord().topRunningActivityLocked();
            if (!mTargetStack.isFocusable() || (topTaskActivity != null && topTaskActivity.mTaskOverlay
                    && mStartActivity != topTaskActivity)) {
                mTargetStack.ensureActivitiesVisibleLocked(mStartActivity, 0, !PRESERVE_WINDOWS);
                mTargetStack.getDisplay().mDisplayContent.executeAppTransition();
            } else {
                if (mTargetStack.isFocusable()
                        && !mRootActivityContainer.isTopDisplayFocusedStack(mTargetStack)) {
                    mTargetStack.moveToFront("startActivityUnchecked");
                }
                //启动栈中顶部的 Activity
                mRootActivityContainer.resumeFocusedStacksTopActivities(mTargetStack, mStartActivity, mOptions);
            }
        }
        //......省略部分代码
}

上图中,关键代码加了注释,最后进入到RootActivityContainer类的resumeFocusedStacksTopActivities()方法中,继续分析。↓

 boolean resumeFocusedStacksTopActivities(ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
        if (!mStackSupervisor.readyToResume()) {
            return false;
        }
        boolean result = false;
        if (targetStack != null && (targetStack.isTopStackOnDisplay()|| getTopDisplayFocusedStack() == targetStack)) {
            result = targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
        }

        //......省略部分代码
        return result;
    }

上图中,这里调用了ActivityStack类的resumeTopActivityUncheckedLocked()方法,该类是Activity在AMS的栈管理,用来记录已经启动的Activity的先后关系,状态信息等,通过ActivityStack决定是否需要启动新的进程。进入resumeTopActivityUncheckedLocked()方法继续分析。↓

boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
        if (mInResumeTopActivity) {
            return false;
        }
        boolean result = false;
        try {
            mInResumeTopActivity = true;
            result = resumeTopActivityInnerLocked(prev, options);
            final ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */);
            if (next == null || !next.canTurnScreenOn()) {
                checkReadyForSleep();
            }
        }
        return result;
    }

上图中,注意resumeTopActivityInnerLocked()方法,进入查看该方法。↓

private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
        //......省略部分代码
        if (next.attachedToProcess()) {
            //......省略部分代码
        } else {
            if (!next.hasBeenLaunched) {
                next.hasBeenLaunched = true;
            } else {
                if (SHOW_APP_STARTING_PREVIEW) {
                    next.showStartingWindow(null /* prev */, false /* newTask */,
                            false /* taskSwich */);
                }
            }
            mStackSupervisor.startSpecificActivityLocked(next, true, true);
        }
        return true;

}

上图中,在代码最末尾处调用了startSpecificActivityLocked()方法,点进去查看。↓

void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) {
        // Is this activity's application already running?
        //根据进程名和进程id判断目标进程是否已经创建,如果没有则代表进程未创建
        final WindowProcessController wpc = mService.getProcessController(r.processName, r.info.applicationInfo.uid);

        boolean knownToBeDead = false;
        //如果进程已经创建,这里直接调用realStartActivityLocked去启动Activity
        if (wpc != null && wpc.hasThread()) {
            try {
                realStartActivityLocked(r, wpc, andResume, checkConfig);
                return;
            } catch (RemoteException e) {
            }
            knownToBeDead = true;
        }
        if (getKeyguardController().isKeyguardLocked()) {
            r.notifyUnknownVisibilityLaunched();
        }
        try {
            //走到这里说明目标进程未创建,这里使用handler发送消息给ActivityManagerService类,让AMS创建一个新的进程
            final Message msg = PooledLambda.obtainMessage(
                    ActivityManagerInternal::startProcess, mService.mAmInternal, r.processName,
                    r.info.applicationInfo, knownToBeDead, "activity", r.intent.getComponent());
            mService.mH.sendMessage(msg);
        }
    }

上图中,进入到ActivityStackSupervisor的startSpecificActivityLocked()方法中,ActivityStackSupervisor是ActivityStack的管理类,在startSpecificActivityLocked()方法中,先去判断目标进程是否已经创建,已经创建的话就去启动Activity,否则使用handler发送消息给ActivityManagerService,即AMS,让AMS去创建一个新的进程出来,到这里就有两条分支,一个是去启动Activity,另一个是去创建进程,先看启动Activity这条线,后面再分析创建进程。接下来进入realStartActivityLocked()方法。↓

boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
            boolean andResume, boolean checkConfig) throws RemoteException {
                //......省略部分代码

                //创建一个Activity启动事务,同时传入proc.getThread(),该对象实际为ApplicationThread
                final ClientTransaction clientTransaction = ClientTransaction.obtain(proc.getThread(), r.appToken);
                final DisplayContent dc = r.getDisplay().mDisplayContent;
                //把LaunchActivityItem加入事务中,后面会调用到该类的handleLaunchActivity()方法
                clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
                        System.identityHashCode(r), r.info,
                        mergedConfiguration.getGlobalConfiguration(),
                        mergedConfiguration.getOverrideConfiguration(), r.compat,
                        r.launchedFromPackage, task.voiceInteractor, proc.getReportedProcState(),
                        r.icicle, r.persistentState, results, newIntents,
                        dc.isNextTransitionForward(), proc.createProfilerInfoIfNeeded(),
                                r.assistToken));

                final ActivityLifecycleItem lifecycleItem;
                if (andResume) {
                    lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward());
                } else {
                    lifecycleItem = PauseActivityItem.obtain();
                }
                clientTransaction.setLifecycleStateRequest(lifecycleItem);
            //在这里启动事务
            Service.getLifecycleManager().scheduleTransaction(clientTransaction);

             //......省略部分代码
}

上图中,重点代码做了注释,可以看到,在这段代码中,主要是创建事务,同时传入ApplicationThread,而ApplicationThread继承于Binder,这里传入目的主要后面用来跟目标APP进程通信。然后就是启动事务,mService.getLifecycleManager()方法返回的是ClientLifecycleManager对象,接下来继续分析ClientLifecycleManager的scheduleTransaction()方法,↓

void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
        final IApplicationThread client = transaction.getClient();
        transaction.schedule();
        if (!(client instanceof Binder)) {
            transaction.recycle();
        }
    }

上图中,在ClientLifecycleManager类的scheduleTransaction()方法中可以明确看到,这里实际调用了ClientTransaction对象的schedule()方法,进入到ClientTransaction的schedule()方法继续分析。↓

private IApplicationThread mClient;
public void schedule() throws RemoteException {
      mClient.scheduleTransaction(this);
}

上图中,在ClientTransaction类的schedule()方法里,又调用了mClient的scheduleTransaction()方法,而这个mClient实际就是在上上上图中创建Activity启动事务时传入的ApplicationThread对象,也就是说,这里开始从AMS进程跨进程调用ApplicationThread 的scheduleTransaction()方法(第二次跨进程),接下来进入到 ApplicationThread 的 scheduleTransaction() 方法中分析。

三、进入APP进程创建Activity

private class ApplicationThread extends IApplicationThread.Stub {
        @Override
        public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
            ActivityThread.this.scheduleTransaction(transaction);
        }
}

上图中,先介绍下ApplicationThread,它是ActivityThread的内部类,继承于IApplicationThread.Stub,而IApplicationThread.Stub又继承于Binder,所以本质还是一个Binder,用来在ActivityThread和AMS之间通信。继续分析scheduleTransaction()方法,这里又调用了ActivityThread的scheduleTransaction()方法,点进去分析。↓

void scheduleTransaction(ClientTransaction transaction) {
        transaction.preExecute(this);
        sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}

上图中,走到了ActivityThread的父类ClientTransactionHandler中的scheduleTransaction()方法,在这个方法里发送handler消息H.EXECUTE_TRANSACTION,并且 Message 中的 obj 就是启动 Activity 的事务对象。而这个 Handler 的具体实现是 ActivityThread 中的 H 对象,接着找到接收handle消息的地方继续分析。↓

class H extends Handler {
        
        public static final int EXECUTE_TRANSACTION = 159;

        public void handleMessage(Message msg) {
            switch (msg.what) {
                case EXECUTE_TRANSACTION:
                    final ClientTransaction transaction = (ClientTransaction) msg.obj;
                    mTransactionExecutor.execute(transaction);
                    if (isSystem()) {
                        transaction.recycle();
                    }
                    break;
            }
        }
   }

上图中,接收handler消息的地方定义在ActivityThread类中,在这里,又调用了TransactionExecutor的execute()方法,点进去继续分析。↓

public void execute(ClientTransaction transaction) {
        //......省略部分代码

        executeCallbacks(transaction);

        executeLifecycleState(transaction);
        mPendingActions.clear();
        if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "End resolving transaction");
    }

上图中,点进去executeCallbacks(transaction)方法继续分析。↓

public void executeCallbacks(ClientTransaction transaction) {
        final List callbacks = transaction.getCallbacks();
  
        //......省略部分代码

        final int size = callbacks.size();
        for (int i = 0; i < size; ++i) {
            final ClientTransactionItem item = callbacks.get(i);
            if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "Resolving callback: " + item);
            final int postExecutionState = item.getPostExecutionState();
            final int closestPreExecutionState = mHelper.getClosestPreExecutionState(r,
                    item.getPostExecutionState());
            if (closestPreExecutionState != UNDEFINED) {
                cycleToPath(r, closestPreExecutionState, transaction);
            }
            //item的类型其实就是LaunchActivityItem
            item.execute(mTransactionHandler, token, mPendingActions);
            item.postExecute(mTransactionHandler, token, mPendingActions);
            
            //......省略部分代码
        }
    }

上图中,在 executeCallback()方法中,会遍历事务中的 callback 并执行 execute 方法,这些 callbacks 是在前面创建Activity启动事务时添加的。↓

boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
            boolean andResume, boolean checkConfig) throws RemoteException {
                //......省略部分代码
                //创建一个Activity启动事务,同时传入proc.getThread(),该对象实际为ApplicationThread
                final ClientTransaction clientTransaction = ClientTransaction.obtain(
                        proc.getThread(), r.appToken);
                final DisplayContent dc = r.getDisplay().mDisplayContent;
                //把LaunchActivityItem加入事务中,后面会调用到该类的handleLaunchActivity()方法
                clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
                        System.identityHashCode(r), r.info,
                        mergedConfiguration.getGlobalConfiguration(),
                        mergedConfiguration.getOverrideConfiguration(), r.compat,
                        r.launchedFromPackage, task.voiceInteractor, proc.getReportedProcState(),
                        r.icicle, r.persistentState, results, newIntents,
                        dc.isNextTransitionForward(), proc.createProfilerInfoIfNeeded(),
                                r.assistToken));
                //......省略部分代码
}

上图中,添加的callback对象其实就是LaunchActivityItem类型的对象,所以在上上图中,item.execute(mTransactionHandler, token, mPendingActions),就是调用了LaunchActivityItem类的execute()方法,进入LaunchActivityItem类的execute()方法继续分析。↓

@Override
public void execute(ClientTransactionHandler client, IBinder token,
            PendingTransactionActions pendingActions) {
    ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
    mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,mPendingResults, mPendingNewIntents, mIsForward,mProfilerInfo, client, mAssistToken);
    //注意这里
    client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
}

上图中,在LaunchActivityItem类的execute()方法里,调用了client.handleLaunchActivity()方法,这里的client为ClientTransactionHandler类型,而ClientTransactionHandler的实现类是ActivityThread,所以这里又回到了ActivityThread类,并调用了handleLaunchActivity()方法,接着进入handleLaunchActivity()方法继续分析。↓

public Activity handleLaunchActivity(ActivityClientRecord r,
            PendingTransactionActions pendingActions, Intent customIntent) {
        //......省略部分代码
        //初始化 Activity 的 WindowManager,每一个 Activity 都会对应一个“窗口”
        WindowManagerGlobal.initialize();
        //重点
        final Activity a = performLaunchActivity(r, customIntent);
        //......省略部分代码
        return a;
    }

上图中,通过调用performLaunchActivity()方法创建并显示一个Activity,进入performLaunchActivity()方法继续分析。↓

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        //......省略部分代码
        ContextImpl appContext = createBaseContextForActivity(r);
        Activity activity = null;
        try {
            //通过反射创建目标 Activity 对象
            java.lang.ClassLoader cl = appContext.getClassLoader();
            activity = mInstrumentation.newActivity(cl, component.getClassName(), r.intent);
            StrictMode.incrementExpectedActivityCount(activity.getClass());
        }
        try {
            Application app = r.packageInfo.makeApplication(false, mInstrumentation);
            if (activity != null) {
                //创建window
                Window window = null;
                if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
                    window = r.mPendingRemoveWindow;
                    r.mPendingRemoveWindow = null;
                    r.mPendingRemoveWindowManager = null;
                }
                //调用 attach 方法建立 Activity 与 Context 之间的联系,创建 PhoneWindow 对象,并与 Activity 进行关联操作           
                activity.attach(appContext, this, getInstrumentation(), r.token,
                        r.ident, app, r.intent, r.activityInfo, title, r.parent,
                        r.embeddedID, r.lastNonConfigurationInstances, config,
                        r.referrer, r.voiceInteractor, window, r.configCallback,
                        r.assistToken);
                int theme = r.activityInfo.getThemeResource();
                if (theme != 0) {
                    //设置主题
                    activity.setTheme(theme);
                }

                activity.mCalled = false;
                //通过 Instrumentation 最终调用 Activity 的 onCreate 方法
                if (r.isPersistable()) {
                    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
                } else {
                    mInstrumentation.callActivityOnCreate(activity, r.state);
                }
                r.activity = activity;
            }
        }
        return activity;
    }

上图中,主要代码已经加了注释,主要做了以下这些事情,

  1. 使用反射创建目标 Activity 对象;
  2. 创建PhoneWindow 对象,
  3. 调用attach方法绑定Activity;
  4. 调用 Activity 的 onCreate 方法

步骤4中,是通过Instrumentation来调用的Activity的onCreate()方法,点进去看下callActivityOnCreate()方法。↓

public void callActivityOnCreate(Activity activity, Bundle icicle) {
        prePerformCreate(activity);
        activity.performCreate(icicle);
        postPerformCreate(activity);
    }

上图中,可以看到调用了Activity的performCreate()方法,进入performCreate()方法查看。↓

final void performCreate(Bundle icicle, PersistableBundle persistentState) {
        //在这里调用了Activity的生命周期onCreate方法
        if (persistentState != null) {
            onCreate(icicle, persistentState);
        } else {
            onCreate(icicle);
        }
        //......省略部分代码
    }

protected void onCreate(@Nullable Bundle savedInstanceState) {
         //......省略部分代码
    }

至此,目标Activity已经被成功创建,并开始了生命周期的回调;

四、创建新的目标进程

在文章当中分析startSpecificActivityLocked()方法的时候,说到该方法里会先判断目标进程是否已经创建,如果已经创建就走启动Activity流程,如果没有,就去创建进程,接下来就分析创建进程,并在创建进程后启动Activity这个过程,重新回到startSpecificActivityLocked()方法。↓

void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) {
        //根据进程名和进程id判断目标进程是否已经创建,如果没有则代表进程未创建
        final WindowProcessController wpc =mService.getProcessController(r.processName, r.info.applicationInfo.uid);
        boolean knownToBeDead = false;
        //如果进程已经创建,这里直接调用realStartActivityLocked去启动Activity
        if (wpc != null && wpc.hasThread()) {
            try {
                realStartActivityLocked(r, wpc, andResume, checkConfig);
                return;
            }
        }
        //......省略部分代码
        try {
            //走到这里说明目标进程未创建,这里使用handler发送消息给ActivityManagerService类,让AMS创建一个新的进程
            final Message msg = PooledLambda.obtainMessage(
                    ActivityManagerInternal::startProcess, mService.mAmInternal, r.processName,
                    r.info.applicationInfo, knownToBeDead, "activity", r.intent.getComponent());
            mService.mH.sendMessage(msg);
        }
    }

上图中,startSpecificActivityLocked()方法定义在ActivityStackSupervisor类中。

1、在obtainMessage()方法中,可以看到调用了ActivityManagerInternal类的startProcess()方法,ActivityManagerInternal是一个抽象类,它的实现类在AMS中,即LocalService类。

2、通过mService.mH.sendMessage(msg)发送handle消息告诉AMS类去执行startProcess()方法,这里mService为ATMS对象,mH是定义在ATMS类中的一个handler。

接着进入AMS中,找到startProcess()方法继续分析。↓

public void startProcess(String processName, ApplicationInfo info,boolean 
knownToBeDead, String hostingType, ComponentName hostingName) {
    try {
        synchronized (ActivityManagerService.this) {
            startProcessLocked(processName, info, knownToBeDead, 0 ,new HostingRecord(hostingType, hostingName),false , false ,true);
        }
    }
}

上图中,只做了一件事,使用同步锁调用了startProcessLocked()方法,进入该方法继续分析。↓

final ProcessRecord startProcessLocked(String processName,ApplicationInfo info, boolean knownToBeDead, 
int intentFlags,HostingRecord hostingRecord, ......) {
        return mProcessList.startProcessLocked(processName, info, knownToBeDead, intentFlags,
                hostingRecord, allowWhileBooting, isolated, 0, keepIfLarge,
                null, null, null,null);
    }

上图中,点击startProcessLocked()方法继续分析。↓

final ProcessRecord startProcessLocked(String processName, ApplicationInfo info,
            boolean knownToBeDead, int intentFlags, HostingRecord hostingRecord,......) {
        //......省略部分代码
        final boolean success = startProcessLocked(app, hostingRecord, abiOverride);
        checkSlow(startTime, "startProcess: done starting proc!");
        return success ? app : null;
}

上图中,调用了相同名称参数个数不同的startProcessLocked()方法,进入继续分析。↓

final boolean startProcessLocked(ProcessRecord app, HostingRecord hostingRecord,
            String abiOverride) {
        return startProcessLocked(app, hostingRecord,
                false /* disableHiddenApiChecks */, false /* mountExtStorageFull */, abiOverride);
    }

上图中,又调用了相同名称参数个数不同的startProcessLocked()方法,进入继续分析。↓

boolean startProcessLocked(ProcessRecord app, HostingRecord hostingRecord,
            boolean disableHiddenApiChecks, boolean mountExtStorageFull,String abiOverride) {
    //......省略部分代码
    try {
        //......省略部分代码
        //创建好新的进程后会立即启动ActivityThread,进入main入口,这里传入ActivityThread路径
        final String entryPoint = "android.app.ActivityThread";
        return startProcessLocked(hostingRecord, entryPoint, app, uid, gids,
                    runtimeFlags, mountExternal, seInfo, requiredAbi, instructionSet, invokeWith,
                    startTime);
        } catch (RuntimeException e) {
            //......省略部分代码
            return false;
        }
}

上图中,又调用了相同名称参数个数不同的startProcessLocked()方法,同时传入了ActivityThread的路径,因为在新的进程创建完成后,会立即启动ActivityThread的main入口,进入startProcessLocked()方法继续分析。↓

boolean startProcessLocked(HostingRecord hostingRecord,String entryPoint,ProcessRecord app, int uid, int[] gids,......) {
        //......省略部分代码
        //是否异步开启进程,默认为true
        if (mService.mConstants.FLAG_PROCESS_START_ASYNC) {
               mService.mProcStartHandler.post(() -> {
                try {
                    //注意这里
                    final Process.ProcessStartResult startResult = startProcess(app.hostingRecord,
                            entryPoint, app, app.startUid, gids, runtimeFlags, mountExternal,
                            app.seInfo, requiredAbi, instructionSet, invokeWith, app.startTime);
                    synchronized (mService) {
                        handleProcessStartedLocked(app, startResult, startSeq);
                    }
                } catch (RuntimeException e) {
                    //......省略部分代码
                }
            });
            return true;
        }
    }

上图中,使用异步方式调用了startProcess()方法,进去该方法分析。↓

private Process.ProcessStartResult startProcess(HostingRecord hostingRecord, String entryPoint,
            ProcessRecord app, int uid, int[] gids, int runtimeFlags, int mountExternal,
            String seInfo, String requiredAbi, String instructionSet, String invokeWith,
            long startTime) {
        try {
            final Process.ProcessStartResult startResult;
            if (hostingRecord.usesWebviewZygote()) {
                //......省略部分代码
            } else if (hostingRecord.usesAppZygote()) {
                //......省略部分代码
            } else {
                startResult = Process.start(entryPoint,
                        app.processName, uid, uid, gids, runtimeFlags, mountExternal,
                        app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
                        app.info.dataDir, invokeWith, app.info.packageName,
                        new String[] {PROC_START_SEQ_IDENT + app.startSeq});
            }
            checkSlow(startTime, "startProcess: returned from zygote!");
            return startResult;
        }
    }

上图中,走到了else里面的代码,为什么是else,在ATMS发送handler消息告诉AMS创建进程时,调用了AMS的内部类LocalService中的startProcess()方法,在该方法里new了一个HostingRecord两个参数的构造参数的对象,所以默认进程类型是“REGULAR_ZYGOTE”。在看Process.start()方法,这里开始调用了Process的创建,点进去Process的start()方法继续分析。↓

public static ProcessStartResult start(@NonNull final String processClass,
                                           @Nullable final String niceName,
                                           int uid, int gid, @Nullable int[] gids,
                                           int runtimeFlags,
                                           int mountExternal,
                                           int targetSdkVersion,
                                           @Nullable String seInfo,
                                           @NonNull String abi,
                                           @Nullable String instructionSet,
                                           @Nullable String appDataDir,
                                           @Nullable String invokeWith,
                                           @Nullable String packageName,
                                           @Nullable String[] zygoteArgs) {
        return ZYGOTE_PROCESS.start(processClass, niceName, uid, gid, gids,
                    runtimeFlags, mountExternal, targetSdkVersion, seInfo,
                    abi, instructionSet, appDataDir, invokeWith, packageName,
                    /*useUsapPool=*/ true, zygoteArgs);
    }

上图中,这里又调用了ZYGOTE_PROCESS.start()方法,ZYGOTE_PROCESS就是系统中的Zygote进程,Android中所有的App进程都是由Zygote进程fork生成的,包括SystemServer进程,Zygote是所有Java进程的父进程,到这里就开始了目标APP进程的创建了,目标APP进程创建成功,会立即启动ActivityThread线程,并进入它的main方法。接下来进入ActivityThread的main入口进行分析。↓

五、进入新创建的目标APP进程

public static void main(String[] args) {
        //......省略部分代码

        Looper.prepareMainLooper();

        //......省略部分代码
        ActivityThread thread = new ActivityThread();
        thread.attach(false, startSeq);

        Looper.loop();
   }

上图中,又回到了目标APP进程中,这里又完成了一次跨进程,在目标APP进程的ActivityThread的Main入口,主要做了两件事,一是创建MainLooper,并loop起来。二是调用ActivityThread的attach()方法,这个方法很重要,点进去分析。↓

private void attach(boolean system, long startSeq) {
        if (!system) {
            //获取AMS代理,然后调用AMS的attachApplication方法
            final IActivityManager mgr = ActivityManager.getService();
            try {
                mgr.attachApplication(mAppThread, startSeq);
            } catch (RemoteException ex) {
                throw ex.rethrowFromSystemServer();
            }
            //......省略部分代码
        } else {
            //......省略部分代码
        }
    }

上图中,在attach()方法中,获取了AMS的代理,然后跨进程调用了AMS的attachApplication()方法,同时传入了ApplicationThread对象,这里又是一次跨进程,进入AMS的attachApplication()方法继续分析。↓

六、进入AMS进程执行Application初始化和启动Activity

private final boolean attachApplicationLocked(IApplicationThread thread,int pid, int callingUid, long startSeq) {
    //......省略部分代码
    try {
        if (app.isolatedEntryPoint != null) {
            //......省略部分代码
        } else if (instr2 != null) {
            //调用ApplicationThread的bindApplication去初始化Application
            thread.bindApplication(processName, appInfo, providers,
                   instr2.mClass,
                   profilerInfo, instr2.mArguments,
                   instr2.mWatcher,
                   instr2.mUiAutomationConnection, testMode,
                   mBinderTransactionTrackingEnabled, enableTrackAllocation,
                   isRestrictedBackupMode || !normalMode, app.isPersistent(),
                   new Configuration(app.getWindowProcessController().getConfiguration()),
                   app.compat, getCommonServicesLocked(app.isolated),
                   mCoreSettingsObserver.getCoreSettingsLocked(),
                   buildSerial, autofillOptions, contentCaptureOptions);
        }
    } catch (Exception e) {
        //......省略部分代码
        return false;
    }

    //......省略部分代码
    if (normalMode) {
        try {
            //去启动Activity
            didSomething = mAtmInternal.attachApplication(app.getWindowProcessController());
        } catch (Exception e) {
            Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
            badApp = true;
        }
    }
}

上图中,主要做了两件事:

1、调用了ApplicationThread的bindApplication()方法去初始化Application,又是一次跨进程调用。

2、通过ATMS去启动目标Activity。

先来分析ApplicationThread的bindApplication()方法。↓

七、回到目标APP进程初始化Application

public final void bindApplication(String processName, ApplicationInfo appInfo,...) {
    //......省略部分代码
    AppBindData data = new AppBindData();
    //......省略部分代码
    sendMessage(H.BIND_APPLICATION, data);
}

上图中,在ApplicationThread中的bindApplication()方法里最终发送了一个H.BIND_APPLICATION消息,接着查看handler接收消息的地方。↓

class H extends Handler {
    public static final int BIND_APPLICATION        = 110;
    
    //......省略部分代码
    public void handleMessage(Message msg) {
            switch (msg.what) {
                case BIND_APPLICATION:
                    AppBindData data = (AppBindData)msg.obj;
                    handleBindApplication(data);
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                    break;
    }
}

上图中,又调用了handleBindApplication(data)方法,继续进入分析。↓

private void handleBindApplication(AppBindData data) {
    //......省略部分代码
    if (ii != null) {
        final LoadedApk pi = getPackageInfo(instrApp, data.compatInfo, appContext.getClassLoader(), false, true, false);
        final ContextImpl instrContext = ContextImpl.createAppContext(this, pi, appContext.getOpPackageName());
        try {
            final ClassLoader cl = instrContext.getClassLoader();
            //创建仪表盘
            mInstrumentation = (Instrumentation) cl.loadClass(data.instrumentationName.getClassName()).newInstance();
        }
        //初始化仪表盘
        mInstrumentation.init(this, instrContext, appContext, component, data.instrumentationWatcher, data.instrumentationUiAutomationConnection);
    }

    //......省略部分代码
    Application app;
    try {
        //创建Application
        app = data.info.makeApplication(data.restrictedBackupMode, null);
        
        //......省略部分代码
        try {
            mInstrumentation.onCreate(data.instrumentationArgs);
        }
        try {
            //调用Application的onCreate方法
            mInstrumentation.callApplicationOnCreate(app);
        }
    }
}

上图中,主要做了三件事:

1、创建仪表盘。

2、使用LoadedApk创建一个Application,不过最终还是使用的仪表盘利用反射创建的Application类。

3、使用仪表盘初始化Application,点击去可以查看下mInstrumentation.callApplicationOnCreate()方法。↓

public void callApplicationOnCreate(Application app) {
        app.onCreate();
    }

到此,Application即初始化完成。

八、从AMS进程启动Activity

在步骤六中,有两步,第一步初始化Application,这里已经完成,还有一步去ATMS启动Activity,先看下之前的代码。↓

private final boolean attachApplicationLocked(IApplicationThread thread,int pid, int callingUid, long startSeq) { 
    //......省略部分代码
    if (normalMode) {
        try {
            //去启动Activity
            didSomething = mAtmInternal.attachApplication(app.getWindowProcessController());
        } catch (Exception e) {
            Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
            badApp = true;
        }
    }
}

上图中,是在AMS的attachApplicationLocked()方法里,mAtmInternal是一个ActivityTaskManagerInternal对象,它是一个抽象类,由LocalService以AMS内部类形式实现,进入attachApplication()方法继续查看。↓

final class LocalService extends ActivityTaskManagerInternal {
    public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
        synchronized (mGlobalLockWithoutBoost) {
            return mRootActivityContainer.attachApplication(wpc);
        }
    }
}

上图中,这个方法只做了一件事,调用RootActivityContainer的attachApplication()方法,下面进入RootActivityContainer类找到

attachApplication()方法。↓

boolean attachApplication(WindowProcessController app) throws RemoteException {
    for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
        if (stack != null) {
            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.mUid == activity.info.applicationInfo.uid && processName.equals(activity.processName)) {
                    try {
                        if (mStackSupervisor.realStartActivityLocked(activity, app,top == activity, true)) {
                            didSomething = true;
                        }
                    } catch (RemoteException e) {
                    }
                }
            }
        }
    }
    return didSomething;
}

上图中,可以看到这里调用了 ActivityStackSupervisor 的 realStartActivityLocked() 方法,到这里就和前面启动Activity的流程完全一致了,可以在流程图中找到。↓

Activity启动流程(Android 10源码分析)_第1张图片

九、总结

至此,Activity的创建过程已经梳理完了,总结一下,主要分两个支线,一个是:

1、启动进程start目标Activity,并进入AMS。

2、AMS判断目标Activity所属进程是否存在,存在就去通知ApplicationThread启动目标Activity。

3、目标ActivityThread收到通知,执行Activity的创建、初始化操作。

另一个是:

1、启动进程start目标Activity,并进入AMS。

2、AMS判断目标Activity所属进程是否存在,不存在就去通知Zygote进程创建一个新的进程。

3、新的进程进入ActivityThread的main入口,初始化Looper,并通知AMS进程去初始化Application。

4、同时AMS又去执行Activity的启动,接着通知ApplicationThread启动目标Activity。

5、目标ActivityThread收到通知,执行Activity的创建、初始化操作。

你可能感兴趣的:(Android,使用,android)