[转]【源码向】Activity启动流程源码分析【二】【基于Android Q】

我们在上一篇博客中已经介绍了关于Activity的一些基础概念。这一篇博客我们以Android 10.0的代码来分析Activity的启动流程。

Activity的启动主要包括以下几个步骤:

  1. 应用通过startActivity或是startActivityForResult方法向ActivityManagerService发出启动请求。

  2. ActivityManagerService接收到启动请求后,解析启动的Activity信息以及启动模式,为正式启动做准备工作。

  3. ActivityManagerService做完准备工作之后,判断栈顶是否为空,如果不为空,即当前有Activity显示在前台,则先会请求对栈顶 Activity进行onPause操作。

  4. 栈顶Activity执行onPause操作。

  5. 栈顶Activity执行onPause操作结束,通知ActivityManagerService onPause完成。

  6. 为启动Activity创建新进程。

  7. Activity所在应用进程和主线程初始化完成之后创建Application。

  8. 继续启动Activity。

整个过程的示意图如下:


下面我们分步骤具体来进行分析。先看步骤1,2,时序图如下:

//frameworks/base/core/java/android/app/Activity.java
5533    @Override
5534    public void startActivity(Intent intent, @Nullable Bundle options) {
5535        if (options != null) {
5536            startActivityForResult(intent, -1, options);
5537        } else {
5538            // Note we want to go through this call for compatibility with
5539            // applications that may have overridden the method.
5540            startActivityForResult(intent, -1);
5541        }
5542    }

参数intent包含了要启动的activity组件的信息。

//frameworks/base/core/java/android/app/Activity.java
5901    @Override
5902    @UnsupportedAppUsage
5903    public void startActivityForResult(
5904            String who, Intent intent, int requestCode, @Nullable Bundle options) {
5905        Uri referrer = onProvideReferrer();
5906        if (referrer != null) {
5907            intent.putExtra(Intent.EXTRA_REFERRER, referrer);
5908        }
5909        options = transferSpringboardActivityOptions(options);
5910        Instrumentation.ActivityResult ar =
5911            mInstrumentation.execStartActivity(
5912                this, mMainThread.getApplicationThread(), mToken, who,
5913                intent, requestCode, options);
5914        if (ar != null) {
5915            mMainThread.sendActivityResult(
5916                mToken, who, requestCode,
5917                ar.getResultCode(), ar.getResultData());
5918        }
5919        cancelInputsAndStartExitTransition(options);
5920    }

execStartActivity里面我们需要注意两个参数。mMainThread.getApplicationThread()会返回一个ApplicationThread类型的变量。这个变量我们在上一章已经介绍过了,这里ApplicationThread代表的是发起请求的APP1,后面AMS和APP1就通过它来进行跨进程通信,步骤2 AMS中止APP1,AMS就是根据这个参数找到APP1的。mToken我们在上一章中也介绍过了,它是连接ActivityRecord,ActivityClientRecord,activity的桥梁,AMS通过它就可以获取APP1的详细信息了。

//frameworks/base/core/java/android/app/Instrumentation.java
1677    @UnsupportedAppUsage
1678    public ActivityResult execStartActivity(
1679            Context who, IBinder contextThread, IBinder token, Activity target,
1680            Intent intent, int requestCode, Bundle options) {
        ........
1711            int result = ActivityTaskManager.getService()
1712                .startActivity(whoThread, who.getBasePackageName(), intent,
1713                        intent.resolveTypeIfNeeded(who.getContentResolver()),
1714                        token, target != null ? target.mEmbeddedID : null,
1715                        requestCode, 0, null, options);
        ........

startActivity会进行一次binder调用,ActivityTaskManagerService之前讲过是用来分担ActivityManagerService的一些功能的。这个地方开始就从当前应用APP1跳转到了AMS,通知AMS要启动APP2。

//frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
1008    @Override
1009    public final int startActivity(IApplicationThread caller, String callingPackage,
1010            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1011            int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1012        return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1013                resultWho, requestCode, startFlags, profilerInfo, bOptions,
1014                UserHandle.getCallingUserId());
1015    }

APP1要求启动APP2,我们需要记录几个关键的参数,caller:谁发起了这次启动请求,intent:被启动activity APP2的信息, resultTo:发起启动要求的APP1的信息。这样谁要求启动谁这个请求就很清晰的传递给了AMS。

//frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
1031    @Override
1032    public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1033            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1034            int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1035        return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1036                resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1037                true /*validateIncomingUser*/);
1038    }
1039
1040    int startActivityAsUser(IApplicationThread caller, String callingPackage,
1041            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1042            int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1043            boolean validateIncomingUser) {
1044        enforceNotIsolatedCaller("startActivityAsUser");
1045
1046        userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
1047                Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1048
1049        // TODO: Switch to user app stacks here.
1050        return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
1051                .setCaller(caller)
1052                .setCallingPackage(callingPackage)
1053                .setResolvedType(resolvedType)
1054                .setResultTo(resultTo)
1055                .setResultWho(resultWho)
1056                .setRequestCode(requestCode)
1057                .setStartFlags(startFlags)
1058                .setProfilerInfo(profilerInfo)
1059                .setActivityOptions(bOptions)
1060                .setMayWait(userId)
1061                .execute();
1062
1063    }

首先获取并初始化ActivityStater对象,然后调用它的execute方法。

//frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java
511    int execute() {
512        try {
513            // TODO(b/64750076): Look into passing request directly to these methods to allow
514            // for transactional diffs and preprocessing.
515            if (mRequest.mayWait) {
516                return startActivityMayWait(mRequest.caller, mRequest.callingUid,
517                        mRequest.callingPackage, mRequest.realCallingPid, mRequest.realCallingUid,
518                        mRequest.intent, mRequest.resolvedType,
519                        mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
520                        mRequest.resultWho, mRequest.requestCode, mRequest.startFlags,
521                        mRequest.profilerInfo, mRequest.waitResult, mRequest.globalConfig,
522                        mRequest.activityOptions, mRequest.ignoreTargetSecurity, mRequest.userId,
523                        mRequest.inTask, mRequest.reason,
524                        mRequest.allowPendingRemoteAnimationRegistryLookup,
525                        mRequest.originatingPendingIntent, mRequest.allowBackgroundActivityStart);
526            } else {
527                return startActivity(mRequest.caller, mRequest.intent, mRequest.ephemeralIntent,
528                        mRequest.resolvedType, mRequest.activityInfo, mRequest.resolveInfo,
529                        mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
530                        mRequest.resultWho, mRequest.requestCode, mRequest.callingPid,
531                        mRequest.callingUid, mRequest.callingPackage, mRequest.realCallingPid,
532                        mRequest.realCallingUid, mRequest.startFlags, mRequest.activityOptions,
533                        mRequest.ignoreTargetSecurity, mRequest.componentSpecified,
534                        mRequest.outActivity, mRequest.inTask, mRequest.reason,
535                        mRequest.allowPendingRemoteAnimationRegistryLookup,
536                        mRequest.originatingPendingIntent, mRequest.allowBackgroundActivityStart);
537            }
538        } finally {
539            onExecutionComplete();
540        }
541    }

接着调用startActivityMayWait。

//frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java
1144    private int startActivityMayWait(IApplicationThread caller, int callingUid,
1145            String callingPackage, int requestRealCallingPid, int requestRealCallingUid,
1146            Intent intent, String resolvedType, IVoiceInteractionSession voiceSession,
1147            IVoiceInteractor voiceInteractor, IBinder resultTo, String resultWho, int requestCode,
1148            int startFlags, ProfilerInfo profilerInfo, WaitResult outResult,
1149            Configuration globalConfig, SafeActivityOptions options, boolean ignoreTargetSecurity,
1150            int userId, TaskRecord inTask, String reason,
1151            boolean allowPendingRemoteAnimationRegistryLookup,
1152            PendingIntentRecord originatingPendingIntent, boolean allowBackgroundActivityStart) {
        ........  
            //PakageManagerService解析intent(APP2的intent),获取Activity更多的信息
1194        ResolveInfo rInfo = mSupervisor.resolveIntent(intent, resolvedType, userId,
1195                0 /* matchFlags */,
1196                        computeResolveFilterUid(
1197                                callingUid, realCallingUid, mRequest.filterCallingUid));
        ........
1297            final ActivityRecord[] outRecord = new ActivityRecord[1];
1298            int res = startActivity(caller, intent, ephemeralIntent, resolvedType, aInfo, rInfo,
1299                    voiceSession, voiceInteractor, resultTo, resultWho, requestCode, callingPid,
1300                    callingUid, callingPackage, realCallingPid, realCallingUid, startFlags, options,
1301                    ignoreTargetSecurity, componentSpecified, outRecord, inTask, reason,
1302                    allowPendingRemoteAnimationRegistryLookup, originatingPendingIntent,
        ........
//frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java
568    private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
569            String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
570            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
571            IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
572            String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
573            SafeActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,
574            ActivityRecord[] outActivity, TaskRecord inTask, String reason,
575            boolean allowPendingRemoteAnimationRegistryLookup,
576            PendingIntentRecord originatingPendingIntent, boolean allowBackgroundActivityStart) {
        ........
585        mLastStartActivityResult = startActivity(caller, intent, ephemeralIntent, resolvedType,
586                aInfo, rInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode,
587                callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
588                options, ignoreTargetSecurity, componentSpecified, mLastStartActivityRecord,
589                inTask, allowPendingRemoteAnimationRegistryLookup, originatingPendingIntent,
590                allowBackgroundActivityStart);
591
592        if (outActivity != null) {
593            // mLastStartActivityRecord[0] is set in the call to startActivity above.
594            outActivity[0] = mLastStartActivityRecord[0];
595        }
596
597        return getExternalResult(mLastStartActivityResult);
598    }
/frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java
613    private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
614            String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
615            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
616            IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
617            String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
618            SafeActivityOptions options,
619            boolean ignoreTargetSecurity, boolean componentSpecified, ActivityRecord[] outActivity,
620            TaskRecord inTask, boolean allowPendingRemoteAnimationRegistryLookup,
621            PendingIntentRecord originatingPendingIntent, boolean allowBackgroundActivityStart) {
        ........
629        if (caller != null) {
630            callerApp = mService.getProcessController(caller);
631            if (callerApp != null) {
                   //获取调用者的pid和uid
632                callingPid = callerApp.getPid();
633                callingUid = callerApp.mInfo.uid;
        ........
           //sourceRecord表示发起本次请求的Activity,即父Activity对应的信息
           //resultRecord表示接收处理结果的Activity。一般情况下二者相等
650        ActivityRecord sourceRecord = null;
651        ActivityRecord resultRecord = null;
652        if (resultTo != null) {
653            sourceRecord = mRootActivityContainer.isInAnyStack(resultTo);
654            if (DEBUG_RESULTS) Slog.v(TAG_RESULTS,
655                    "Will send result to " + resultTo + " " + sourceRecord);
656            if (sourceRecord != null) {
657                if (requestCode >= 0 && !sourceRecord.finishing) {
658                    resultRecord = sourceRecord;
659                }
660            }
661        }
        ........
           //创建ActivityRecord,ActivityRecord用于保存Activity的信息,现在AMS已经拥有了该Activity的实例,但他还没有和TaskRecord关联起来
901        ActivityRecord r = new ActivityRecord(mService, callerApp, callingPid, callingUid,
902                callingPackage, intent, resolvedType, aInfo, mService.getGlobalConfiguration(),
903                resultRecord, resultWho, requestCode, componentSpecified, voiceSession != null,
904                mSupervisor, checkedOptions, sourceRecord);
905        if (outActivity != null) {
906            outActivity[0] = r;
907        }
        .......
935        final int res = startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
936                true /* doResume */, checkedOptions, inTask, outActivity, restrictedBgActivity);
937        mSupervisor.getActivityMetricsLogger().notifyActivityLaunched(res, outActivity[0]);
938        return res;
939    }
//frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java
1396    private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
1397                IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
1398                int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
1399                ActivityRecord[] outActivity, boolean restrictedBgActivity) {
1400        int result = START_CANCELED;
1401        final ActivityStack startedActivityStack;
1402        try {
1403            mService.mWindowManager.deferSurfaceLayout();
1404            result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
1405                    startFlags, doResume, options, inTask, outActivity, restrictedBgActivity);
        ........

startActivityUnchecked这个函数最重要的工作就是为我们刚刚创建好的ActivityRecord找到它对用的TaskRecord和ActivityStack。

1474    private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
1475            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
1476            int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
1477            ActivityRecord[] outActivity, boolean restrictedBgActivity) {
        ........
1683        // Should this be considered a new task?
1684        int result = START_SUCCESS;
1685        if (mStartActivity.resultTo == null && mInTask == null && !mAddingToTask
1686                && (mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0) {
1687            newTask = true;
                //ActivityRecord和TaskRecord,ActivityStack就是在这个函数建立联系的,详细过程可以参考上一篇博客
1688            result = setTaskFromReuseOrCreateNewTask(taskToAffiliate);
        ........
1746                mRootActivityContainer.resumeFocusedStacksTopActivities(
1747                        mTargetStack, mStartActivity, mOptions);
1748            }
1749        } else if (mStartActivity != null) {
1750            mSupervisor.mRecentTasks.add(mStartActivity.getTaskRecord());
1751        }
1752        mRootActivityContainer.updateUserStack(mStartActivity.mUserId, mTargetStack);
1753
1754        mSupervisor.handleNonResizableTaskIfNeeded(mStartActivity.getTaskRecord(),
1755                preferredWindowingMode, mPreferredDisplayId, mTargetStack);
1756
1757        return START_SUCCESS;
1758    }
//frameworks/base/services/core/java/com/android/server/wm/RootActivityContainer.java
1149    boolean resumeFocusedStacksTopActivities(
1150            ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
1151
1152        if (!mStackSupervisor.readyToResume()) {
1153            return false;
1154        }
1155
1156        boolean result = false;
1157        if (targetStack != null && (targetStack.isTopStackOnDisplay()
1158                || getTopDisplayFocusedStack() == targetStack)) {
1159            result = targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
1160        }
        ........
//frameworks/base/services/core/java/com/android/server/wm/ActivityStack.java
2567    boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
2568        if (mInResumeTopActivity) {
2569            // Don't even start recursing.
2570            return false;
2571        }
2572
2573        boolean result = false;
2574        try {
2575            // Protect against recursion.
2576            mInResumeTopActivity = true;
2577            result = resumeTopActivityInnerLocked(prev, options);
2578
2579            // When resuming the top activity, it may be necessary to pause the top activity (for
2580            // example, returning to the lock screen. We suppress the normal pause logic in
2581            // {@link #resumeTopActivityUncheckedLocked}, since the top activity is resumed at the
2582            // end. We call the {@link ActivityStackSupervisor#checkReadyForSleepLocked} again here
2583            // to ensure any necessary pause logic occurs. In the case where the Activity will be
2584            // shown regardless of the lock screen, the call to
2585            // {@link ActivityStackSupervisor#checkReadyForSleepLocked} is skipped.
2586            final ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */);
2587            if (next == null || !next.canTurnScreenOn()) {
2588                checkReadyForSleep();
2589            }
2590        } finally {
2591            mInResumeTopActivity = false;
2592        }
2593
2594        return result;
2595    }
//frameworks/base/services/core/java/com/android/server/wm/ActivityStack.java
2616    private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
2617        if (!mService.isBooting() && !mService.isBooted()) {
2618            // Not ready yet!
2619            return false;
2620        }
        ........
2747        if (mResumedActivity != null) {
2748            if (DEBUG_STATES) Slog.d(TAG_STATES,
2749                    "resumeTopActivityLocked: Pausing " + mResumedActivity);
                //中止当前activity
2750            pausing |= startPausingLocked(userLeaving, false, next, false);
2751        }
        ........
                //继续activity的启动
3039            mStackSupervisor.startSpecificActivityLocked(next, true, true);
3040        }
3041
3042        return true;
3043    }

如果当前界面正在显示一个Activity,那么在启动新的Activity之前必须中断当前的Activity,中断完成之后继续调用startSpectificActivityLocked函数继续启动activity。步骤1,2主要做的就是根据APP1启动APP2的请求,为APP1创建ActivityRecord,并为这个ActivityRecord找到找到它所属的TaskRecord,ActivityStack,ActivityDisplay。

接下来我们看下步骤3,4,onPause当前Activity,我们还是先看下这一步骤的时序图:

//frameworks/base/services/core/java/com/android/server/wm/ActivityStack.java
1653      final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping,
1654              ActivityRecord resuming, boolean pauseImmediately) {
          ........
//Android 9.0之后引入了ClientLifecycleManager和ClientTransactionHandler来辅助管理Activity的
//生命周期,它会发送EXECUTE_TRANSACTION消息到ActivityThread.H里面继续执行。这边我们要注意传入了
//一个参数PauseActivityItem
1698                  mService.getLifecycleManager().scheduleTransaction(prev.app.getThread(),
1699                          prev.appToken, PauseActivityItem.obtain(prev.finishing, userLeaving,
1700                                  prev.configChangeFlags, pauseImmediately));
          ........
//frameworks/base/services/core/java/com/android/server/wm/ClientLifecycleManager.java
65      void scheduleTransaction(@NonNull IApplicationThread client, @NonNull IBinder activityToken,
66              @NonNull ActivityLifecycleItem stateRequest) throws RemoteException {
67          final ClientTransaction clientTransaction = transactionWithState(client, activityToken,
68                  stateRequest);
69          scheduleTransaction(clientTransaction);
70      }
 
 
45      void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
46          final IApplicationThread client = transaction.getClient();
47          transaction.schedule();
48          if (!(client instanceof Binder)) {
49              // If client is not an instance of Binder - it's a remote call and at this point it is
50              // safe to recycle the object. All objects used for local calls will be recycled after
51              // the transaction is executed on client in ActivityThread.
52              transaction.recycle();
53          }
54      }
 
//frameworks/base/core/java/android/app/servertransaction/ClientTransaction.java
134      public void schedule() throws RemoteException {
135          mClient.scheduleTransaction(this);
136      }
137  

Client是一个IApplicationThread类型。ActivityThread的内部类ApplicationThread派生这个接口类并实现对应的方法。所以直接跳转到ApplicationThread中的scheduleTransaction方法。

//frameworks/base/core/java/android/app/ActivityThread.java
1665          public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
1666              ActivityThread.this.scheduleTransaction(transaction);
1667          }
1668  

接着调用它父类ClientTransactionHandler的scheduleTransaction方法

//frameworks/base/core/java/android/app/ClientTransactionHandler.java
45      void scheduleTransaction(ClientTransaction transaction) {
46          transaction.preExecute(this);
47          sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
48      }
49  

在ClientTransactionHandler.scheduleTransaction方法中调用了sendMessage方法,这个方法是一个抽象方法,其实现在ClientTransactionHandler派生类ActivityThread中。ActivityThread.sendMessage方法会把消息发送给内部名字叫H的Handler。

//frameworks/base/core/java/android/app/ActivityThread.java
3106      void sendMessage(int what, Object obj) {
3107          sendMessage(what, obj, 0, 0, false);
3108      }
3109  
3110      private void sendMessage(int what, Object obj, int arg1) {
3111          sendMessage(what, obj, arg1, 0, false);
3112      }
3113  
3114      private void sendMessage(int what, Object obj, int arg1, int arg2) {
3115          sendMessage(what, obj, arg1, arg2, false);
3116      }
3117  
3118      private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
3119          if (DEBUG_MESSAGES) {
3120              Slog.v(TAG,
3121                      "SCHEDULE " + what + " " + mH.codeToString(what) + ": " + arg1 + " / " + obj);
3122          }
3123          Message msg = Message.obtain();
3124          msg.what = what;
3125          msg.obj = obj;
3126          msg.arg1 = arg1;
3127          msg.arg2 = arg2;
3128          if (async) {
3129              msg.setAsynchronous(true);
3130          }
3131          mH.sendMessage(msg);
3132      }
 
1853          public void handleMessage(Message msg) {
1854              if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
1855              switch (msg.what) {
          ........
2014                  case EXECUTE_TRANSACTION:
2015                      final ClientTransaction transaction = (ClientTransaction) msg.obj;
2016                      mTransactionExecutor.execute(transaction);
2017                      if (isSystem()) {
2018                          // Client transactions inside system process are recycled on the client side
2019                          // instead of ClientLifecycleManager to avoid being cleared before this
2020                          // message is handled.
2021                          transaction.recycle();
2022                      }
2023                      // TODO(lifecycler): Recycle locally scheduled transactions.
2024                      break;
          ........

Handler H的实例接收到EXECUTE_TRANSACTION消息后调用TransactionExecutor.execute切换Activity的状态。

//frameworks/base/core/java/android/app/servertransaction/TransactionExecutor.java
69      public void execute(ClientTransaction transaction) {
70          if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "Start resolving transaction");
71  
72          final IBinder token = transaction.getActivityToken();
73          if (token != null) {
74              final Map<IBinder, ClientTransactionItem> activitiesToBeDestroyed =
75                      mTransactionHandler.getActivitiesToBeDestroyed();
76              final ClientTransactionItem destroyItem = activitiesToBeDestroyed.get(token);
77              if (destroyItem != null) {
78                  if (transaction.getLifecycleStateRequest() == destroyItem) {
79                      // It is going to execute the transaction that will destroy activity with the
80                      // token, so the corresponding to-be-destroyed record can be removed.
81                      activitiesToBeDestroyed.remove(token);
82                  }
83                  if (mTransactionHandler.getActivityClient(token) == null) {
84                      // The activity has not been created but has been requested to destroy, so all
85                      // transactions for the token are just like being cancelled.
86                      Slog.w(TAG, tId(transaction) + "Skip pre-destroyed transaction:\n"
87                              + transactionToString(transaction, mTransactionHandler));
88                      return;
89                  }
90              }
91          }
92  
93          if (DEBUG_RESOLVER) Slog.d(TAG, transactionToString(transaction, mTransactionHandler));
94  
95          executeCallbacks(transaction);
96  
97          executeLifecycleState(transaction);
98          mPendingActions.clear();
99          if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "End resolving transaction");
100      }

接下来我们关注executeLifecycleState函数。

//frameworks/base/core/java/android/app/servertransaction/TransactionExecutor.java
152      private void executeLifecycleState(ClientTransaction transaction) {
             //我们最开始在ActivityStack.startPausingLocked方法里面scheduleTransaction
             //传递的是PauseActivityItem
153          final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
154          if (lifecycleItem == null) {
155              // No lifecycle request, return early.
156              return;
157          }
158  
159          final IBinder token = transaction.getActivityToken();
160          final ActivityClientRecord r = mTransactionHandler.getActivityClient(token);
161          if (DEBUG_RESOLVER) {
162              Slog.d(TAG, tId(transaction) + "Resolving lifecycle state: "
163                      + lifecycleItem + " for activity: "
164                      + getShortActivityName(token, mTransactionHandler));
165          }
166  
167          if (r == null) {
168              // Ignore requests for non-existent client records for now.
169              return;
170          }
171  
172          // Cycle to the state right before the final requested state.
173          cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */, transaction);
174  
175          // Execute the final transition with proper parameters.
176          lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
             //调用PauseActivityItem.execute
177          lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
178      }
//frameworks/base/core/java/android/app/servertransaction/PauseActivityItem.java
43      public void execute(ClientTransactionHandler client, IBinder token,
44              PendingTransactionActions pendingActions) {
45          Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityPause");
46          client.handlePauseActivity(token, mFinished, mUserLeaving, mConfigChanges, pendingActions,
47                  "PAUSE_ACTIVITY_ITEM");
48          Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
49      }
50  

在PauseActivityItem.execute方法中调用Activity.handlePauseActivity方法。

//frameworks/base/core/java/android/app/ActivityThread.java
4397      public void handlePauseActivity(IBinder token, boolean finished, boolean userLeaving,
4398              int configChanges, PendingTransactionActions pendingActions, String reason) {
4399          ActivityClientRecord r = mActivities.get(token);
4400          if (r != null) {
4401              if (userLeaving) {
4402                  performUserLeavingActivity(r);
4403              }
4404  
4405              r.activity.mConfigChangeFlags |= configChanges;
4406              performPauseActivity(r, finished, reason, pendingActions);
4407  
4408              // Make sure any pending writes are now committed.
4409              if (r.isPreHoneycomb()) {
4410                  QueuedWork.waitToFinish();
4411              }
4412              mSomeActivitiesChanged = true;
4413          }
4414      }
 
4430      private Bundle performPauseActivity(ActivityClientRecord r, boolean finished, String reason,
4431              PendingTransactionActions pendingActions) {
4432          if (r.paused) {
4433              if (r.activity.mFinished) {
4434                  // If we are finishing, we won't call onResume() in certain cases.
4435                  // So here we likewise don't want to call onPause() if the activity
4436                  // isn't resumed.
4437                  return null;
4438              }
4439              RuntimeException e = new RuntimeException(
4440                      "Performing pause of activity that is not resumed: "
4441                      + r.intent.getComponent().toShortString());
4442              Slog.e(TAG, e.getMessage(), e);
4443          }
4444          if (finished) {
4445              r.activity.mFinished = true;
4446          }
4447  
4448          // Pre-Honeycomb apps always save their state before pausing
4449          final boolean shouldSaveState = !r.activity.mFinished && r.isPreHoneycomb();
4450          if (shouldSaveState) {
4451              callActivityOnSaveInstanceState(r);
4452          }
4453  
4454          performPauseActivityIfNeeded(r, reason);
          ........
 
4481      private void performPauseActivityIfNeeded(ActivityClientRecord r, String reason) {
4482          if (r.paused) {
4483              // You are already paused silly...
4484              return;
4485          }
4486  
4487          // Always reporting top resumed position loss when pausing an activity. If necessary, it
4488          // will be restored in performResumeActivity().
4489          reportTopResumedActivityChanged(r, false /* onTop */, "pausing");
4490  
4491          try {
4492              r.activity.mCalled = false;
4493              mInstrumentation.callActivityOnPause(r.activity);
4494              if (!r.activity.mCalled) {
4495                  throw new SuperNotCalledException("Activity " + safeToComponentShortString(r.intent)
4496                          + " did not call through to super.onPause()");
4497              }
4498          } catch (SuperNotCalledException e) {
4499              throw e;
4500          } catch (Exception e) {
4501              if (!mInstrumentation.onException(r.activity, e)) {
4502                  throw new RuntimeException("Unable to pause activity "
4503                          + safeToComponentShortString(r.intent) + ": " + e.toString(), e);
4504              }
4505          }
4506          r.setState(ON_PAUSE);
4507      }
4508  

继调用Instrumentation。callActivityOnPause。

//frameworks/base/core/java/android/app/Instrumentation.java
1506      public void callActivityOnPause(Activity activity) {
1507          activity.performPause();
1508      }

在performPause方法中我们终于看到了熟悉的身影Activity生命周期的onPause方法,至此栈顶Activity的Pause流程全部结束。

//frameworks/base/core/java/android/app/Activity.java
7973      final void performPause() {
7974          dispatchActivityPrePaused();
7975          mDoReportFullyDrawn = false;
7976          mFragments.dispatchPause();
7977          mCalled = false;
7978          onPause();
7979          writeEventLog(LOG_AM_ON_PAUSE_CALLED, "performPause");
7980          mResumed = false;
7981          if (!mCalled && getApplicationInfo().targetSdkVersion
7982                  >= android.os.Build.VERSION_CODES.GINGERBREAD) {
7983              throw new SuperNotCalledException(
7984                      "Activity " + mComponent.toShortString() +
7985                      " did not call through to super.onPause()");
7986          }
7987          dispatchActivityPostPaused();
7988      }

我们继续流程分析,步骤6为要启动的APP2创建Process。还是先把时序图放上来。

//frameworks/base/services/core/java/com/android/server/wm/ActivityStackSupervisor.java
956      void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) {
957          // Is this activity's application already running?
958          final WindowProcessController wpc =
959                  mService.getProcessController(r.processName, r.info.applicationInfo.uid);
960  
961          boolean knownToBeDead = false;
962          if (wpc != null && wpc.hasThread()) {
963              try {
                     //如果进程和线程存在,则直接调用realStartActivityLocked
964                  realStartActivityLocked(r, wpc, andResume, checkConfig);
965                  return;
966              } catch (RemoteException e) {
967                  Slog.w(TAG, "Exception when starting activity "
968                          + r.intent.getComponent().flattenToShortString(), e);
969              }
970  
971              // If a dead object exception was thrown -- fall through to
972              // restart the application.
973              knownToBeDead = true;
974          }
          ........
990              final Message msg = PooledLambda.obtainMessage(
991                      ActivityManagerInternal::startProcess, mService.mAmInternal, r.processName,
992                      r.info.applicationInfo, knownToBeDead, "activity", r.intent.getComponent());
993              mService.mH.sendMessage(msg);
994          } finally {
995              Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
996          }
997      }

ActivityManagerInternal的实现类为ActivityManagerService.localService。

//frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
18400          public void startProcess(String processName, ApplicationInfo info,
18401                  boolean knownToBeDead, String hostingType, ComponentName hostingName) {
18402              try {
18403                  if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
18404                      Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "startProcess:"
18405                              + processName);
18406                  }
18407                  synchronized (ActivityManagerService.this) {
18408                      startProcessLocked(processName, info, knownToBeDead, 0 /* intentFlags */,
18409                              new HostingRecord(hostingType, hostingName),
18410                              false /* allowWhileBooting */, false /* isolated */,
18411                              true /* keepIfLarge */);
18412                  }
18413              } finally {
18414                  Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
18415              }
18416          }
 
3022      final ProcessRecord startProcessLocked(String processName,
3023              ApplicationInfo info, boolean knownToBeDead, int intentFlags,
3024              HostingRecord hostingRecord, boolean allowWhileBooting,
3025              boolean isolated, boolean keepIfLarge) {
3026          return mProcessList.startProcessLocked(processName, info, knownToBeDead, intentFlags,
3027                  hostingRecord, allowWhileBooting, isolated, 0 /* isolatedUid */, keepIfLarge,
3028                  null /* ABI override */, null /* entryPoint */, null /* entryPointArgs */,
3029                  null /* crashHandler */);
3030      }

startProcessLocked这个方法开始准备创建进程,这个方法调用的是ProcessList的startProcessLocked方法。

1849      final ProcessRecord startProcessLocked(String processName, ApplicationInfo info,
1850              boolean knownToBeDead, int intentFlags, HostingRecord hostingRecord,
1851              boolean allowWhileBooting, boolean isolated, int isolatedUid, boolean keepIfLarge,
1852              String abiOverride, String entryPoint, String[] entryPointArgs, Runnable crashHandler) {
          ........
1920          if (app == null) {
1921              checkSlow(startTime, "startProcess: creating new process record");
                  //创建ProcessRecord
1922              app = newProcessRecordLocked(info, processName, isolated, isolatedUid, hostingRecord);
          ........
1952          checkSlow(startTime, "startProcess: stepping in to startProcess");
1953          final boolean success = startProcessLocked(app, hostingRecord, abiOverride);
1954          checkSlow(startTime, "startProcess: done starting proc!");
1955          return success ? app : null;
1956      }
 
 
1842      final boolean startProcessLocked(ProcessRecord app, HostingRecord hostingRecord,
1843              String abiOverride) {
1844          return startProcessLocked(app, hostingRecord,
1845                  false /* disableHiddenApiChecks */, false /* mountExtStorageFull */, abiOverride);
1846      }
 
1428      boolean startProcessLocked(ProcessRecord app, HostingRecord hostingRecord,
1429              boolean disableHiddenApiChecks, boolean mountExtStorageFull,
1430              String abiOverride) {
          ........
1621              return startProcessLocked(hostingRecord, entryPoint, app, uid, gids,
1622                      runtimeFlags, mountExternal, seInfo, requiredAbi, instructionSet, invokeWith,
1623                      startTime);
1624          } catch (RuntimeException e) {
1625              Slog.e(ActivityManagerService.TAG, "Failure starting process " + app.processName, e);
1626  
1627              // Something went very wrong while trying to start this process; one
1628              // common case is when the package is frozen due to an active
1629              // upgrade. To recover, clean up any active bookkeeping related to
1630              // starting this process. (We already invoked this method once when
1631              // the package was initially frozen through KILL_APPLICATION_MSG, so
1632              // it doesn't hurt to use it again.)
1633              mService.forceStopPackageLocked(app.info.packageName, UserHandle.getAppId(app.uid),
1634                      false, false, true, false, false, app.userId, "start failure");
1635              return false;
1636          }
1637      }
 
 
1640      boolean startProcessLocked(HostingRecord hostingRecord,
1641              String entryPoint,
1642              ProcessRecord app, int uid, int[] gids, int runtimeFlags, int mountExternal,
1643              String seInfo, String requiredAbi, String instructionSet, String invokeWith,
1644              long startTime) {
          ........
1667                  try {
                          //注意这个参数final String entryPoint = "android.app.ActivityThread";
1668                      final Process.ProcessStartResult startResult = startProcess(app.hostingRecord,
1669                              entryPoint, app, app.startUid, gids, runtimeFlags, mountExternal,
1670                              app.seInfo, requiredAbi, instructionSet, invokeWith, app.startTime);
1671                      synchronized (mService) {
1672                          handleProcessStartedLocked(app, startResult, startSeq);
1673                      }
          ........

内部经过一系列startProcessLocked的调用会来到startProcess函数。我们需要注意其中

final String entryPoint = "android.app.ActivityThread";这个参数,这个参数会一路从Process传递到ZygoteProcess,并在ZygoteProcess中调用startViaZygote方法,fork出一个新的进程。并根据传递的"android.app.ActivityThread"反射出该对象,于是进程创建进入到ActivityThread的main方法中。这一部分的具体流程我们会单独在后面的博客中进行讲解。

至此我们已经创建好了进程。当Zygote创建完一个应用进程之后,得到的仅仅是一个可以运行的载体,它还没有和Android系统建立联系,我们需要为它创建一个运行环境Context,然后在装载Provider信息,再将新创建的进程绑定到AMS中,这才是一个完整的Android进程。这就是我们步骤7需要完成的操作。

//frameworks/base/core/java/android/app/ActivityThread.java
7310      public static void main(String[] args) {
7311          Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
7312  
7313          // Install selective syscall interception
7314          AndroidOs.install();
7315  
7316          // CloseGuard defaults to true and can be quite spammy.  We
7317          // disable it here, but selectively enable it later (via
7318          // StrictMode) on debug builds, but using DropBox, not logs.
7319          CloseGuard.setEnabled(false);
7320  
7321          Environment.initForCurrentUser();
7322  
7323          // Make sure TrustedCertificateStore looks in the right place for CA certificates
7324          final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
7325          TrustedCertificateStore.setDefaultUserDirectory(configDir);
7326  
7327          Process.setArgV0("<pre-initialized>");
7328  
              //创建了主线程的Looper对象,并调用Looper.loop()方法启动Loop
7329          Looper.prepareMainLooper();
          ........
7342          ActivityThread thread = new ActivityThread();
7343          thread.attach(false, startSeq);
7344  
7345          if (sMainThreadHandler == null) {
7346              sMainThreadHandler = thread.getHandler();
7347          }
7348  
7349          if (false) {
7350              Looper.myLooper().setMessageLogging(new
7351                      LogPrinter(Log.DEBUG, "ActivityThread"));
7352          }
7353  
7354          // End of event ActivityThreadMain.
7355          Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
7356          Looper.loop();
7357  
7358          throw new RuntimeException("Main thread loop unexpectedly exited");
7359      }
 
7071      private void attach(boolean system, long startSeq) {
7072          sCurrentActivityThread = this;
7073          mSystemThread = system;
7074          if (!system) {
7075              android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",
7076                                                      UserHandle.myUserId());
7077              RuntimeInit.setApplicationObject(mAppThread.asBinder());
7078              final IActivityManager mgr = ActivityManager.getService();
7079              try {
                      //这又是一个binder调用,它通过binder将ActivityThread中的IApplicationThread的实例传递给AMS,
                      //然后AMS就可以通过它与应用程序进行通信
7080                  mgr.attachApplication(mAppThread, startSeq);
          ........
//frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
5175      public final void attachApplication(IApplicationThread thread, long startSeq) {
5176          synchronized (this) {
5177              int callingPid = Binder.getCallingPid();
5178              final int callingUid = Binder.getCallingUid();
5179              final long origId = Binder.clearCallingIdentity();
5180              attachApplicationLocked(thread, callingPid, callingUid, startSeq);
5181              Binder.restoreCallingIdentity(origId);
5182          }
5183      }
 
4762      private final boolean attachApplicationLocked(IApplicationThread thread,
4763              int pid, int callingUid, long startSeq) {
          ........
5058                  thread.bindApplication(processName, appInfo, providers, null, profilerInfo,
5059                          null, null, null, testMode,
5060                          mBinderTransactionTrackingEnabled, enableTrackAllocation,
5061                          isRestrictedBackupMode || !normalMode, app.isPersistent(),
5062                          new Configuration(app.getWindowProcessController().getConfiguration()),
5063                          app.compat, getCommonServicesLocked(app.isolated),
5064                          mCoreSettingsObserver.getCoreSettingsLocked(),
5065                          buildSerial, autofillOptions, contentCaptureOptions);
          ........
                  //将thread传给ProcessRecord.thread,可以理解为将应用进程与AMS建立起了绑定
5074              app.makeActive(thread, mProcessStats);

我们从应用程序调用到AMS中又通过bindApplication调回到应用程序,它在AMS中最重要的事就是建立了应用程序与AMS的联系。之前我们Zygote fork的进程并没有包含任何与Activity相关的 信息,甚至连进程名都没有真正命名。此处的bindApplication就是初始化这个新进程并创建对应的Android环境。

//frameworks/base/core/java/android/app/ActivityThread.java
996          public final void bindApplication(String processName, ApplicationInfo appInfo,
997                  List<ProviderInfo> providers, ComponentName instrumentationName,
998                  ProfilerInfo profilerInfo, Bundle instrumentationArgs,
999                  IInstrumentationWatcher instrumentationWatcher,
1000                  IUiAutomationConnection instrumentationUiConnection, int debugMode,
1001                  boolean enableBinderTracking, boolean trackAllocation,
1002                  boolean isRestrictedBackupMode, boolean persistent, Configuration config,
1003                  CompatibilityInfo compatInfo, Map services, Bundle coreSettings,
1004                  String buildSerial, AutofillOptions autofillOptions,
1005                  ContentCaptureOptions contentCaptureOptions) {
          ........
1034              AppBindData data = new AppBindData();
1035              data.processName = processName;
1036              data.appInfo = appInfo;
1037              data.providers = providers;
1038              data.instrumentationName = instrumentationName;
1039              data.instrumentationArgs = instrumentationArgs;
1040              data.instrumentationWatcher = instrumentationWatcher;
1041              data.instrumentationUiAutomationConnection = instrumentationUiConnection;
1042              data.debugMode = debugMode;
1043              data.enableBinderTracking = enableBinderTracking;
1044              data.trackAllocation = trackAllocation;
1045              data.restrictedBackupMode = isRestrictedBackupMode;
1046              data.persistent = persistent;
1047              data.config = config;
1048              data.compatInfo = compatInfo;
1049              data.initProfilerInfo = profilerInfo;
1050              data.buildSerial = buildSerial;
1051              data.autofillOptions = autofillOptions;
1052              data.contentCaptureOptions = contentCaptureOptions;
1053              sendMessage(H.BIND_APPLICATION, data);
1054          }

ActivityThread的接口被AMS调用后,会将参数保存到AppBindData对象中,然后发送消息BIND_APPLICATION让ActivityThread的主线程处理。

6122      private void handleBindApplication(AppBindData data) {
          ........
6154          // send up app name; do this *before* waiting for debugger
              //设置进程名
6155          Process.setArgV0(data.processName);
          ........
6428          try {
6429              // If the app is being launched for full backup or restore, bring it up in
6430              // a restricted environment with the base application class.
6431              app = data.info.makeApplication(data.restrictedBackupMode, null);
          ........
//frameworks/base/core/java/android/app/LoadedApk.java
1194      public Application makeApplication(boolean forceDefaultAppClass,
1195              Instrumentation instrumentation) {
          ........
1217              ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
1218              app = mActivityThread.mInstrumentation.newApplication(
1219                      cl, appClass, appContext);
          ........
1232          if (instrumentation != null) {
1233              try {
1234                  instrumentation.callApplicationOnCreate(app);
1235              } catch (Exception e) {
1236                  if (!instrumentation.onException(app, e)) {
1237                      Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
1238                      throw new RuntimeException(
1239                          "Unable to create application " + app.getClass().getName()
1240                          + ": " + e.toString(), e);
1241                  }
1242              }
1243          }
          ........

data.info.makeApplication方法,在创建Application的过程中,接着调用Instrumentation的newApplication方法。

//frameworks/base/core/java/android/app/Instrumentation.java
1151      public Application newApplication(ClassLoader cl, String className, Context context)
1152              throws InstantiationException, IllegalAccessException,
1153              ClassNotFoundException {
1154          Application app = getFactory(context.getPackageName())
1155                  .instantiateApplication(cl, className);
1156          app.attach(context);
1157          return app;
1158      }
 

newApplication方法通过反射的方法创建Application。因为app安装的时候会去解析manifest中的内容,因此查询系统可以知道要启动的application的具体类名,然后通过类名反射创建application。至此application创建完成。

创建application之后,通过Instrumentation的callApplicationOnCreate方法调用了创建Application对象的onCreate方法。

//frameworks/base/core/java/android/app/Instrumentation.java
1188      public void callApplicationOnCreate(Application app) {
1189          app.onCreate();
1190      }

终于走到应用的Application的onCreate方法,这一步骤结束。

application创建完成之后,继续回到AMS中的attachApplicationLocked方法,接着启动Activity的流程。

//frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
4762      private final boolean attachApplicationLocked(IApplicationThread thread,
4763              int pid, int callingUid, long startSeq) {
          ........
5101          if (normalMode) {
5102              try {
5103                  didSomething = mAtmInternal.attachApplication(app.getWindowProcessController());
5104              } catch (Exception e) {
5105                  Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
5106                  badApp = true;
5107              }
5108          }
          ........

mAtmInternal是ActivityTaskManagerService的内部类LocalService。在localService的attachApplication方法中调用了RootActivityContainer的attachApplication方法。

//frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
6867          public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
6868              synchronized (mGlobalLockWithoutBoost) {
6869                  return mRootActivityContainer.attachApplication(wpc);
6870              }
6871          }
 
//frameworks/base/services/core/java/com/android/server/wm/RootActivityContainer.java
768      boolean attachApplication(WindowProcessController app) throws RemoteException {
          ........
if (activity.app == null && app.mUid == activity.info.applicationInfo.uid
781                              && processName.equals(activity.processName)) {
782                          try {
783                              if (mStackSupervisor.realStartActivityLocked(activity, app,
784                                      top == activity /* andResume */, true /* checkConfig */)) {
785                                  didSomething = true;
786                              }
787                          } catch (RemoteException e) {
788                              Slog.w(TAG, "Exception in new application when starting activity "
789                                      + top.intent.getComponent().flattenToShortString(), e);
790                              throw e;
791                          }
792                      }
          ........

在这我们看到了realStartActivityLocked,这个方法之前在startSpecificActivityLocked方法中见到过,只是当时我们还没有创建好进程所以没有执行。

//frameworks/base/services/core/java/com/android/server/wm/ActivityStackSupervisor.java
705      boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
706              boolean andResume, boolean checkConfig) throws RemoteException {
          ........
827                  // Create activity launch transaction.
828                  final ClientTransaction clientTransaction = ClientTransaction.obtain(
829                          proc.getThread(), r.appToken);
830  
831                  final DisplayContent dc = r.getDisplay().mDisplayContent;
832                  clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
833                          System.identityHashCode(r), r.info,
834                          // TODO: Have this take the merged configuration instead of separate global
835                          // and override configs.
836                          mergedConfiguration.getGlobalConfiguration(),
837                          mergedConfiguration.getOverrideConfiguration(), r.compat,
838                          r.launchedFromPackage, task.voiceInteractor, proc.getReportedProcState(),
839                          r.icicle, r.persistentState, results, newIntents,
840                          dc.isNextTransitionForward(), proc.createProfilerInfoIfNeeded(),
841                                  r.assistToken));
842  
843                  // Set desired final state.
844                  final ActivityLifecycleItem lifecycleItem;
845                  if (andResume) {
846                      lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward());
847                  } else {
848                      lifecycleItem = PauseActivityItem.obtain();
849                  }
850                  clientTransaction.setLifecycleStateRequest(lifecycleItem);
851  
852                  // Schedule transaction.
853                  mService.getLifecycleManager().scheduleTransaction(clientTransaction);
          ........

新建了一个ClientTransaction对象后,设置LaunchActivityItem的callback,然后调用mService的getLifecycleManager获取到ClientLifecycleManager,在通过scheduleTransaction发送请求。这和pause Activity的流程类似,就是改变activity的生命周期。

//frameworks/base/services/core/java/com/android/server/wm/ClientLifecycleManager.java
45      void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
46          final IApplicationThread client = transaction.getClient();
47          transaction.schedule();
48          if (!(client instanceof Binder)) {
49              // If client is not an instance of Binder - it's a remote call and at this point it is
50              // safe to recycle the object. All objects used for local calls will be recycled after
51              // the transaction is executed on client in ActivityThread.
52              transaction.recycle();
53          }
54      }
 
//frameworks/base/core/java/android/app/servertransaction/ClientTransaction.java
134      public void schedule() throws RemoteException {
135          mClient.scheduleTransaction(this);
136      }
 
//frameworks/base/core/java/android/app/ActivityThread.java
1665          public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
1666              ActivityThread.this.scheduleTransaction(transaction);
1667          }
 
//frameworks/base/core/java/android/app/ClientTransactionHandler.java
45      void scheduleTransaction(ClientTransaction transaction) {
46          transaction.preExecute(this);
47          sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
48      }

这边经过了一圈调用就是向ActivityThread发送一个EXECUTE_TRANSACTION。

//frameworks/base/core/java/android/app/ActivityThread.java
1853          public void handleMessage(Message msg) {
          ........
2014                  case EXECUTE_TRANSACTION:
2015                      final ClientTransaction transaction = (ClientTransaction) msg.obj;
2016                      mTransactionExecutor.execute(transaction);
2017                      if (isSystem()) {
2018                          // Client transactions inside system process are recycled on the client side
2019                          // instead of ClientLifecycleManager to avoid being cleared before this
2020                          // message is handled.
2021                          transaction.recycle();
2022                      }
2023                      // TODO(lifecycler): Recycle locally scheduled transactions.
2024                      break;
          ........

和之前pause时候类似,ClientTransaction的execute会调用LaunchActivityItem的execute。

//frameworks/base/core/java/android/app/servertransaction/LaunchActivityItem.java
76      public void execute(ClientTransactionHandler client, IBinder token,
77              PendingTransactionActions pendingActions) {
78          Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
79          ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
80                  mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,
81                  mPendingResults, mPendingNewIntents, mIsForward,
82                  mProfilerInfo, client, mAssistToken);
83          client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
84          Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
85      }

此处的client是一个ActivityThread对象,因此这里调用的ActivityThread的handleLaunchActivity。

//frameworks/base/core/java/android/app/ActivityThread.java
3381      public Activity handleLaunchActivity(ActivityClientRecord r,
3382              PendingTransactionActions pendingActions, Intent customIntent) {
          ........
3409          final Activity a = performLaunchActivity(r, customIntent);
          ........
 
3159      private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
          ........
3178          ContextImpl appContext = createBaseContextForActivity(r);
3179          Activity activity = null;
3180          try {
3181              java.lang.ClassLoader cl = appContext.getClassLoader();
3182              activity = mInstrumentation.newActivity(
3183                      cl, component.getClassName(), r.intent);
3184              StrictMode.incrementExpectedActivityCount(activity.getClass());
3185              r.intent.setExtrasClassLoader(cl);
3186              r.intent.prepareToEnterProcess();
3187              if (r.state != null) {
3188                  r.state.setClassLoader(cl);
3189              }
          ........
3224                  activity.attach(appContext, this, getInstrumentation(), r.token,
3225                          r.ident, app, r.intent, r.activityInfo, title, r.parent,
3226                          r.embeddedID, r.lastNonConfigurationInstances, config,
3227                          r.referrer, r.voiceInteractor, window, r.configCallback,
3228                          r.assistToken);
          ........
3242                  if (r.isPersistable()) {
3243                      mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
3244                  } else {
3245                      mInstrumentation.callActivityOnCreate(activity, r.state);
3246                  }
          ........

performLaunchActivity中通过mInstrumentation的newActivity方法创建了一个activity。activity就保存了上下文信息。然后通过attach将activity和ActivityThread,Instrumentation,Application等重要的类联系起来。这一方法对Activity的ComponentName,ContextImpl,Activity以及Application对象进行了初始化并相互关联。最后调用callActivityOnCreate。

//frameworks/base/core/java/android/app/Instrumentation.java
1304      public void callActivityOnCreate(Activity activity, Bundle icicle) {
1305          prePerformCreate(activity);
1306          activity.performCreate(icicle);
1307          postPerformCreate(activity);
1308      }
1309  
 
 
//frameworks/base/core/java/android/app/Activity.java
 
7794      @UnsupportedAppUsage
7795      final void performCreate(Bundle icicle, PersistableBundle persistentState) {
7796          dispatchActivityPreCreated(icicle);
7797          mCanEnterPictureInPicture = true;
7798          restoreHasCurrentPermissionRequest(icicle);
7799          if (persistentState != null) {
7800              onCreate(icicle, persistentState);
7801          } else {
7802              onCreate(icicle);
7803          }
7804          writeEventLog(LOG_AM_ON_CREATE_CALLED, "performCreate");
7805          mActivityTransitionState.readState(icicle);
7806  
7807          mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
7808                  com.android.internal.R.styleable.Window_windowNoDisplay, false);
7809          mFragments.dispatchActivityCreated();
7810          mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
7811          dispatchActivityPostCreated(icicle);
7812      }

在performCreate中调用了activity的onCreate,Activity创建完成。在Activity对象构建成功,并成功走完onCreate,onStart两个生命周期函数之后,便要进入onResume这个生命周期函数,至此完成Activity全部的启动操作。Activity的启动流程太过复杂,所以本篇博客只是总结了启动的大致流程,其中有很多细节并没有深入描写。其中一些重要的细节,会在后续的博客中详细分析。

原文链接:
https://blog.csdn.net/nanyou519/article/details/104735722
https://juejin.cn/post/6867744083809419277

推荐阅读更多精彩内容