一、ActivityThreadattach函数

在创立使用进程最终一步,会调用ActivityThreadmain函数,调起当时使用进程的主线程。除了开始消息循环机制外,会调用ActivityThreadattach函数。

public static void main(String[] args) {
    ...
    ActivityThread thread = new ActivityThread();
    thread.attach(false, startSeq);
    ...
}

attach函数,首要经过Binder机制取得ActivityManger在当时进程的引证mgr,并调用其attachApplication函数,将当时的Applciation目标mAppThread作为参数,startSeq为当时进程的唯一标识序号传递给了attachApplication函数。

private void attach(boolean system, long startSeq) {
    sCurrentActivityThread = this;
    mSystemThread = system;
    if (!system) {
        ...
        final IActivityManager mgr = ActivityManager.getService();
        try {
            mgr.attachApplication(mAppThread, startSeq);
        } catch (RemoteException ex) {
            throw ex.rethrowFromSystemServer();
        }
        ...
    } else {
        ...
    }
 }

定位ActivityManagerattachApplication函数。

public final void attachApplication(IApplicationThread thread, long startSeq) {
    if (thread == null) {
        throw new SecurityException("Invalid application interface");
    }
    synchronized (this) {
        int callingPid = Binder.getCallingPid();
        final int callingUid = Binder.getCallingUid();
        final long origId = Binder.clearCallingIdentity();
        attachApplicationLocked(thread, callingPid, callingUid, startSeq);
        Binder.restoreCallingIdentity(origId);
    }
}

attachApplicationLocked函数中咱们只关心调用了app.makeActive(thread, mProcessStats);这儿的appProcessRecord目标,在创立使用进程时,在ProcessList被创立并保存在AMSmPidsSelfLocked中。在attachApplicationLocked函数中,首要经过pidmPidsSelfLocked获取ProcessRecord目标,并调用其bindApplication函数和makeActivie函数。

ApplicationThread#bindApplication

Application会涉及到使用Application和上下文的创立。

ProcessRecord#makeActive
public void makeActive(IApplicationThread _thread, ProcessStatsService tracker) {
    if (thread == null) {
    thread = _thread;
    mWindowProcessController.setThread(thread);
}

这儿咱们只关心将进程ApplicationThread在AMS的使用设置给了mWindowProcessController目标的mThread变量,这个在接下来的剖析,是判别创立进程或发动Activity的重要分支点。一起,SystemServer进程经过当时进程的ApplicationThreadBinder引证来与该进程进行通信。

二、根Activity的创立

1、 startActivity

一般,咱们经过startActivity函数来发动一个Activity,此刻这个Activity可能是咱们自己使用程序的,也可能是其他使用程序的。此刻咱们假设其他使用程序,且该使用进程未发动。

public void startActivity(Intent intent) {
    this.startActivity(intent, null);
}
//重载函数
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) {
    startActivityForResult(intent, requestCode, null);
}

2、startActivityForResult

也便是所有发动ActivitystartActivity函数和startActivityForResult函数终究都会走到重载的startActivityForResult函数。


  public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,@Nullable Bundle options) {
  	//使用程序初次创立Activity,此刻是不存在父类Activity的
    if (mParent == null) {
        options = transferSpringboardActivityOptions(options);
        Instrumentation.ActivityResult ar =
            mInstrumentation.execStartActivity(
                this, mMainThread.getApplicationThread(), mToken, this,
                intent, requestCode, options);
		...
    } else {
        if (options != null) {
            mParent.startActivityFromChild(this, intent, requestCode, options);
        } else {
            mParent.startActivityFromChild(this, intent, requestCode);
        }
    }
}

3、Instrumentation.execStartActivity

Instrumentation是用来监督使用进程和系统交互的,这儿调用其execStartActivity,该函数内部调用了ActivityTaskManager.getService().startActivity函数。ActivityTaskManager.getService()会经过AIDL机制取得ActivityTaskMangerService在使用进程的引证,调用其startActivity函数,意味调用了SystemServer进程的ATMSstartActivity函数。

public ActivityResult execStartActivity(
        Context who, IBinder contextThread, IBinder token, Activity target,
        Intent intent, int requestCode, Bundle options) {
    IApplicationThread whoThread = (IApplicationThread) contextThread;
	...
    try {
        ...
        int result = ActivityTaskManager.getService().startActivity(whoThread,
                who.getBasePackageName(), who.getAttributionTag(), intent,
                intent.resolveTypeIfNeeded(who.getContentResolver()), token,
                target != null ? target.mEmbeddedID : null, requestCode, 0, null, options);
       	...
    } catch (RemoteException e) {
        throw new RuntimeException("Failure from system", e);
    }
    return null;
}

4、ATMS.startActivity

ATMSstartActivity函数startActivityAsUser,多获取了一个UserId,用于判别调用者的权限。

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

startActivityAsUser函数首要检测是否包名和UserId共同,是否阻隔进程等安全权限问题。然后经过getActivityStartController().obtainStarter函数获取ActivityStarter,并经过Builder规划形式,规划相关特点,最终履行其excute函数。


public int startActivityAsUser(IApplicationThread caller, String callingPackage,
        String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
        String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
        Bundle bOptions, int userId) {
    //调用重载函数,validateIncomingUser 为true,会依据调用id和targetId,解析出用户id
    return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
            resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
            true /*validateIncomingUser*/);
}
//调用重载函数
private int startActivityAsUser(IApplicationThread caller, String callingPackage,
        @Nullable String callingFeatureId, Intent intent, String resolvedType,
        IBinder resultTo, String resultWho, int requestCode, int startFlags,
        ProfilerInfo profilerInfo, Bundle bOptions, int userId, boolean validateIncomingUser) {
    //查看包名与CallingId是否共同
    assertPackageMatchesCallingUid(callingPackage);
    //检测是否检测阻隔
    enforceNotIsolatedCaller("startActivityAsUser");
    //解析初用户ID
    userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
            Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
    //获取ActivityStarter,设置参数,履行其exexute函数。
    return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
            .setCaller(caller)
            .setCallingPackage(callingPackage)
            .setCallingFeatureId(callingFeatureId)
            .setResolvedType(resolvedType)
            .setResultTo(resultTo)
            .setResultWho(resultWho)
            .setRequestCode(requestCode)
            .setStartFlags(startFlags)
            .setProfilerInfo(profilerInfo)
            .setActivityOptions(bOptions)
            .setUserId(userId)
            .execute();
}

5、ActivityStarter.execute

execute=>executeRequest

executeexecuteRequest函数,首要进行初步的查看和具有必要的权限,并把发动新的Activity的相关信息封装到ActivityRecord中,也便是说ActivityRecord描述着一个Activity。然后调用startActivityUnchecked函数。

private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            int startFlags, boolean doResume, ActivityOptions options, Task inTask,
            boolean restrictedBgActivity, NeededUriGrants intentGrants) {
    int result = START_CANCELED;
    final ActivityStack startedActivityStack;
    try {
        mService.deferWindowLayout();
        result = startActivityInner(r, sourceRecord, voiceSession, voiceInteractor,
                startFlags, doResume, options, inTask, restrictedBgActivity, intentGrants);
    } finally {
        startedActivityStack = handleStartResult(r, result);
        mService.continueWindowLayout();
    }
    postStartActivityProcessing(r, result, startedActivityStack);
    return result;
}

依据startActivityUnchecked的注释,该函数是为了确保创立Activity反常时,该Activity能被移除。仅紧着调用startActivityInner函数。

startActivityInner函数首要设置和寻觅当时Activity适宜的栈,以及显现问题。

int startActivityInner(final ActivityRecord r, ActivityRecord sourceRecord,
        IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
        int startFlags, boolean doResume, ActivityOptions options, Task inTask,
        boolean restrictedBgActivity, NeededUriGrants intentGrants) {
    setInitialState(r, options, inTask, doResume, startFlags, sourceRecord, voiceSession,
            voiceInteractor, restrictedBgActivity);
	//对Activity发动形式的判别和设置
    computeLaunchingTaskFlags();
    computeSourceStack();
    mIntent.setFlags(mLaunchFlags);
    final Task reusedTask = getReusableTask();
    // If requested, freeze the task list
    if (mOptions != null && mOptions.freezeRecentTasksReordering()
            && mSupervisor.mRecentTasks.isCallerRecents(r.launchedFromUid)
            && !mSupervisor.mRecentTasks.isFreezeTaskListReorderingSet()) {
        mFrozeTaskList = true;
        mSupervisor.mRecentTasks.setFreezeTaskListReordering();
    }
    // Compute if there is an existing task that should be used for.
    final Task targetTask = reusedTask != null ? reusedTask : computeTargetTask();
    final boolean newTask = targetTask == null;
    mTargetTask = targetTask;
    computeLaunchParams(r, sourceRecord, targetTask);
    // Check if starting activity on given task or on a new task is allowed.
    int startResult = isAllowedToStart(r, newTask, targetTask);
    if (startResult != START_SUCCESS) {
        return startResult;
    }
    final ActivityRecord targetTaskTop = newTask
            ? null : targetTask.getTopNonFinishingActivity();
    if (targetTaskTop != null) {
        // Recycle the target task for this launch.
        startResult = recycleTask(targetTask, targetTaskTop, reusedTask, intentGrants);
        if (startResult != START_SUCCESS) {
            return startResult;
        }
    } else {
        mAddingToTask = true;
    }
	...
    if (mTargetStack == null) {
        mTargetStack = getLaunchStack(mStartActivity, mLaunchFlags, targetTask, mOptions);
    }
    if (newTask) {
        final Task taskToAffiliate = (mLaunchTaskBehind && mSourceRecord != null)
                ? mSourceRecord.getTask() : null;
        setNewTask(taskToAffiliate);
        if (mService.getLockTaskController().isLockTaskModeViolation(
                mStartActivity.getTask())) {
            Slog.e(TAG, "Attempted Lock Task Mode violation mStartActivity=" + mStartActivity);
            return START_RETURN_LOCK_TASK_MODE_VIOLATION;
        }
    } else if (mAddingToTask) {
        addOrReparentStartingActivity(targetTask, "adding to task");
    }
	...
    mTargetStack.mLastPausedActivity = null;
    mRootWindowContainer.sendPowerHintForLaunchStartIfNeeded(
            false /* forceSend */, mStartActivity);
    mTargetStack.startActivityLocked(mStartActivity, topStack.getTopNonFinishingActivity(),
            newTask, mKeepCurTransition, mOptions);
    if (mDoResume) {
        final ActivityRecord topTaskActivity =
                mStartActivity.getTask().topRunningActivityLocked();
        if (!mTargetStack.isTopActivityFocusable()
                || (topTaskActivity != null && topTaskActivity.isTaskOverlay()
                && mStartActivity != topTaskActivity)) {
            mTargetStack.ensureActivitiesVisible(null /* starting */,
                    0 /* configChanges */, !PRESERVE_WINDOWS);
            mTargetStack.getDisplay().mDisplayContent.executeAppTransition();
        } else {
            if (mTargetStack.isTopActivityFocusable()
                    && !mRootWindowContainer.isTopDisplayFocusedStack(mTargetStack)) {
                mTargetStack.moveToFront("startActivityInner");
            }
            mRootWindowContainer.resumeFocusedStacksTopActivities(
                    mTargetStack, mStartActivity, mOptions);
        }
    }
    mRootWindowContainer.updateUserStack(mStartActivity.mUserId, mTargetStack);
    mSupervisor.mRecentTasks.add(mStartActivity.getTask());
    mSupervisor.handleNonResizableTaskIfNeeded(mStartActivity.getTask(),
            mPreferredWindowingMode, mPreferredTaskDisplayArea, mTargetStack);
    return START_SUCCESS;
}

6、RootWindowContainer.resumeFocusedStacksTopActivities

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

7、ActivityStack.resumeTopActivityUncheckedLocked

该函数内部又调用了resumeTopActivityInnerLocked函数。对栈顶Activity的状态进行查看。依据不同的状态做不通的处理。

private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
    ...
    mStackSupervisor.startSpecificActivity(next, true, true);
    ...
    return true;
}

8、ActivityStackSupervisor.startSpecificActivity

依据第一节创立使用进程之后,调用ActivityThreadattach函数结果来看,startSpecificActivity函数中的wpc != null && wpc.hasThread()成立,走的将是realStartActivityLocked的分支来发动Activity。不然便是走创立y使用进程的流程。

    void startSpecificActivity(ActivityRecord r, boolean andResume, boolean checkConfig) {
        final WindowProcessController wpc =
                mService.getProcessController(r.processName, r.info.applicationInfo.uid);
        boolean knownToBeDead = false;
        if (wpc != null && wpc.hasThread()) {
            try {
                realStartActivityLocked(r, wpc, andResume, checkConfig);
                return;
            } catch (RemoteException e) {
                Slog.w(TAG, "Exception when starting activity "
                        + r.intent.getComponent().flattenToShortString(), e);
            }
            knownToBeDead = true;
        }
        r.notifyUnknownVisibilityLaunchedForKeyguardTransition();
        final boolean isTop = andResume && r.isTopRunningActivity();
        mService.startProcessAsync(r, knownToBeDead, isTop, isTop ? "top-activity" : "activity");
    }

9、ActivityStackSupervisor.realStartActivityLocked

realStartActivityLocked函数在剖析一,创立了ClientTransaction目标,并传递了使用进程的ApplicationThread引证,该引证会赋值ClientTransactionmClient变量。

剖析二、给ClientTransaction添加了Callback回调。参数是LaunchActivityItem目标,封装了许多信息,添加到了ClientTransactionmActivityCallbacks列表。LaunchActivityItem承继ClientTransactionItem,具有excute函数。

剖析三、调用ATMSClientLifecycleManager目标履行该ClientTransaction目标。

boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
    boolean andResume, boolean checkConfig) throws RemoteException {
        ...
        //剖析一
        final ClientTransaction clientTransaction = ClientTransaction.obtain(
                proc.getThread(), r.appToken);
        final DisplayContent dc = r.getDisplay().mDisplayContent;
        //剖析二
        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.getSavedState(), r.getPersistentSavedState(), results, newIntents,
                dc.isNextTransitionForward(), proc.createProfilerInfoIfNeeded(),
                r.assistToken, r.createFixedRotationAdjustmentsIfNeeded()));
        ...
        // 剖析3
        mService.getLifecycleManager().scheduleTransaction(clientTransaction);
        ...
return true;
}

10、ClientLifecycleManager.scheduleTransaction

void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
    ...
    transaction.schedule();
    ...
}

11、ClientTransaction.schedule

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

依据第9步的剖析,mClient是使用进程的ApplicationThreadSystemServer进程的使用,这儿经过IPC调用了使用进程的ApplicationThradscheduleTransaction函数。

12、ApplicationThread.scheduleTransaction

ApplicationThreadActivityThread的内部类,是ATMS经过AIDL调用使用进程的相关功能的完成类。

public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
    ActivityThread.this.scheduleTransaction(transaction);
}

13、ActivityThread.scheduleTransaction

ActivityThreadscheduleTransaction函数定义在它的父类继ClientTransactionHandler

14、ClientTransactionHandler.scheduleTransaction

Handler目标H,发送了EXECUTE_TRANSACTION状态码。

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

15、ActivityThread.mH.EXECUTE_TRANSACTION

调用业务履行器履行了一路从ATMS传递过来的ClientTransaction目标。

case EXECUTE_TRANSACTION:
    final ClientTransaction transaction = (ClientTransaction) msg.obj;
    mTransactionExecutor.execute(transaction);
    if (isSystem()) {
        transaction.recycle();
    }

16、TransactionExecutor.execute

public void execute(ClientTransaction transaction) {
	...
    executeCallbacks(transaction);
	...
}

17、TransactionExecutor.executeCallbacks

经过遍历ClientTransaction目标的mActivityCallbacks列表,并调用每个元素ClientTransactionItemexecute函数。在第9步的时候,给mActivityCallbacks添加了LaunchActivityItem实例。

    public void executeCallbacks(ClientTransaction transaction) {
        final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
    	...
        final IBinder token = transaction.getActivityToken();
        ActivityClientRecord r = mTransactionHandler.getActivityClient(token);
		...
        final int size = callbacks.size();
        for (int i = 0; i < size; ++i) {
            final ClientTransactionItem item = callbacks.get(i);
            item.execute(mTransactionHandler, token, mPendingActions);
            item.postExecute(mTransactionHandler, token, mPendingActions);
            ...
        }
    }

18、LaunchActivityItem.execute

创立了ActivityClientRecord目标,描述要创立的Activity的特点。并调用ActivityThreadhandleLaunchActivity函数。

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, mFixedRotationAdjustments);
    client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
}

19、ActivityThread.handleLaunchActivity

  public Activity handleLaunchActivity(ActivityClientRecord r,
            PendingTransactionActions pendingActions, Intent customIntent) {
		...
        final Activity a = performLaunchActivity(r, customIntent);
        ...
        return a;
    }

20、ActivityThread.performLaunchActivity

函数经过 mInstrumentation.newActivity函数反射创立了Activity,并经过mInstrumentation.callActivityOnCreate调用ActivityonCreate函数。

这儿创立了许多要害目标,例如Activity的上下文,Application目标和上下文。以及绑定联系。

  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);
        }
		//Activity的上下文
        ContextImpl appContext = createBaseContextForActivity(r);
        Activity activity = null;
        try {
        	//经过反射办法方法创立Activity
            java.lang.ClassLoader cl = appContext.getClassLoader();
            activity = mInstrumentation.newActivity(
                    cl, component.getClassName(), r.intent);
           	...
        } catch (Exception e) {
        	...
        }
        try {
        	//Application及上下文的创立
            Application app = r.packageInfo.makeApplication(false, mInstrumentation);
            if (activity != null) {
                ...
				//Activity与上下文彼此绑定
                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,
                        r.assistToken);
				...
                if (r.isPersistable()) {
                    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
                } else {
                    mInstrumentation.callActivityOnCreate(activity, r.state);
                }
                ...
                r.activity = activity;
                mLastReportedWindowingMode.put(activity.getActivityToken(),
                        config.windowConfiguration.getWindowingMode());
            }
            ...
        } catch (SuperNotCalledException e) {
            ...
        }
        return activity;
    }

21、Instrumentation.callActivityOnCreate

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

22、Activity.performCreate

final void performCreate(Bundle icicle, PersistableBundle persistentState) {
    dispatchActivityPreCreated(icicle);
    mCanEnterPictureInPicture = true;
    // initialize mIsInMultiWindowMode and mIsInPictureInPictureMode before onCreate
    final int windowingMode = getResources().getConfiguration().windowConfiguration
            .getWindowingMode();
    mIsInMultiWindowMode = inMultiWindowMode(windowingMode);
    mIsInPictureInPictureMode = windowingMode == WINDOWING_MODE_PINNED;
    restoreHasCurrentPermissionRequest(icicle);
    if (persistentState != null) {
        onCreate(icicle, persistentState);
    } else {
        onCreate(icicle);
    }
    EventLogTags.writeWmOnCreateCalled(mIdent, getComponentName().getClassName(),
            "performCreate");
    mActivityTransitionState.readState(icicle);
    mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
            com.android.internal.R.styleable.Window_windowNoDisplay, false);
    mFragments.dispatchActivityCreated();
    mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
    dispatchActivityPostCreated(icicle);
}

至此,ActivityonCreate函数现已被调用。到了Activity的生命周期第一步。

三、总结

流程看是看懂了,也关联到平常经常开发的知识点,将平常零星的知识点串联起来。例如ActivityContext创立时机,它两的彼此绑定。为啥Activity的创立要经过ClientTransaction最终回调到Handler或者Executor进行创立Activity实例。切到AMS中去走Activity的发动流程,是为了完成一些权限查看、资源管控、业务需求(例如使命栈的切换)、资源和数据的加载。而切换到使用的主线程来创立Activity,是为了与使用进程的生命周期、资源绑定、Activity的归属。但我总感觉少了点什么?看来还是得持续努力。