Android 9.0版本的activity的启动流程于之前相比发生了一些改动,但是改动也不大。本文基于Android 9.0版本源码,从Activity启动方法startActivity为切入口分析整个流程。

首先从activity的startActivity开始

//activity  @Override    public void startActivity(Intent intent) {        this.startActivity(intent, null);    }   @Override    public void startActivity(Intent intent, @Nullable Bundle options) {        if (options != null) {            startActivityForResult(intent, -1, options);        } else {            // Note we want to go through this call for compatibility with            // applications that may have overridden the method.            startActivityForResult(intent, -1);        }    } public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,            @Nullable Bundle options) {        if (mParent == null) {            options = transferSpringboardActivityOptions(options);            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());            }            if (requestCode >= 0) {                // If this start is requesting a result, we can avoid making                // the activity visible until the result is received.  Setting                // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the                // activity hidden during this time, to avoid flickering.                // This can only be done when a result is requested because                // that guarantees we will get information back when the                // activity is finished, no matter what happens to it.                mStartedActivity = true;            }            cancelInputsAndStartExitTransition(options);            // TODO Consider clearing/flushing other event sources and events for child windows.        } else {            if (options != null) {                mParent.startActivityFromChild(this, intent, requestCode, options);            } else {                // Note we want to go through this method for compatibility with                // existing applications that may have overridden it.                mParent.startActivityFromChild(this, intent, requestCode);            }        }    }//Instrumentation public ActivityResult execStartActivity(            Context who, IBinder contextThread, IBinder token, Activity target,            Intent intent, int requestCode, Bundle options) {          ...        try {            intent.migrateExtraStreamToClipData();            intent.prepareToLeaveProcess(who);            int result = ActivityManager.getService()                .startActivity(whoThread, who.getBasePackageName(), intent,                        intent.resolveTypeIfNeeded(who.getContentResolver()),                        token, target != null ? target.mEmbeddedID : null,                        requestCode, 0, null, options);            checkStartActivityResult(result, intent);        } catch (RemoteException e) {            throw new RuntimeException("Failure from system", e);        }        return null;    }

调用startActivity之后经过一系列的调用会到Instrumentation的execStartActivity方法,在方法里可以看到会调用

 ActivityManager.getService()                .startActivity(whoThread, who.getBasePackageName(), intent,                        intent.resolveTypeIfNeeded(who.getContentResolver()),                        token, target != null ? target.mEmbeddedID : null,                        requestCode, 0, null, options);

ActivityManager.getService()获得ActivityManagerService提供的服务,进入ActivityManagerService中查看startActivity方法

  @Override    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());    }   @Override    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) {        return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,                resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,                true /*validateIncomingUser*/);    }  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) {        enforceNotIsolatedCaller("startActivity");        userId = mActivityStartController.checkTargetUser(userId, validateIncomingUser,                Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");        // TODO: Switch to user app stacks here.        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)                .execute();    }

最终可以看到是调用ActivityStartController.obtainStarter获得一个ActivityStarter并调用ActivityStarter的execute方法,进入此方法

 int execute() {        try {            // TODO(b/64750076): Look into passing request directly to these methods to allow            // for transactional diffs and preprocessing.            if (mRequest.mayWait) {                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 {                return startActivity(mRequest.caller, mRequest.intent, mRequest.ephemeralIntent,                        mRequest.resolvedType, mRequest.activityInfo, mRequest.resolveInfo,                        mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,                        mRequest.resultWho, mRequest.requestCode, mRequest.callingPid,                        mRequest.callingUid, mRequest.callingPackage, mRequest.realCallingPid,                        mRequest.realCallingUid, mRequest.startFlags, mRequest.activityOptions,                        mRequest.ignoreTargetSecurity, mRequest.componentSpecified,                        mRequest.outActivity, mRequest.inTask, mRequest.reason,                        mRequest.allowPendingRemoteAnimationRegistryLookup);            }        } finally {            onExecutionComplete();        }    }

在ActivityManagerService.startActivityAsUser中调用了ActivityStarter.setMayWait方法,所以这里会调用startActivityMayWait方法,进入到startActivityMayWait方法中查看流程

 private int startActivityMayWait(IApplicationThread caller, int callingUid,            String callingPackage, Intent intent, String resolvedType,            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,            IBinder resultTo, String resultWho, int requestCode, int startFlags,            ProfilerInfo profilerInfo, WaitResult outResult,            Configuration globalConfig, SafeActivityOptions options, boolean ignoreTargetSecurity,            int userId, TaskRecord inTask, String reason,            boolean allowPendingRemoteAnimationRegistryLookup) {            ...            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);            ...            return res;        }    } private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,            String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,            IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,            String callingPackage, int realCallingPid, int realCallingUid, int startFlags,            SafeActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,            ActivityRecord[] outActivity, TaskRecord inTask, String reason,            boolean allowPendingRemoteAnimationRegistryLookup) {        ...        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);        ...        return getExternalResult(mLastStartActivityResult);    }    private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,            String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,            IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,            String callingPackage, int realCallingPid, int realCallingUid, int startFlags,            SafeActivityOptions options,            boolean ignoreTargetSecurity, boolean componentSpecified, ActivityRecord[] outActivity,            TaskRecord inTask, boolean allowPendingRemoteAnimationRegistryLookup) {        ...        return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,                true /* doResume */, checkedOptions, inTask, outActivity);    }    private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,                IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,                int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,                ActivityRecord[] outActivity) {        ...            result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,                    startFlags, doResume, options, inTask, outActivity);        ...        postStartActivityProcessing(r, result, mTargetStack);        return result;    }

startActivityMayWait经过一系列startActivity方法的调用最终进入到了startActivityUnchecked,startActivityUnchecked方法会做启动模式的检查等工作。平时在外部设置的activity启动模式在这里就会进行判断并进行相应的操作。

 private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,            int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,            ActivityRecord[] outActivity) {        setInitialState(r, options, inTask, doResume, startFlags, sourceRecord, voiceSession,                voiceInteractor);        computeLaunchingTaskFlags();        computeSourceStack();        mIntent.setFlags(mLaunchFlags);        ActivityRecord reusedActivity = getReusableIntentActivity();        int preferredWindowingMode = WINDOWING_MODE_UNDEFINED;        int preferredLaunchDisplayId = DEFAULT_DISPLAY;        if (mOptions != null) {            preferredWindowingMode = mOptions.getLaunchWindowingMode();            preferredLaunchDisplayId = mOptions.getLaunchDisplayId();        }        // windowing mode and preferred launch display values from {@link LaunchParams} take        // priority over those specified in {@link ActivityOptions}.        if (!mLaunchParams.isEmpty()) {            if (mLaunchParams.hasPreferredDisplay()) {                preferredLaunchDisplayId = mLaunchParams.mPreferredDisplayId;            }            if (mLaunchParams.hasWindowingMode()) {                preferredWindowingMode = mLaunchParams.mWindowingMode;            }        }        if (reusedActivity != null) {            // When the flags NEW_TASK and CLEAR_TASK are set, then the task gets reused but            // still needs to be a lock task mode violation since the task gets cleared out and            // the device would otherwise leave the locked task.            if (mService.getLockTaskController().isLockTaskModeViolation(reusedActivity.getTask(),                    (mLaunchFlags & (FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK))                            == (FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK))) {                Slog.e(TAG, "startActivityUnchecked: Attempt to violate Lock Task Mode");                return START_RETURN_LOCK_TASK_MODE_VIOLATION;            }            // True if we are clearing top and resetting of a standard (default) launch mode            // ({@code LAUNCH_MULTIPLE}) activity. The existing activity will be finished.            final boolean clearTopAndResetStandardLaunchMode =                    (mLaunchFlags & (FLAG_ACTIVITY_CLEAR_TOP | FLAG_ACTIVITY_RESET_TASK_IF_NEEDED))                            == (FLAG_ACTIVITY_CLEAR_TOP | FLAG_ACTIVITY_RESET_TASK_IF_NEEDED)                    && mLaunchMode == LAUNCH_MULTIPLE;            // If mStartActivity does not have a task associated with it, associate it with the            // reused activity's task. Do not do so if we're clearing top and resetting for a            // standard launchMode activity.            if (mStartActivity.getTask() == null && !clearTopAndResetStandardLaunchMode) {                mStartActivity.setTask(reusedActivity.getTask());            }            if (reusedActivity.getTask().intent == null) {                // This task was started because of movement of the activity based on affinity...                // Now that we are actually launching it, we can assign the base intent.                reusedActivity.getTask().setIntent(mStartActivity);            }            // This code path leads to delivering a new intent, we want to make sure we schedule it            // as the first operation, in case the activity will be resumed as a result of later            // operations.            if ((mLaunchFlags & FLAG_ACTIVITY_CLEAR_TOP) != 0                    || isDocumentLaunchesIntoExisting(mLaunchFlags)                    || isLaunchModeOneOf(LAUNCH_SINGLE_INSTANCE, LAUNCH_SINGLE_TASK)) {                final TaskRecord task = reusedActivity.getTask();                // In this situation we want to remove all activities from the task up to the one                // being started. In most cases this means we are resetting the task to its initial                // state.                final ActivityRecord top = task.performClearTaskForReuseLocked(mStartActivity,                        mLaunchFlags);                // The above code can remove {@code reusedActivity} from the task, leading to the                // the {@code ActivityRecord} removing its reference to the {@code TaskRecord}. The                // task reference is needed in the call below to                // {@link setTargetStackAndMoveToFrontIfNeeded}.                if (reusedActivity.getTask() == null) {                    reusedActivity.setTask(task);                }                if (top != null) {                    if (top.frontOfTask) {                        // Activity aliases may mean we use different intents for the top activity,                        // so make sure the task now has the identity of the new intent.                        top.getTask().setIntent(mStartActivity);                    }                    deliverNewIntent(top);                }            }            mSupervisor.sendPowerHintForLaunchStartIfNeeded(false /* forceSend */, reusedActivity);            reusedActivity = setTargetStackAndMoveToFrontIfNeeded(reusedActivity);            final ActivityRecord outResult =                    outActivity != null && outActivity.length > 0 ? outActivity[0] : null;            // When there is a reused activity and the current result is a trampoline activity,            // set the reused activity as the result.            if (outResult != null && (outResult.finishing || outResult.noDisplay)) {                outActivity[0] = reusedActivity;            }            if ((mStartFlags & START_FLAG_ONLY_IF_NEEDED) != 0) {                // We don't need to start a new activity, and the client said not to do anything                // if that is the case, so this is it!  And for paranoia, make sure we have                // correctly resumed the top activity.                resumeTargetStackIfNeeded();                return START_RETURN_INTENT_TO_CALLER;            }            if (reusedActivity != null) {                setTaskFromIntentActivity(reusedActivity);                if (!mAddingToTask && mReuseTask == null) {                    // We didn't do anything...  but it was needed (a.k.a., client don't use that                    // intent!)  And for paranoia, make sure we have correctly resumed the top activity.                    resumeTargetStackIfNeeded();                    if (outActivity != null && outActivity.length > 0) {                        outActivity[0] = reusedActivity;                    }                    return mMovedToFront ? START_TASK_TO_FRONT : START_DELIVERED_TO_TOP;                }            }        }        if (mStartActivity.packageName == null) {            final ActivityStack sourceStack = mStartActivity.resultTo != null                    ? mStartActivity.resultTo.getStack() : null;            if (sourceStack != null) {                sourceStack.sendActivityResultLocked(-1 /* callingUid */, mStartActivity.resultTo,                        mStartActivity.resultWho, mStartActivity.requestCode, RESULT_CANCELED,                        null /* data */);            }            ActivityOptions.abort(mOptions);            return START_CLASS_NOT_FOUND;        }        // If the activity being launched is the same as the one currently at the top, then        // we need to check if it should only be launched once.        final ActivityStack topStack = mSupervisor.mFocusedStack;        final ActivityRecord topFocused = topStack.getTopActivity();        final ActivityRecord top = topStack.topRunningNonDelayedActivityLocked(mNotTop);        final boolean dontStart = top != null && mStartActivity.resultTo == null                && top.realActivity.equals(mStartActivity.realActivity)                && top.userId == mStartActivity.userId                && top.app != null && top.app.thread != null                && ((mLaunchFlags & FLAG_ACTIVITY_SINGLE_TOP) != 0                || isLaunchModeOneOf(LAUNCH_SINGLE_TOP, LAUNCH_SINGLE_TASK));        if (dontStart) {            // For paranoia, make sure we have correctly resumed the top activity.            topStack.mLastPausedActivity = null;            if (mDoResume) {                mSupervisor.resumeFocusedStackTopActivityLocked();            }            ActivityOptions.abort(mOptions);            if ((mStartFlags & START_FLAG_ONLY_IF_NEEDED) != 0) {                // We don't need to start a new activity, and the client said not to do                // anything if that is the case, so this is it!                return START_RETURN_INTENT_TO_CALLER;            }            deliverNewIntent(top);            // Don't use mStartActivity.task to show the toast. We're not starting a new activity            // but reusing 'top'. Fields in mStartActivity may not be fully initialized.            mSupervisor.handleNonResizableTaskIfNeeded(top.getTask(), preferredWindowingMode,                    preferredLaunchDisplayId, topStack);            return START_DELIVERED_TO_TOP;        }        boolean newTask = false;        final TaskRecord taskToAffiliate = (mLaunchTaskBehind && mSourceRecord != null)                ? mSourceRecord.getTask() : null;        // Should this be considered a new task?        int result = START_SUCCESS;        if (mStartActivity.resultTo == null && mInTask == null && !mAddingToTask                && (mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0) {            newTask = true;            result = setTaskFromReuseOrCreateNewTask(taskToAffiliate, topStack);        } else if (mSourceRecord != null) {            result = setTaskFromSourceRecord();        } else if (mInTask != null) {            result = setTaskFromInTask();        } else {            // This not being started from an existing activity, and not part of a new task...            // just put it in the top task, though these days this case should never happen.            setTaskToCurrentTopOrCreateNewTask();        }        if (result != START_SUCCESS) {            return result;        }        mService.grantUriPermissionFromIntentLocked(mCallingUid, mStartActivity.packageName,                mIntent, mStartActivity.getUriPermissionsLocked(), mStartActivity.userId);        mService.grantEphemeralAccessLocked(mStartActivity.userId, mIntent,                mStartActivity.appInfo.uid, UserHandle.getAppId(mCallingUid));        if (newTask) {            EventLog.writeEvent(EventLogTags.AM_CREATE_TASK, mStartActivity.userId,                    mStartActivity.getTask().taskId);        }        ActivityStack.logStartActivity(                EventLogTags.AM_CREATE_ACTIVITY, mStartActivity, mStartActivity.getTask());        mTargetStack.mLastPausedActivity = null;        mSupervisor.sendPowerHintForLaunchStartIfNeeded(false /* forceSend */, mStartActivity);        mTargetStack.startActivityLocked(mStartActivity, topFocused, newTask, mKeepCurTransition,                mOptions);        if (mDoResume) {            final ActivityRecord topTaskActivity =                    mStartActivity.getTask().topRunningActivityLocked();            if (!mTargetStack.isFocusable()                    || (topTaskActivity != null && topTaskActivity.mTaskOverlay                    && mStartActivity != topTaskActivity)) {                // If the activity is not focusable, we can't resume it, but still would like to                // make sure it becomes visible as it starts (this will also trigger entry                // animation). An example of this are PIP activities.                // Also, we don't want to resume activities in a task that currently has an overlay                // as the starting activity just needs to be in the visible paused state until the                // over is removed.                mTargetStack.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);                // Go ahead and tell window manager to execute app transition for this activity                // since the app transition will not be triggered through the resume channel.                mService.mWindowManager.executeAppTransition();            } else {                // If the target stack was not previously focusable (previous top running activity                // on that stack was not visible) then any prior calls to move the stack to the                // will not update the focused stack.  If starting the new activity now allows the                // task stack to be focusable, then ensure that we now update the focused stack                // accordingly.                if (mTargetStack.isFocusable() && !mSupervisor.isFocusedStack(mTargetStack)) {                    mTargetStack.moveToFront("startActivityUnchecked");                }                mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity,                        mOptions);            }        } else if (mStartActivity != null) {            mSupervisor.mRecentTasks.add(mStartActivity.getTask());        }        mSupervisor.updateUserStackLocked(mStartActivity.userId, mTargetStack);        mSupervisor.handleNonResizableTaskIfNeeded(mStartActivity.getTask(), preferredWindowingMode,                preferredLaunchDisplayId, mTargetStack);        return START_SUCCESS;    }

那不管设置那种启动模式最终都会进入ActivityStackSupervisor.resumeFocusedStackTopActivityLocked

//ActivityStackSupervisor  boolean resumeFocusedStackTopActivityLocked(            ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {        if (!readyToResume()) {            return false;        }        if (targetStack != null && isFocusedStack(targetStack)) {            return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);        }        final ActivityRecord r = mFocusedStack.topRunningActivityLocked();        if (r == null || !r.isState(RESUMED)) {            mFocusedStack.resumeTopActivityUncheckedLocked(null, null);        } else if (r.isState(RESUMED)) {            // Kick off any lingering app transitions form the MoveTaskToFront operation.            mFocusedStack.executeAppTransition(targetOptions);        }        return false;    }    //ActivityStack boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {           ...         result = resumeTopActivityInnerLocked(prev, options);        ... private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {        ...        boolean pausing = mStackSupervisor.pauseBackStacks(userLeaving, next, false);        if (mResumedActivity != null) {            pausing |= startPausingLocked(userLeaving, false, next, false);        }        ...        mStackSupervisor.startSpecificActivityLocked(next, true, true);        ...        return true;    }

在这个方法里会先判断有没有activity处在resume,如果有的话那就先让其执行pause,然后在执行startSpecificActivityLocked。执行pause的流程和执行activity的创建其实流程差不多的,都是通过ClientLifecycleManager.scheduleTransaction执行相应的操作,具体后面在分析。进入到ActivityStackSupervisor.startSpecificActivityLocked方法中

 void startSpecificActivityLocked(ActivityRecord r,            boolean andResume, boolean checkConfig) {        // Is this activity's application already running?        ProcessRecord app = mService.getProcessRecordLocked(r.processName,                r.info.applicationInfo.uid, true);        getLaunchTimeTracker().setLaunchTime(r);        if (app != null && app.thread != null) {            try {                if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0                        || !"android".equals(r.info.packageName)) {                    // Don't add this if it is a platform component that is marked                    // to run in multiple processes, because this is actually                    // part of the framework so doesn't make sense to track as a                    // separate apk in the process.                    app.addPackage(r.info.packageName, r.info.applicationInfo.longVersionCode,                            mService.mProcessStats);                }                realStartActivityLocked(r, app, andResume, checkConfig);                return;            } catch (RemoteException e) {                Slog.w(TAG, "Exception when starting activity "                        + r.intent.getComponent().flattenToShortString(), e);            }            // If a dead object exception was thrown -- fall through to            // restart the application.        }        mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,                "activity", r.intent.getComponent(), false, false, true);    }

这个方法里会判断app进程是否启动,没有启动的话会启动一个进程,启动了的话会调用realStartActivityLocked,这里就不分析启动新进程的流程了,直接看realStartActivityLocked方法

 final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,            boolean andResume, boolean checkConfig) throws RemoteException {       ..                // Create activity launch transaction.                final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread,                        r.appToken);                clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),                        System.identityHashCode(r), r.info,                        // TODO: Have this take the merged configuration instead of separate global                        // and override configs.                        mergedConfiguration.getGlobalConfiguration(),                        mergedConfiguration.getOverrideConfiguration(), r.compat,                        r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,                        r.persistentState, results, newIntents, mService.isNextTransitionForward(),                        profilerInfo));                // Set desired final state.                final ActivityLifecycleItem lifecycleItem;                if (andResume) {                    lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward());                } else {                    lifecycleItem = PauseActivityItem.obtain();                }                clientTransaction.setLifecycleStateRequest(lifecycleItem);                // Schedule transaction.                mService.getLifecycleManager().scheduleTransaction(clientTransaction);   ...   

方法里代码有点长,重点看一下我这里显示出来的这部分,这里首先会创建一个ClientTransaction,
并且调用其addCallback方法添加一个LaunchActivityItem然后通过ActivityManagerService. getLifecycleManager. scheduleTransaction去开启一个事务,这个方法实际上是调用ClientTransaction.schedule方法

//ClientTransaction  public void schedule() throws RemoteException {        mClient.scheduleTransaction(this);    }

方法里的mClient是IApplicationThread,那就可以知道实际上是调用ApplicationThread的scheduleTransaction方法

//ActivityThread$ApplicationThread @Override        public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {            ActivityThread.this.scheduleTransaction(transaction);        }

方法里调用了ActivityThread的scheduleTransaction,但是可以发现ActivityThread没有此方法,那就应该是在其父类里,进入其父类ClientTransactionHandler中发现了scheduleTransaction方法

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

这个方法里调用了ActivityThread.H发送了一个消息,并把ClientTransaction设置成obj传过去,回到ActivityThread中查看接收到消息之后的操作

 case EXECUTE_TRANSACTION:                    final ClientTransaction transaction = (ClientTransaction) msg.obj;                    mTransactionExecutor.execute(transaction);                    if (isSystem()) {                        // Client transactions inside system process are recycled on the client side                        // instead of ClientLifecycleManager to avoid being cleared before this                        // message is handled.                        transaction.recycle();                    }                    // TODO(lifecycler): Recycle locally scheduled transactions.                    break;

ActivityThread接收到消息之后调用TransactionExecutor. execute,首先看一下TransactionExecutor的初始化

private final TransactionExecutor mTransactionExecutor = new TransactionExecutor(this);

初始化时会传一个ClientTransactionHandler,这里传的是ActivityThread。继续看TransactionExecutor. execute

 public void execute(ClientTransaction transaction) {        final IBinder token = transaction.getActivityToken();        log("Start resolving transaction for client: " + mTransactionHandler + ", token: " + token);        executeCallbacks(transaction);        executeLifecycleState(transaction);        mPendingActions.clear();        log("End resolving transaction");    }

可以看到有调用一个executeCallbacks方法,前面说到会realStartActivityLocked方法里会创建一个ClientTransaction,并且调用其addCallback方法添加一个LaunchActivityItem。进入executeCallbacks

 public void executeCallbacks(ClientTransaction transaction) {        final List callbacks = transaction.getCallbacks();        if (callbacks == null) {            // No callbacks to execute, return early.            return;        }        log("Resolving callbacks");        final IBinder token = transaction.getActivityToken();        ActivityClientRecord r = mTransactionHandler.getActivityClient(token);        // In case when post-execution state of the last callback matches the final state requested        // for the activity in this transaction, we won't do the last transition here and do it when        // moving to final state instead (because it may contain additional parameters from server).        final ActivityLifecycleItem finalStateRequest = transaction.getLifecycleStateRequest();        final int finalState = finalStateRequest != null ? finalStateRequest.getTargetState()                : UNDEFINED;        // Index of the last callback that requests some post-execution state.        final int lastCallbackRequestingState = lastCallbackRequestingState(transaction);        final int size = callbacks.size();        for (int i = 0; i < size; ++i) {            final ClientTransactionItem item = callbacks.get(i);            log("Resolving callback: " + item);            final int postExecutionState = item.getPostExecutionState();            final int closestPreExecutionState = mHelper.getClosestPreExecutionState(r,                    item.getPostExecutionState());            if (closestPreExecutionState != UNDEFINED) {                cycleToPath(r, closestPreExecutionState);            }            item.execute(mTransactionHandler, token, mPendingActions);            item.postExecute(mTransactionHandler, token, mPendingActions);            if (r == null) {                // Launch activity request will create an activity record.                r = mTransactionHandler.getActivityClient(token);            }            if (postExecutionState != UNDEFINED && r != null) {                // Skip the very last transition and perform it by explicit state request instead.                final boolean shouldExcludeLastTransition =                        i == lastCallbackRequestingState && finalState == postExecutionState;                cycleToPath(r, postExecutionState, shouldExcludeLastTransition);            }        }    }

方法里会循环获取添加的的callback,并且调用callback的execute,postExecute等方法。那我们进入LaunchActivityItem的execute方法中查看一下

  @Override    public void execute(ClientTransactionHandler client, IBinder token,            PendingTransactionActions pendingActions) {        Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityStart");        ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,                mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,                mPendingResults, mPendingNewIntents, mIsForward,                mProfilerInfo, client);        client.handleLaunchActivity(r, pendingActions, null /* customIntent */);        Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);    }

发现了熟悉的handleLaunchActivity,这里的client就是上面说的TransactionExecutor初始化时传的ActivityThread。进入ActivityThread.handleLaunchActivity中

 public Activity handleLaunchActivity(ActivityClientRecord r,            PendingTransactionActions pendingActions, Intent customIntent) {        // If we are getting ready to gc after going to the background, well        // we are back active so skip it.        unscheduleGcIdler();        mSomeActivitiesChanged = true;        if (r.profilerInfo != null) {            mProfiler.setProfiler(r.profilerInfo);            mProfiler.startProfiling();        }        // Make sure we are running with the most recent config.        handleConfigurationChanged(null, null);        if (localLOGV) Slog.v(            TAG, "Handling launch of " + r);        // Initialize before creating the activity        if (!ThreadedRenderer.sRendererDisabled) {            GraphicsEnvironment.earlyInitEGL();        }        WindowManagerGlobal.initialize();        final Activity a = performLaunchActivity(r, customIntent);        if (a != null) {            r.createdConfig = new Configuration(mConfiguration);            reportSizeConfigurations(r);            if (!r.activity.mFinished && pendingActions != null) {                pendingActions.setOldState(r.state);                pendingActions.setRestoreInstanceState(true);                pendingActions.setCallOnPostCreate(true);            }        } else {            // If there was an error, for any reason, tell the activity manager to stop us.            try {                ActivityManager.getService()                        .finishActivity(r.token, Activity.RESULT_CANCELED, null,                                Activity.DONT_FINISH_TASK_WITH_ACTIVITY);            } catch (RemoteException ex) {                throw ex.rethrowFromSystemServer();            }        }        return a;    }

方法里调用了performLaunchActivity创建一个activity

 private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {        ActivityInfo aInfo = r.activityInfo;        if (r.packageInfo == null) {            r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,                    Context.CONTEXT_INCLUDE_CODE);        }        ComponentName component = r.intent.getComponent();        if (component == null) {            component = r.intent.resolveActivity(                mInitialApplication.getPackageManager());            r.intent.setComponent(component);        }        if (r.activityInfo.targetActivity != null) {            component = new ComponentName(r.activityInfo.packageName,                    r.activityInfo.targetActivity);        }        ContextImpl appContext = createBaseContextForActivity(r);        Activity activity = null;        try {            java.lang.ClassLoader cl = appContext.getClassLoader();            activity = mInstrumentation.newActivity(                    cl, component.getClassName(), r.intent);            StrictMode.incrementExpectedActivityCount(activity.getClass());            r.intent.setExtrasClassLoader(cl);            r.intent.prepareToEnterProcess();            if (r.state != null) {                r.state.setClassLoader(cl);            }        } catch (Exception e) {            if (!mInstrumentation.onException(activity, e)) {                throw new RuntimeException(                    "Unable to instantiate activity " + component                    + ": " + e.toString(), e);            }        }        try {            Application app = r.packageInfo.makeApplication(false, mInstrumentation);            if (localLOGV) Slog.v(TAG, "Performing launch of " + r);            if (localLOGV) Slog.v(                    TAG, r + ": app=" + app                    + ", appName=" + app.getPackageName()                    + ", pkg=" + r.packageInfo.getPackageName()                    + ", comp=" + r.intent.getComponent().toShortString()                    + ", dir=" + r.packageInfo.getAppDir());            if (activity != null) {                CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());                Configuration config = new Configuration(mCompatConfiguration);                if (r.overrideConfig != null) {                    config.updateFrom(r.overrideConfig);                }                if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "                        + r.activityInfo.name + " with config " + config);                Window window = null;                if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {                    window = r.mPendingRemoveWindow;                    r.mPendingRemoveWindow = null;                    r.mPendingRemoveWindowManager = null;                }                appContext.setOuterContext(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);                if (customIntent != null) {                    activity.mIntent = customIntent;                }                r.lastNonConfigurationInstances = null;                checkAndBlockForNetworkAccess();                activity.mStartedActivity = false;                int theme = r.activityInfo.getThemeResource();                if (theme != 0) {                    activity.setTheme(theme);                }                activity.mCalled = false;                if (r.isPersistable()) {                    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);                } else {                    mInstrumentation.callActivityOnCreate(activity, r.state);                }                if (!activity.mCalled) {                    throw new SuperNotCalledException(                        "Activity " + r.intent.getComponent().toShortString() +                        " did not call through to super.onCreate()");                }                r.activity = activity;            }            r.setState(ON_CREATE);            mActivities.put(r.token, r);        } catch (SuperNotCalledException e) {            throw e;        } catch (Exception e) {            if (!mInstrumentation.onException(activity, e)) {                throw new RuntimeException(                    "Unable to start activity " + component                    + ": " + e.toString(), e);            }        }        return activity;    }

这个方法做的操作比较多,比如给activity设置context,判断application是否已经创建。activity创建完毕之后调用activity.attach。attach方法中会给activity设置关联window,设置context等。调用完attach之后会调用callActivityOnCreate

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

这个方法里调用activity的performCreate

 final void performCreate(Bundle icicle) {        performCreate(icicle, null);    }    final void performCreate(Bundle icicle, PersistableBundle persistentState) {        mCanEnterPictureInPicture = true;        restoreHasCurrentPermissionRequest(icicle);        if (persistentState != null) {            onCreate(icicle, persistentState);        } else {            onCreate(icicle);        }        writeEventLog(LOG_AM_ON_CREATE_CALLED, "performCreate");        mActivityTransitionState.readState(icicle);        mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(                com.android.internal.R.styleable.Window_windowNoDisplay, false);        mFragments.dispatchActivityCreated();        mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());    }

到这里终于发现了熟悉的oncreate方法了

更多相关文章

  1. Android资源加载机制
  2. ActivityThread-activity启动分析
  3. android 铃声设置流程讲解
  4. Android(安卓)GUI更新过程
  5. Android(安卓)GCM使用
  6. android通过usb读取U盘的方法
  7. Android手机亮屏流程分析
  8. Android(安卓)Studio 解析XML的三种方法
  9. Android(安卓)Intent FLAG介绍

随机推荐

  1. Android 头像上传
  2. 最强 Android(安卓)Studio 使用小技巧和
  3. Android(安卓)5.0为了安全而“关门”
  4. 跨进程调用Service(AIDL服务)
  5. Android开发请求网络方式详解
  6. android学习——Android的系统架构简介
  7. Android中图片占用内存的计算
  8. Android本地视频播放器开发--ffmpeg解码
  9. Android(安卓)startActivity源码详解
  10. android中MVP的理解和实例