Android系统揭秘(一)-Activity启动流程(下)

·  阅读 2105

阅读前请先阅读上篇 Android系统揭秘(一)-Activity启动流程(上)

Android 10

请求ATMS

Android 10开发不再是直接请求AMS,而是请求ActivityTaskManagerService。流程与请求AMS相似

img

前面与Android 8一样,也是先走 Activity.startActivity() -> Activity.startActivityForResult() -> Instrumentation.execStartActivity 的流程

只是execStartActivity里面不是不是通过ActivityManager而是ActivityTaskManager获取Service frameworks/base/core/java/android/app/Instrumentation.java

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);
            checkStartActivityResult(result, intent);
        } catch (RemoteException e) {
            throw new RuntimeException("Failure from system", e);
        }
        return null;
    }

复制代码

当然获取到的也不是IActivityManager 而是 IActivityTaskManager

frameworks/base/core/java/android/app/ActivityTaskManager.java

@SystemService(Context.ACTIVITY_TASK_SERVICE)
public class ActivityTaskManager {
     public static IActivityTaskManager getService() {
         return IActivityTaskManagerSingleton.get();
     }
 
     @UnsupportedAppUsage(trackingBug = 129726065)
     private static final Singleton<IActivityTaskManager> IActivityTaskManagerSingleton =
             new Singleton<IActivityTaskManager>() {
                 @Override
                 protected IActivityTaskManager create() {
                     final IBinder b = ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE);
                     return IActivityTaskManager.Stub.asInterface(b);
                 }
             };

}
复制代码

我们看到AMS绑定的AIDL接口仍然是IActivityManager

frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

public class ActivityManagerService extends IActivityManager.Stub
        implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
复制代码

搜索代码找到ActivityTaskManagerService绑定了IActivityTaskManager,应该是AMS把部分工作分配出去了。
frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java

/**
 * System service for managing activities and their containers (task, stacks, displays,... ).
 *
 * {@hide}
 */
public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
复制代码

ATMS发送指令到ActivityThread

img

我们继续看下ActivityTaskManagerService的startActivity方法

frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java

    @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());
    }
复制代码

它调用了startActivityAsUser方法

 @Override
    public 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, callingFeatureId, intent, resolvedType,
                resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
                true /*validateIncomingUser*/);
    }

    private 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) {
        assertPackageMatchesCallingUid(callingPackage);
        enforceNotIsolatedCaller("startActivityAsUser");

        userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
                Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");

        // TODO: Switch to user app stacks here.
        return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
                .setCaller(caller)
                .setCallingPackage(callingPackage)
                .setResolvedType(resolvedType)
                .setResultTo(resultTo)
                .setResultWho(resultWho)
                .setRequestCode(requestCode)
                .setStartFlags(startFlags)
                .setProfilerInfo(profilerInfo)
                .setActivityOptions(bOptions)
                .setUserId(userId)
                .execute();

    }
复制代码

getActivityStartController()返回的是一个ActivityStarterController对象

frameworks/base/services/core/java/com/android/server/wm/ActivityStartController.java

    ActivityStarter obtainStarter(Intent intent, String reason) {
        return mFactory.obtain().setIntent(intent).setReason(reason);
    }
复制代码

而obtainStarter最终返回ActivityStarter

frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java

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.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);
        } 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,
                    mRequest.originatingPendingIntent, mRequest.allowBackgroundActivityStart);
        }
    } finally {
        onExecutionComplete();
    }
}
复制代码

这里有两种启动方法,我们选择其中一种接着看下去


    private int startActivityMayWait(IApplicationThread caller, int callingUid,
            String callingPackage, int requestRealCallingPid, int requestRealCallingUid,
            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,
            PendingIntentRecord originatingPendingIntent, boolean allowBackgroundActivityStart) {
            ...
            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);
            ...
}

复制代码

startActivityMayWait是安全启动,最终还是调用startActivity方法

    private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,

            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,
            PendingIntentRecord originatingPendingIntent, boolean allowBackgroundActivityStart) {
        .....
        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);
    }

复制代码
private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
                IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
                int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
                ActivityRecord[] outActivity, boolean restrictedBgActivity) {
        ...
        try {
        ...
            result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
                    startFlags, doResume, options, inTask, outActivity, restrictedBgActivity);
        } 
        ...
}
复制代码

看下startActivityUnchecked方法


    private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
            ActivityRecord[] outActivity, boolean restrictedBgActivity) {
        ...
        mTargetStack.startActivityLocked(mStartActivity, topFocused, newTask, mKeepCurTransition,
                mOptions);
        if (mDoResume) {
            final ActivityRecord topTaskActivity =
                    mStartActivity.getTaskRecord().topRunningActivityLocked();
            ...
                mRootActivityContainer.resumeFocusedStacksTopActivities(
                        mTargetStack, mStartActivity, mOptions);
            }
        } 
        ...

        return START_SUCCESS;
    }
复制代码

这里调用了RootActivityContainer的resumeFocusedStacksTopActivities方法

frameworks/base/services/core/java/com/android/server/wm/RootActivityContainer.java


    boolean resumeFocusedStacksTopActivities() {
        return resumeFocusedStacksTopActivities(null, null, null);
    }
    boolean resumeFocusedStacksTopActivities(
            ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {

        ...

        for (int displayNdx = getChildCount() - 1; displayNdx >= 0; --displayNdx) {
            ...
            if (!resumedOnDisplay) {
               
                final ActivityStack focusedStack = display.getFocusedStack();
                if (focusedStack != null) {
                    focusedStack.resumeTopActivityUncheckedLocked(target, targetOptions);
                }
            }
        }

        return result;
    }

复制代码

接下来又走到了ActivityStack

frameworks/base/services/core/java/com/android/server/wm/ActivityStack.java

   boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
         ...
                result = resumeTopActivityInnerLocked(prev, options);
         ....
      
    }
    
   private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
            ....
    
            
            mStackSupervisor.startSpecificActivityLocked(next, true, false);
            ...
   }
复制代码

resumeTopActivityInnerLocked跳转到ActivityStackSupervisor进行下一步

frameworks/base/services/core/java/com/android/server/wm/ActivityStackSupervisor.java

   void startSpecificActivityLocked(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 {
                // 应用已启动则启动Activity
                   realStartActivityLocked(r, wpc, 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.
               knownToBeDead = true;
           }
   
           ...
           try {
               ...
               // 通知启动应用
               final Message msg = PooledLambda.obtainMessage(
                       ActivityManagerInternal::startProcess, mService.mAmInternal, r.processName,
                       r.info.applicationInfo, knownToBeDead, "activity", r.intent.getComponent());
               mService.mH.sendMessage(msg);
           } finally {
               Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
           }
       }
复制代码

这里会判断是否第一个Activity,若不是直接启动Activity,否则通知ATMS启动应用。这一节我们只分析直接启动Activity的情况

boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
            boolean andResume, boolean checkConfig) throws RemoteException {

          ...


                // Create activity launch transaction.
                final ClientTransaction clientTransaction = ClientTransaction.obtain(
                        proc.getThread(), r.appToken);

                final DisplayContent dc = r.getDisplay().mDisplayContent;
                // 这里的LaunchActivityItem要特别注意,后面会用到
                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, proc.getReportedProcState(),
                        r.icicle, r.persistentState, results, newIntents,
                        dc.isNextTransitionForward(), proc.createProfilerInfoIfNeeded(),
                                r.assistToken));

                // Set desired final state.
                final ActivityLifecycleItem lifecycleItem;
                if (andResume) {
                    lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward());
                } else {
                    lifecycleItem = PauseActivityItem.obtain();
                }
                clientTransaction.setLifecycleStateRequest(lifecycleItem);

                // 通过Lifecycle通知启动
                mService.getLifecycleManager().scheduleTransaction(clientTransaction);

              ...

        return true;
    }
复制代码

注意下这里的LaunchActivityItem,这个会作为lifecycleItem发给ActivityThread,后面又用到

frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java

ClientLifecycleManager getLifecycleManager() {
        return mLifecycleManager;
    }
复制代码

接下来通过Lifecycle通知启动Activity,其中mService为ActivityTaskManagerService,

ActivityThread启动新的Activity

img
如图所示,ClientLifecycleManager会调用IApplicationThread的scheduleTransaction方法 frameworks/base/services/core/java/com/android/server/wm/ClientLifecycleManager.java

void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
        final IApplicationThread client = transaction.getClient();
        transaction.schedule();
        if (!(client instanceof Binder)) {
            // If client is not an instance of Binder - it's a remote call and at this point it is
            // safe to recycle the object. All objects used for local calls will be recycled after
            // the transaction is executed on client in ActivityThread.
            transaction.recycle();
        }
    }
复制代码

frameworks/base/core/java/android/app/servertransaction/ClientTransaction.java


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

而IApplicationThread的scheduleTransaction方法调用了ActivityThread父类的scheduleTransaction方法
frameworks/base/core/java/android/app/ActivityThread.java

public final class ActivityThread extends ClientTransactionHandler {
    private class ApplicationThread extends IApplicationThread.Stub {
        @Override
        public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
            ActivityThread.this.scheduleTransaction(transaction);
        }
    }
}
复制代码

frameworks/base/core/java/android/app/ClientTransactionHandler.java

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

最终是向H发送包含EXECUTE_TRANSACTION和transaction的Message

   private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
        if (DEBUG_MESSAGES) {
            Slog.v(TAG,
                    "SCHEDULE " + what + " " + mH.codeToString(what) + ": " + arg1 + " / " + obj);
        }
        Message msg = Message.obtain();
        msg.what = what;
        msg.obj = obj;
        msg.arg1 = arg1;
        msg.arg2 = arg2;
        if (async) {
            msg.setAsynchronous(true);
        }
        mH.sendMessage(msg);
    }
复制代码
 class H extends Handler {
        ...
        public static final int EXECUTE_TRANSACTION = 159;
        ...
        public void handleMessage(Message msg) {
            if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
            switch (msg.what) {
                ...
                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;
                ...
            }
复制代码

H收到msg之后执行transaction

frameworks/base/core/java/android/app/servertransaction/TransactionExecutor.java

public void execute(ClientTransaction transaction) {
        if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "Start resolving transaction");

        final IBinder token = transaction.getActivityToken();
        if (token != null) {
            final Map<IBinder, ClientTransactionItem> activitiesToBeDestroyed =
                    mTransactionHandler.getActivitiesToBeDestroyed();
            final ClientTransactionItem destroyItem = activitiesToBeDestroyed.get(token);
            if (destroyItem != null) {
                if (transaction.getLifecycleStateRequest() == destroyItem) {
                    // It is going to execute the transaction that will destroy activity with the
                    // token, so the corresponding to-be-destroyed record can be removed.
                    activitiesToBeDestroyed.remove(token);
                }
                if (mTransactionHandler.getActivityClient(token) == null) {
                    // The activity has not been created but has been requested to destroy, so all
                    // transactions for the token are just like being cancelled.
                    Slog.w(TAG, tId(transaction) + "Skip pre-destroyed transaction:\n"
                            + transactionToString(transaction, mTransactionHandler));
                    return;
                }
            }
        }

        if (DEBUG_RESOLVER) Slog.d(TAG, transactionToString(transaction, mTransactionHandler));

        executeCallbacks(transaction);

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

这里我们关注executeLifecycleState方法

  /** Transition to the final state if requested by the transaction. */
    private void executeLifecycleState(ClientTransaction transaction) {
        final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
        if (lifecycleItem == null) {
            // No lifecycle request, return early.
            return;
        }

        final IBinder token = transaction.getActivityToken();
        final ActivityClientRecord r = mTransactionHandler.getActivityClient(token);
        if (DEBUG_RESOLVER) {
            Slog.d(TAG, tId(transaction) + "Resolving lifecycle state: "
                    + lifecycleItem + " for activity: "
                    + getShortActivityName(token, mTransactionHandler));
        }

        if (r == null) {
            // Ignore requests for non-existent client records for now.
            return;
        }

        // Cycle to the state right before the final requested state.
        cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */, transaction);

        // Execute the final transition with proper parameters.
        lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
        lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
    }
复制代码

这里的lifecycleItem 就是上节提到的LaunchActivityItem,我们看下它的实现

frameworks/base/core/java/android/app/servertransaction/LaunchActivityItem.java

  @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, mAssistToken);
        client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
        Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
    }
复制代码

client其实就是ActivityThread,接下来就是调用ActivityThread的handleLaunchActivity方法,后面的流程与Android基本一致,就不再赘述了

Android 11

Android 11与Android 10的过程变化不大,只带着时序图说下不同之处

请求ATMS

img

这一步基本一致,只是Android 11startActivity方法多了一个callingFeatureId参数,后续也会传给ActivityStarter

frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java

    @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());
    }
复制代码

ATMS发送指令到ActivityThread

img

重点看下时序图里面红色的部分:

  • ActivityStarter逻辑有些改动
  • RootActivityContainer改成了RootWindowContainer
  • ActivityStackSupervisor->startSpecificActivityLock改为startSpecificActivity

然后看下这部分的代码 frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java

int execute() {
        try {
            ...

            int res;
            synchronized (mService.mGlobalLock) {
                ...
                res = executeRequest(mRequest);

               ...
                mSupervisor.getActivityMetricsLogger().notifyActivityLaunched(launchingState, res,
                        mLastStartActivityRecord);
                return getExternalResult(mRequest.waitResult == null ? res
                        : waitForResult(res, mLastStartActivityRecord));
            }
        } finally {
            onExecutionComplete();
        }
    }
复制代码

executeRequest的代码贼多贼多,但我们在里面找到了一个熟悉的方法名startActivityUnchecked

  private int executeRequest(Request request) {
        ...

        int err = ActivityManager.START_SUCCESS;
    

        ...

        mLastStartActivityResult = startActivityUnchecked(r, sourceRecord, voiceSession,
                request.voiceInteractor, startFlags, true /* doResume */, checkedOptions, inTask,
                restrictedBgActivity, intentGrants);

        if (request.outActivity != null) {
            request.outActivity[0] = mLastStartActivityRecord;
        }

        return mLastStartActivityResult;
    }

复制代码

当然,它也变了

    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();
            Trace.traceBegin(Trace.TRACE_TAG_WINDOW_MANAGER, "startActivityInner");
            result = startActivityInner(r, sourceRecord, voiceSession, voiceInteractor,
                    startFlags, doResume, options, inTask, restrictedBgActivity, intentGrants);
        } finally {
            Trace.traceEnd(Trace.TRACE_TAG_WINDOW_MANAGER);
            startedActivityStack = handleStartResult(r, result);
            mService.continueWindowLayout();
        }

        postStartActivityProcessing(r, result, startedActivityStack);

        return result;
    }
复制代码

  int startActivityInner(final ActivityRecord r, ActivityRecord sourceRecord,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            int startFlags, boolean doResume, ActivityOptions options, Task inTask,
            boolean restrictedBgActivity, NeededUriGrants intentGrants) {
        ...

        if (mTargetStack == null) {
            mTargetStack = getLaunchStack(mStartActivity, mLaunchFlags, targetTask, mOptions);
        }
       ...

        mTargetStack.startActivityLocked(mStartActivity, topStack.getTopNonFinishingActivity(),
                newTask, mKeepCurTransition, mOptions);
        if (mDoResume) {
                ...
                mRootWindowContainer.resumeFocusedStacksTopActivities(
                        mTargetStack, mStartActivity, mOptions);
                ...
            }
        }
        ...

        return START_SUCCESS;
    }

复制代码

这里调用了RootWindowContainer的resumeFocusedStacksTopActivities方法

frameworks/base/services/core/java/com/android/server/wm/RootWindowContainer.java


    boolean resumeFocusedStacksTopActivities() {
        return resumeFocusedStacksTopActivities(null, null, null);
    }
    boolean resumeFocusedStacksTopActivities(
            ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {

        ...

        for (int displayNdx = getChildCount() - 1; displayNdx >= 0; --displayNdx) {
            ...
            if (!resumedOnDisplay) {
               
                final ActivityStack focusedStack = display.getFocusedStack();
                if (focusedStack != null) {
                    focusedStack.resumeTopActivityUncheckedLocked(target, targetOptions);
                }
            }
        }

        return result;
    }

复制代码

接下来又走到了ActivityStack

frameworks/base/services/core/java/com/android/server/wm/ActivityStack.java

   boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
         ...
                result = resumeTopActivityInnerLocked(prev, options);
         ....
      
    }
    
   private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
            ....
    
            
            mStackSupervisor.startSpecificActivity(next, true, false);
            ...
   }
复制代码

android 10为startSpecificActivityLock,11 为startSpecificActivity

frameworks/base/services/core/java/com/android/server/wm/ActivityStackSupervisor.java

   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 {
                // 应用已启动则启动Activity
                   realStartActivityLocked(r, wpc, 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.
               knownToBeDead = true;
           }
   
           ...
           try {
               ...
               // 通知启动应用
               final Message msg = PooledLambda.obtainMessage(
                       ActivityManagerInternal::startProcess, mService.mAmInternal, r.processName,
                       r.info.applicationInfo, knownToBeDead, "activity", r.intent.getComponent());
               mService.mH.sendMessage(msg);
           } finally {
               Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
           }
       }
复制代码

ActivityThread启动新的Activity

img
这一过程流程没有变化

总结

Android 8 - 9

  • 调用startActivity后通过Instrumentation通知AMS
  • AMS通知ActivityStarter启动Activity
  • ActivityStarter通知ActivityStackSupervisor,ActivityStackSupervisor协同ActivityStack处理一些堆栈事务,然后通知ApplicationThread启动Activity
  • ApplicationThread告知ActivityThread发送启动消息,ActivityThread向mH发送LAUNCH_ACTIVITY消息
  • mH收到LAUNCH_ACTIVITY消息后,通过主线程调用performLaunchActivity方法创建Activity
  • 创建完后通过Instrumentation告知Activity,然后Activity回调onCreate方法,告知开发者Activity已创建

请求AMS

img

AMS到ApplicationThread的调用过程

img

ActivityThread 启动Activity 的过程

img

Android 10 - 11

  • 调用startActivity后通过Instrumentation通知AMS的小弟ATMS
  • ATMS通过ActivityStartController通知ActivityStarter启动Activity
  • ActivityStarter通知RootActivityContainer(Android 11为RootWindowContainer),RootActivityContainer通知ActivityStack处理堆栈
  • 使用ActivityStackSupervisor通知ClientLifecycleManager,并彻底LaunchActivityItem对象
  • ClientLifecycleManager通知ApplicationThread
  • ApplicationThread告知ActivityThread发送启动消息,ActivityThread向mH发送EXECUTE_TRANSACTION消息和LaunchActivityItem对象
  • mH收到EXECUTE_TRANSACTION消息后,通过主线程执行LaunchActivityItem的execute方法,然后调用performLaunchActivity方法创建Activity
  • 创建完后通过Instrumentation告知Activity,然后Activity回调onCreate方法,告知开发者Activity已创建

请求ATMS

img

ATMS发送指令到ActivityThread

Android 10

img

Android 11

img
两个版本对比:

  • ActivityStarter逻辑有些改动
  • RootActivityContainer改成了RootWindowContainer
  • ActivityStackSupervisor->startSpecificActivityLock改为startSpecificActivity

ActivityThread启动新的Activity

img

分类:
Android
标签:
收藏成功!
已添加到「」, 点击更改