APP启动流程分析(下)

前言

本文基于Android 9.0(Android P),API 28。
本文是APP启动流程分析的下篇,走源码流程。
如果想了解总体流程,请看上篇APP启动流程分析(上)

总流程

APP启动流程分析(下)_第1张图片
总流程分成三个阶段

Launcher请求AMS阶段

APP启动流程分析(下)_第2张图片

AMS到ApplicationThread阶段

APP启动流程分析(下)_第3张图片

ApplicationThread到Activity阶段

APP启动流程分析(下)_第4张图片

上图中的序号,会在下面的源码中标记

源码解析

Launcher请求AMS阶段

Launcher也是APP,从Launcher点击一个APP图标,也是用startActivity。

     //1 进去
     startActivity(intent);

我们点进去startActivity,来到

1 Activity的startActivity方法

  @Override
    public void startActivity(Intent intent) {
        this.startActivity(intent, null);
    }

再点进去

    @Override
    public void startActivity(Intent intent, @Nullable Bundle options) {
        if (options != null) {
            //2 进去
            startActivityForResult(intent, -1, options);
        } else {
            // Note we want to go through this call for compatibility with
            // applications that may have overridden the method.
            startActivityForResult(intent, -1);
        }
    }

2 Activity的startActivityForResult方法

 public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
            @Nullable Bundle options) {
        if (mParent == null) {
            options = transferSpringboardActivityOptions(options);
            Instrumentation.ActivityResult ar =
                    //mMainThread.getApplicationThread()是ApplicationThread,APP那边Binder的代理类,等下传递给AMS
                    //3 进去
                mInstrumentation.execStartActivity(
                    this, mMainThread.getApplicationThread(), mToken, this,
                    intent, requestCode, options);
                    
      省略代码....
          
    }

3 Instrumentation的execStartActivity方法

public ActivityResult execStartActivity(
            Context who, IBinder contextThread, IBinder token, Activity target,
            Intent intent, int requestCode, Bundle options) {
            
      省略代码......
      
      try {
            //合并Intent的参数
            intent.migrateExtraStreamToClipData();
            intent.prepareToLeaveProcess(who);
            //ActivityManager.getService()得到了IActivityManager
            //调用IActivityManager的startActivity方法 4
            //IActivityManager是AMS的代理类,用于APP与AMS进行Binder通信
            //所以跳到ActivityManagerService的startActivity方法 5
            //第一阶段结束
            int result = ActivityManager.getService()
                .startActivity(whoThread, who.getBasePackageName(), intent,
                        intent.resolveTypeIfNeeded(who.getContentResolver()),
                        token, target != null ? target.mEmbeddedID : null,
                        requestCode, 0, null, options);
            //检查startActivity返回的结果
            checkStartActivityResult(result, intent);
        } catch (RemoteException e) {
            throw new RuntimeException("Failure from system", e);
        }
        return null;
    }

AMS到ApplicationThread阶段

4 5 6 ActivityManagerService的startActivity方法

    //对应图中5和6
    @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) {
        //7 进去
        return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
                resultWho, requestCode, startFlags, profilerInfo, bOptions,
                //多了一个UserId,用于多用户
                UserHandle.getCallingUserId());
    }

7 ActivityManagerService的startActivityAsUser方法

    @Override
    public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
            int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
        //进去
        return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
                resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
                //多了一个true
                true /*validateIncomingUser*/);
    }

再点进去

    public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
            int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
            boolean validateIncomingUser) {
        enforceNotIsolatedCaller("startActivity");

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

        // TODO: Switch to user app stacks here.
        //建造者模式
        //obtainStarter通过工厂模式获取ActivityStarter对象
        return mActivityStartController.obtainStarter(intent, "startActivityAsUser")
                .setCaller(caller)
                .setCallingPackage(callingPackage)
                .setResolvedType(resolvedType)
                .setResultTo(resultTo)
                .setResultWho(resultWho)
                .setRequestCode(requestCode)
                .setStartFlags(startFlags)
                .setProfilerInfo(profilerInfo)
                .setActivityOptions(bOptions)
                .setMayWait(userId)
                //进去
                .execute();

    }

ActivityStarter的execute方法

    int execute() {
        try {
            // TODO(b/64750076): Look into passing request directly to these methods to allow
            // for transactional diffs and preprocessing.
            if (mRequest.mayWait) {
                //8 进去
                return startActivityMayWait(mRequest.caller, mRequest.callingUid,
                        mRequest.callingPackage, mRequest.intent, mRequest.resolvedType,
                        mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
                        mRequest.resultWho, mRequest.requestCode, mRequest.startFlags,
                        mRequest.profilerInfo, mRequest.waitResult, mRequest.globalConfig,
                        mRequest.activityOptions, mRequest.ignoreTargetSecurity, mRequest.userId,
                        mRequest.inTask, mRequest.reason,
                        mRequest.allowPendingRemoteAnimationRegistryLookup);
            } else {
                return startActivity(mRequest.caller, mRequest.intent, mRequest.ephemeralIntent,
                        mRequest.resolvedType, mRequest.activityInfo, mRequest.resolveInfo,
                        mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
                        mRequest.resultWho, mRequest.requestCode, mRequest.callingPid,
                        mRequest.callingUid, mRequest.callingPackage, mRequest.realCallingPid,
                        mRequest.realCallingUid, mRequest.startFlags, mRequest.activityOptions,
                        mRequest.ignoreTargetSecurity, mRequest.componentSpecified,
                        mRequest.outActivity, mRequest.inTask, mRequest.reason,
                        mRequest.allowPendingRemoteAnimationRegistryLookup);
            }
        } finally {
            onExecutionComplete();
        }
    }

8 ActivityStarter的startActivityMayWait方法

 private int startActivityMayWait(IApplicationThread caller, int callingUid,
            String callingPackage, Intent intent, String resolvedType,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            IBinder resultTo, String resultWho, int requestCode, int startFlags,
            ProfilerInfo profilerInfo, WaitResult outResult,
            Configuration globalConfig, SafeActivityOptions options, boolean ignoreTargetSecurity,
            int userId, TaskRecord inTask, String reason,
            boolean allowPendingRemoteAnimationRegistryLookup) {
            
        省略代码...
        
        // Save a copy in case ephemeral needs it
        //复制新的Intent对象,
        //后续要对Intent进行修改,复制一份使原有Intent不受影响
        final Intent ephemeralIntent = new Intent(intent);
        // Don't modify the client's object!
        intent = new Intent(intent);
        
        省略代码...
        
        // Collect information about the target of the Intent.
        //收集Intent,看有哪些Activity可以处理这个action
        //比如想打开pdf文件,而手机上安装和WPS和其他PDF阅读器,这行代码会收集可以打开pdf文件
        //的Activity,然后弹出对话框让用户选一个
        ActivityInfo aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags, profilerInfo);

        省略代码...

        final ActivityRecord[] outRecord = new ActivityRecord[1];
        //9 进去
        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);

        Binder.restoreCallingIdentity(origId);

        省略代码...

    }

9 ActivityStarter的startActivity方法

  private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
            String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
            String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
            SafeActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,
            ActivityRecord[] outActivity, TaskRecord inTask, String reason,
            boolean allowPendingRemoteAnimationRegistryLookup) {

        省略代码...
        
        //10 进去
        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);

        省略代码...
    }

10 ActivityStarter的startActivity方法

    private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
            String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
            String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
            SafeActivityOptions options,
            boolean ignoreTargetSecurity, boolean componentSpecified, ActivityRecord[] outActivity,
            TaskRecord inTask, boolean allowPendingRemoteAnimationRegistryLookup) {
        
        省略代码...
        
        //获取我们应用的进程描述类,ProcessRecord对象,获取原理是先获取所有进程
        //然后用我们的caller和ProcessRecord下的thread对象做对比,如果是同一个便可以作为返回结果了
        ProcessRecord callerApp = null;
        if (caller != null) {
            callerApp = mService.getRecordForAppLocked(caller);
            if (callerApp != null) {
                callingPid = callerApp.pid;
                callingUid = callerApp.info.uid;
            } else {
                Slog.w(TAG, "Unable to find app for caller " + caller
                        + " (pid=" + callingPid + ") when starting: "
                        + intent.toString());
                err = ActivityManager.START_PERMISSION_DENIED;
            }
        }
        //又一次获取userId,如果单用户,还是之前那一个userId
        final int userId = aInfo != null && aInfo.applicationInfo != null
                ? UserHandle.getUserId(aInfo.applicationInfo.uid) : 0;

         省略代码...
         
        //接下来做一些校验判断
        if (err == ActivityManager.START_SUCCESS && intent.getComponent() == null) {
            // We couldn't find a class that can handle the given Intent.
            // That's the end of that!
            //从Intent中无法找到相应的Component
            err = ActivityManager.START_INTENT_NOT_RESOLVED;
        }

        if (err == ActivityManager.START_SUCCESS && aInfo == null) {
            // We couldn't find the specific class specified in the Intent.
            // Also the end of the line.
            //从Intent中无法找到相应的ActivityInfo
            err = ActivityManager.START_CLASS_NOT_FOUND;
        }

        省略代码...
        
        //校验当前应用是否有开启权限,我们普通开启肯定有权限
        boolean abort = !mSupervisor.checkStartAnyActivityPermission(intent, aInfo, resultWho,
                requestCode, callingPid, callingUid, callingPackage, ignoreTargetSecurity,
                inTask != null, callerApp, resultRecord, resultStack);
        abort |= !mService.mIntentFirewall.checkStartActivity(intent, callingUid,
                callingPid, resolvedType, aInfo.applicationInfo);

        省略代码...
        
        //通过上面的判断我们知道要创建的Activity是真实存在的,是有权限的,可以启动这个Activity了
        //创建出我们的目标ActivityRecord对象,存到传入数组0的索引上
        ActivityRecord r = new ActivityRecord(mService, callerApp, callingPid, callingUid,
                callingPackage, intent, resolvedType, aInfo, mService.getGlobalConfiguration(),
                resultRecord, resultWho, requestCode, componentSpecified, voiceSession != null,
                mSupervisor, checkedOptions, sourceRecord);
        if (outActivity != null) {
            outActivity[0] = r;
        }

        省略代码...
        
        //11 进去
        return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
                true /* doResume */, checkedOptions, inTask, outActivity);
    }

11 ActivityStarter的startActivity方法

    private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
                IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
                int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
                ActivityRecord[] outActivity) {
        //sourceRecord是指调用者,r是指本次将要启动的Activity
        int result = START_CANCELED;
        try {
            mService.mWindowManager.deferSurfaceLayout();
            //12 进去
            result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
                    startFlags, doResume, options, inTask, outActivity);
        } finally {
            // If we are not able to proceed, disassociate the activity from the task. Leaving an
            // activity in an incomplete state can lead to issues, such as performing operations
            // without a window container.
            final ActivityStack stack = mStartActivity.getStack();
            if (!ActivityManager.isStartResultSuccessful(result) && stack != null) {
                stack.finishActivityLocked(mStartActivity, RESULT_CANCELED,
                        null /* intentResultData */, "startActivity", true /* oomAdj */);
            }
            mService.mWindowManager.continueSurfaceLayout();
        }

        postStartActivityProcessing(r, result, mTargetStack);

        return result;
    }

12 ActivityStarter的startActivityUnchecked方法

    private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
            ActivityRecord[] outActivity) {
            //根据启动intent识别启动模式
            setInitialState(r, options, inTask, doResume, startFlags, sourceRecord, voiceSession,
                voiceInteractor);
            //判断启动模式,并且在mLaunchFlags上追加相应的标记
            computeLaunchingTaskFlags();
            //获取到Activity的启动栈
            computeSourceStack();
            //根据上面的计算,应用识别到的flags
            mIntent.setFlags(mLaunchFlags);

            省略代码...

            // True if we are clearing top and resetting of a standard (default) launch mode
            // ({@code LAUNCH_MULTIPLE}) activity. The existing activity will be finished.
            //如果设置了CLEAR_TOP,就把相应的Activity清空掉
            final boolean clearTopAndResetStandardLaunchMode =
                    (mLaunchFlags & (FLAG_ACTIVITY_CLEAR_TOP | FLAG_ACTIVITY_RESET_TASK_IF_NEEDED))
                            == (FLAG_ACTIVITY_CLEAR_TOP | FLAG_ACTIVITY_RESET_TASK_IF_NEEDED)
                    && mLaunchMode == LAUNCH_MULTIPLE;

            省略代码...
            
                if (top != null) {
                    if (top.frontOfTask) {
                        // Activity aliases may mean we use different intents for the top activity,
                        // so make sure the task now has the identity of the new intent.
                        top.getTask().setIntent(mStartActivity);
                    }
                    //触发onNewIntent()
                    // 比如SingleTask,不用new Activity了,要走onNewIntent()流程
                    deliverNewIntent(top);
                }
            }

        省略代码...
         
        // If the activity being launched is the same as the one currently at the top, then
        // we need to check if it should only be launched once.
        final ActivityStack topStack = mSupervisor.mFocusedStack;
        final ActivityRecord topFocused = topStack.getTopActivity();
        final ActivityRecord top = topStack.topRunningNonDelayedActivityLocked(mNotTop);
        final boolean dontStart = top != null && mStartActivity.resultTo == null
                && top.realActivity.equals(mStartActivity.realActivity)
                && top.userId == mStartActivity.userId
                && top.app != null && top.app.thread != null
                && ((mLaunchFlags & FLAG_ACTIVITY_SINGLE_TOP) != 0
                || isLaunchModeOneOf(LAUNCH_SINGLE_TOP, LAUNCH_SINGLE_TASK));
        if (dontStart) {
            // For paranoia, make sure we have correctly resumed the top activity.
            topStack.mLastPausedActivity = null;
            if (mDoResume) {
                //13 进去
                mSupervisor.resumeFocusedStackTopActivityLocked();
            }
    
        省略代码...
        
    }

13 ActivityStackSupervisor的resumeFocusedStackTopActivityLocked方法

  boolean resumeFocusedStackTopActivityLocked() {
        //14 进去
        return resumeFocusedStackTopActivityLocked(null, null, null);
    }

14 ActivityStackSupervisor的resumeFocusedStackTopActivityLocked方法

  boolean resumeFocusedStackTopActivityLocked(
            ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {

        if (!readyToResume()) {
            return false;
        }

        if (targetStack != null && isFocusedStack(targetStack)) {
            //15 进去,走上一个Activity的onPause方法
            return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
        }

        final ActivityRecord r = mFocusedStack.topRunningActivityLocked();
        if (r == null || !r.isState(RESUMED)) {
            mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
        } else if (r.isState(RESUMED)) {
            // Kick off any lingering app transitions form the MoveTaskToFront operation.
            mFocusedStack.executeAppTransition(targetOptions);
        }

        return false;
    }

15 ActivityStack的resumeTopActivityUncheckedLocked方法

  @GuardedBy("mService")
    boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
    
    省略代码...
    
    //16 进去
    result = resumeTopActivityInnerLocked(prev, options);

    省略代码...

    return result;
    }

16 ActivityStack的resumeTopActivityInnerLocked方法

 private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
 
 省略代码...
 
 //将发起者置于Pause状态,也就是MainActivity改成onPause状态
 boolean pausing = mStackSupervisor.pauseBackStacks(userLeaving, next, false);
 
 省略代码...
  
 //17 进去
 mStackSupervisor.startSpecificActivityLocked(next, true, true);
      
 省略代码...
 
 }

17 ActivityStackSupervisor的startSpecificActivityLocked方法

这是一个非常重要的方法
首先查看要启动的Activity所在的应用进程是否已经启动,从而产生两个分支

  1. 如果目标APP已经启动,走热启动流程
  2. 如果目标APP还没启动,走冷启动流程
    void startSpecificActivityLocked(ActivityRecord r,
            boolean andResume, boolean checkConfig) {
        // Is this activity's application already running?
        //查看要启动的Activity所在的应用进程是否已经启动
        ProcessRecord app = mService.getProcessRecordLocked(r.processName,
                r.info.applicationInfo.uid, true);

        getLaunchTimeTracker().setLaunchTime(r);

        //如果这个app已经启动
        if (app != null && app.thread != null) {
            try {
                if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
                        || !"android".equals(r.info.packageName)) {
                    // Don't add this if it is a platform component that is marked
                    // to run in multiple processes, because this is actually
                    // part of the framework so doesn't make sense to track as a
                    // separate apk in the process.
                    app.addPackage(r.info.packageName, r.info.applicationInfo.longVersionCode,
                            mService.mProcessStats);
                }
                //18 热启动,进去
                realStartActivityLocked(r, app, andResume, checkConfig);
                return;
            } catch (RemoteException e) {
                Slog.w(TAG, "Exception when starting activity "
                        + r.intent.getComponent().flattenToShortString(), e);
            }

            // If a dead object exception was thrown -- fall through to
            // restart the application.
        }
        //如果app没有启动,冷启动
        mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
                "activity", r.intent.getComponent(), false, false, true);
    }

我们先假设目标APP已经启动,走热启动流程

Launcher请求AMS阶段

热启动流程

18 ActivityStackSupervisor的realStartActivityLocked方法

    final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
            boolean andResume, boolean checkConfig) throws RemoteException {
            
                省略代码...
                
                // Create activity launch transaction.
                final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread,
                        r.appToken);
                //这里传递的就是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, app.repProcState, r.icicle,
                        r.persistentState, results, newIntents, mService.isNextTransitionForward(),
                        profilerInfo));
                        
                省略代码...        
                 
                // Schedule transaction.
                //19 进去
                mService.getLifecycleManager().scheduleTransaction(clientTransaction);

        省略代码... 
          
        return true;
    }

19 ClientLifecycleManager的scheduleTransaction方法

  void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
        final IApplicationThread client = transaction.getClient();
        //20 进去
        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();
        }
    }

20 ClientTransaction的schedule方法

    public void schedule() throws RemoteException {
        //21 进去
        mClient.scheduleTransaction(this);
    }

这里的mClient是抽象类IApplicationThread,实现类是ApplicationThread。
mClient实际上是APP传过来的代理对象ApplicationThread

private class ApplicationThread extends IApplicationThread.Stub 

同时,ApplicationThread是ActivityThread的内部类
所以我们跳转到

21 ActivityThread的内部类ApplicationThread的scheduleTransaction方法

        @Override
        public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
            //22 进去
            ActivityThread.this.scheduleTransaction(transaction);
        }

到了这里,有些小朋友就不知道怎么走了,因为ActivityThread并没有scheduleTransaction方法
我们注意到ActivityThread 继承了ClientTransactionHandler

public final class ActivityThread extends ClientTransactionHandler {

所以下一步应该跳转到

22 ClientTransactionHandler的scheduleTransaction方法

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

23 ActivityThread的sendMessage方法

    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);
    }

我们注意到,这里给Handler发了一个消息,这是为什么呢?
因为ApplicationThread是一个Binder对象,处于子线程。ActivityThread则处于主线程。
现在要从ApplicationThread切换到ActivityThread,需要进行线程切换,进行线程切换使用Handler,所以给Handler发了一条消息ActivityThread.H.EXECUTE_TRANSACTION。
我们点进去ActivityThread.H.EXECUTE_TRANSACTION,发现这条消息是在ActivityThread的成员变量Handler H里处理的。

24 ActivityThread内部的Handler H的handleMessage方法

   //24
   case EXECUTE_TRANSACTION:
         final ClientTransaction transaction = (ClientTransaction) msg.obj;
         //25 进入
         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;

25 TransactionExecutor的execute方法

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

26 TransactionExecutor的executeCallbacks方法

    @VisibleForTesting
    public void executeCallbacks(ClientTransaction transaction) {
    
    省略代码...
    
        final int size = callbacks.size();
        for (int i = 0; i < size; ++i) {
        
            省略代码...
           
            //这里的item是ClientTransactionItem,ClientTransactionItem是抽象类
            //这里的item实际上是ClientTransactionItem的实现类LaunchActivityItem
            //证据在ActivityStackSupervisor.realstartActivityLocked的clientTransaction.addCallback
            //27 进去
            item.execute(mTransactionHandler, token, mPendingActions);
            item.postExecute(mTransactionHandler, token, mPendingActions);
            
            省略代码...         
            
        }
    }

27 LaunchActivityItem的execute方法

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

28 ActivityThread的handleLaunchActivity方法

    @Override
    public Activity handleLaunchActivity(ActivityClientRecord r,
            PendingTransactionActions pendingActions, Intent customIntent) {
            
    省略代码...
 
    //29 进去
    final Activity a = performLaunchActivity(r, customIntent);

    省略代码...
    
    }

29 ActivityThread的performLaunchActivity方法

    private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    
        省略代码...
        
        Activity activity = null;
        try {
            java.lang.ClassLoader cl = appContext.getClassLoader();
            //通过反射创建Activity
            //hook Activity的时候会用到这里
            activity = mInstrumentation.newActivity(
                    cl, component.getClassName(), r.intent);
            StrictMode.incrementExpectedActivityCount(activity.getClass());
            r.intent.setExtrasClassLoader(cl);
            r.intent.prepareToEnterProcess();
            if (r.state != null) {
                r.state.setClassLoader(cl);
            }
        } catch (Exception e) {
            if (!mInstrumentation.onException(activity, e)) {
                throw new RuntimeException(
                    "Unable to instantiate activity " + component
                    + ": " + e.toString(), e);
            }
        }

        try {
            //拿到Application
            Application app = r.packageInfo.makeApplication(false, mInstrumentation);

            省略代码...

                activity.mCalled = false;
                if (r.isPersistable()) {
                    //30 进去 走生命周期Activity的OnCreate
                    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
                } else {
                    mInstrumentation.callActivityOnCreate(activity, r.state);
                }
                
            省略代码...
            
            }
            
            省略代码...
            
        } catch (Exception e) {
        
          省略代码...
          
        }

        return activity;
    }

30 Instrumentation的callActivityOnCreate方法

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

31 Activity的performCreate方法

    final void performCreate(Bundle icicle) {
        performCreate(icicle, null);
    }

32 Activity的onCreate方法

    final void performCreate(Bundle icicle, PersistableBundle persistentState) {
        mCanEnterPictureInPicture = true;
        restoreHasCurrentPermissionRequest(icicle);
        if (persistentState != null) {
            //32 进去
            onCreate(icicle, persistentState);
        } else {
            onCreate(icicle);
        }
        writeEventLog(LOG_AM_ON_CREATE_CALLED, "performCreate");
        mActivityTransitionState.readState(icicle);

        mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
                com.android.internal.R.styleable.Window_windowNoDisplay, false);
        mFragments.dispatchActivityCreated();
        mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
    }

走到这里,我们APP已经创建完成了。
但是这条是热启动(APP已经启动)的分支。
下面介绍冷启动的分支:AMS向Zygote请求创建目标应用进程,成功创建目标应用进程后,走热启动流程。

冷启动流程

我们回到

17 ActivityStackSupervisor的startSpecificActivityLocked方法

这是一个非常重要的方法
在这个方法里会查看要启动的Activity所在的应用进程是否已经启动,从而产生两个分支

  1. 如果目标APP已经启动,走热启动流程
  2. 如果目标APP还没启动,走冷启动流程
    void startSpecificActivityLocked(ActivityRecord r,
            boolean andResume, boolean checkConfig) {
        // Is this activity's application already running?
        //查看要启动的Activity所在的应用进程是否已经启动
        ProcessRecord app = mService.getProcessRecordLocked(r.processName,
                r.info.applicationInfo.uid, true);

        getLaunchTimeTracker().setLaunchTime(r);

        //如果这个app已经启动
        if (app != null && app.thread != null) {
            try {
                if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
                        || !"android".equals(r.info.packageName)) {
                    // Don't add this if it is a platform component that is marked
                    // to run in multiple processes, because this is actually
                    // part of the framework so doesn't make sense to track as a
                    // separate apk in the process.
                    app.addPackage(r.info.packageName, r.info.applicationInfo.longVersionCode,
                            mService.mProcessStats);
                }
                //如果这个app已经启动,就打开目标app的Activity。
                //18 进去,热启动流程
                realStartActivityLocked(r, app, andResume, checkConfig);
                return;
            } catch (RemoteException e) {
                Slog.w(TAG, "Exception when starting activity "
                        + r.intent.getComponent().flattenToShortString(), e);
            }

            // If a dead object exception was thrown -- fall through to
            // restart the application.
        }
        //如果app没有启动,冷启动。
        //使用Socket通信向Zygote进程请求创建目标应用进程,创建成功后,走热启动流程。
        mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
                "activity", r.intent.getComponent(), false, false, true);
    }

这一次我们走冷启动的分支,所以进入

ActivityManagerService的startProcessLocked方法

    final ProcessRecord startProcessLocked(String processName,
            ApplicationInfo info, boolean knownToBeDead, int intentFlags,
            String hostingType, ComponentName hostingName, boolean allowWhileBooting,
            boolean isolated, boolean keepIfLarge) {
        //进去
        return startProcessLocked(processName, info, knownToBeDead, intentFlags, hostingType,
                hostingName, allowWhileBooting, isolated, 0 /* isolatedUid */, keepIfLarge,
                null /* ABI override */, null /* entryPoint */, null /* entryPointArgs */,
                null /* crashHandler */);
    }
    final ProcessRecord startProcessLocked(String processName, ApplicationInfo info,
            boolean knownToBeDead, int intentFlags, String hostingType, ComponentName hostingName,
            boolean allowWhileBooting, boolean isolated, int isolatedUid, boolean keepIfLarge,
            String abiOverride, String entryPoint, String[] entryPointArgs, Runnable crashHandler) {
            
        省略代码...
        
        //进去
        final boolean success = startProcessLocked(app, hostingType, hostingNameStr, abiOverride);
        
        省略代码...
        
        return success ? app : null;
    }

ActivityManagerService的startProcessLocked方法

    @GuardedBy("this")
    private final boolean startProcessLocked(ProcessRecord app,
            String hostingType, String hostingNameStr, String abiOverride) {
        //进去
        return startProcessLocked(app, hostingType, hostingNameStr,
                false /* disableHiddenApiChecks */, abiOverride);
    }
    private final boolean startProcessLocked(ProcessRecord app, String hostingType,
            String hostingNameStr, boolean disableHiddenApiChecks, String abiOverride) {
            
         省略代码...
         
         //进去
         final ProcessStartResult startResult = startProcess(app.hostingType, entryPoint,
                            app, app.startUid, gids, runtimeFlags, mountExternal, app.seInfo,
                            requiredAbi, instructionSet, invokeWith, app.startTime);
                            
         省略代码...        
            
            }

ActivityManagerService的startProcess方法

    private ProcessStartResult startProcess(String hostingType, String entryPoint,
            ProcessRecord app, int uid, int[] gids, int runtimeFlags, int mountExternal,
            String seInfo, String requiredAbi, String instructionSet, String invokeWith,
            long startTime) {
        try {
            Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "Start proc: " +
                    app.processName);
            checkTime(startTime, "startProcess: asking zygote to start proc");
            final ProcessStartResult startResult;
            if (hostingType.equals("webview_service")) {
                //如果要启动的进程是Web进程
                startResult = startWebView(entryPoint,
                        app.processName, uid, uid, gids, runtimeFlags, mountExternal,
                        app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
                        app.info.dataDir, null,
                        new String[] {PROC_START_SEQ_IDENT + app.startSeq});
            } else {
                //不是Web进程,进去
                startResult = Process.start(entryPoint,
                        app.processName, uid, uid, gids, runtimeFlags, mountExternal,
                        app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
                        app.info.dataDir, invokeWith,
                        new String[] {PROC_START_SEQ_IDENT + app.startSeq});
            }
            checkTime(startTime, "startProcess: returned from zygote!");
            return startResult;
        } finally {
            Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        }
    }

Process的start方法

    public static final ProcessStartResult start(final String processClass,
                                  final String niceName,
                                  int uid, int gid, int[] gids,
                                  int runtimeFlags, int mountExternal,
                                  int targetSdkVersion,
                                  String seInfo,
                                  String abi,
                                  String instructionSet,
                                  String appDataDir,
                                  String invokeWith,
                                  String[] zygoteArgs) {
        //进去
        return zygoteProcess.start(processClass, niceName, uid, gid, gids,
                    runtimeFlags, mountExternal, targetSdkVersion, seInfo,
                    abi, instructionSet, appDataDir, invokeWith, zygoteArgs);
    }

ZygoteProcess的start方法

    public final Process.ProcessStartResult start(final String processClass,
                                                  final String niceName,
                                                  int uid, int gid, int[] gids,
                                                  int runtimeFlags, int mountExternal,
                                                  int targetSdkVersion,
                                                  String seInfo,
                                                  String abi,
                                                  String instructionSet,
                                                  String appDataDir,
                                                  String invokeWith,
                                                  String[] zygoteArgs) {
        try {
            //进去
            return startViaZygote(processClass, niceName, uid, gid, gids,
                    runtimeFlags, mountExternal, targetSdkVersion, seInfo,
                    abi, instructionSet, appDataDir, invokeWith, false /* startChildZygote */,
                    zygoteArgs);
        } catch (ZygoteStartFailedEx ex) {
            Log.e(LOG_TAG,
                    "Starting VM process through Zygote failed");
            throw new RuntimeException(
                    "Starting VM process through Zygote failed", ex);
        }
    }

ZygoteProcess的startViaZygote方法

    private Process.ProcessStartResult startViaZygote(final String processClass,
                                                      final String niceName,
                                                      final int uid, final int gid,
                                                      final int[] gids,
                                                      int runtimeFlags, int mountExternal,
                                                      int targetSdkVersion,
                                                      String seInfo,
                                                      String abi,
                                                      String instructionSet,
                                                      String appDataDir,
                                                      String invokeWith,
                                                      boolean startChildZygote,
                                                      String[] extraArgs)
                                                      throws ZygoteStartFailedEx {
                                                      
         省略代码...
         
        synchronized(mLock) {
            //进去,这个是阻塞函数
            return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi), argsForZygote);
        }
    }

ZygoteProcess的zygoteSendArgsAndGetResult方法

AMS在这个方法里与Zygote进行Socket通信(请求Zygote创建目标应用进程),并接收结果。

    private static Process.ProcessStartResult zygoteSendArgsAndGetResult(
            ZygoteState zygoteState, ArrayList<String> args)
            throws ZygoteStartFailedEx {
        try {
            
            省略代码...
            
            final BufferedWriter writer = zygoteState.writer;
            final DataInputStream inputStream = zygoteState.inputStream;

            writer.write(Integer.toString(args.size()));
            writer.newLine();

            //Socket通信,把内容写进去,发送给Zygote
            for (int i = 0; i < sz; i++) {
                String arg = args.get(i);
                writer.write(arg);
                writer.newLine();
            }

            writer.flush();

            // Should there be a timeout on this?
            //接收结果
            Process.ProcessStartResult result = new Process.ProcessStartResult();

            // Always read the entire result from the input stream to avoid leaving
            // bytes in the stream for future process starts to accidentally stumble
            // upon.
            result.pid = inputStream.readInt();
            result.usingWrapper = inputStream.readBoolean();

            if (result.pid < 0) {
                throw new ZygoteStartFailedEx("fork() failed");
            }
            return result;
        } catch (IOException ex) {
            zygoteState.close();
            throw new ZygoteStartFailedEx(ex);
        }
    }

这个socket通信在哪里建立连接的呢?
我们回到上一步的
ZygoteProcess的startViaZygote方法

    private Process.ProcessStartResult startViaZygote(final String processClass,
                                                      final String niceName,
                                                      final int uid, final int gid,
                                                      final int[] gids,
                                                      int runtimeFlags, int mountExternal,
                                                      int targetSdkVersion,
                                                      String seInfo,
                                                      String abi,
                                                      String instructionSet,
                                                      String appDataDir,
                                                      String invokeWith,
                                                      boolean startChildZygote,
                                                      String[] extraArgs)
                                                      throws ZygoteStartFailedEx {
                                                      
         省略代码...
         
        synchronized(mLock) {
                                                //这次我们进去这个方法
            return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi), argsForZygote);
        }
    }

这一次我们进入openZygoteSocketIfNeeded方法

 private ZygoteState openZygoteSocketIfNeeded(String abi) throws ZygoteStartFailedEx {
        Preconditions.checkState(Thread.holdsLock(mLock), "ZygoteProcess lock not held");
        
        省略代码...
        
        //进去
        primaryZygoteState = ZygoteState.connect(mSocket);
            
        省略代码...
        
    }

ZygoteState的connect方法

        public static ZygoteState connect(LocalSocketAddress address) throws IOException {
            DataInputStream zygoteInputStream = null;
            BufferedWriter zygoteWriter = null;
            //创建一个LocalSocket
            final LocalSocket zygoteSocket = new LocalSocket();

            try {
                //调用LocalSocket的connect方法,并把地址传进去,与Zygote建立Socket通信
                //进去,ZygoteInit.java的main方法
                zygoteSocket.connect(address);

                zygoteInputStream = new DataInputStream(zygoteSocket.getInputStream());

                zygoteWriter = new BufferedWriter(new OutputStreamWriter(
                        zygoteSocket.getOutputStream()), 256);
            } catch (IOException ex) {
                try {
                    zygoteSocket.close();
                } catch (IOException ignore) {
                }

                throw ex;
            }

            省略代码...
            
        }

调用zygoteSocket.connect(address)进行socket连接后,会回调ZygoteInit的main方法

ZygoteInit的main方法

    public static void main(String argv[]) {
            //首先创建Zygote服务器
            ZygoteServer zygoteServer = new ZygoteServer();
 
            省略代码...
            
            //注册Socket
            zygoteServer.registerServerSocketFromEnv(socketName);
            
            省略代码...
            
            //进去,在里面fork出目标应用进程
            caller = zygoteServer.runSelectLoop(abiList);
        } catch (Throwable ex) {
            Log.e(TAG, "System zygote died with exception", ex);
            throw ex;
        } finally {
            zygoteServer.closeServerSocket();
        }

        // We're in the child process and have exited the select loop. Proceed to execute the
        // command.
        if (caller != null) {
            //启动上面创建的应用进程
            caller.run();
        }
    }

ZygoteServer的runSelectLoop方法

    Runnable runSelectLoop(String abiList) {
    
       省略代码...

        while (true) {
        
            省略代码...
            
            for (int i = pollFds.length - 1; i >= 0; --i) {
            
                  省略代码...
         
                    try {
                        //通过for循环不断取出AMS的连接
                        ZygoteConnection connection = peers.get(i);
                        //在这里fork出我们要启动的应用进程
                        final Runnable command = connection.processOneCommand(this);
                        
                        省略代码...
                        
                        }
                    } catch (Exception e) {
                    
                        省略代码...
                        
                        }
                    } finally {
                        mIsForkChild = false;
                    }
                }
            }
        }
    }

到这里我们创建并启动了目标应用进程。
当Zygote收到AMS的请求,创建出一个新的app进程后,会调用ActivityThread的main方法。

ActivityThread的main方法

    public static void main(String[] args) {
    
         省略代码...
         
         //准备主线程的Looper
         Looper.prepareMainLooper();

         省略代码...
         
        //new 一个ActivityThread
        //注意:ActivityThread不是线程,ActivityThread只是会跑在UI主线程里面
        ActivityThread thread = new ActivityThread();
        //当应用进程被创建完成的时候,走attach流程,通知AMS,并把自己的代理对象传给AMS
        //进入
        thread.attach(false, startSeq);

        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }

        省略代码...
        
        Looper.loop();

        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

ActivityThread的attach方法

  private void attach(boolean system, long startSeq) {
  
  省略代码...

  //获取AMS的代理对象
  final IActivityManager mgr = ActivityManager.getService();
  try {
      //调用IActivityManager的attachApplication,把APP的代理对象ActivityThread传给AMS
      //进入
      mgr.attachApplication(mAppThread, startSeq);
      } catch (RemoteException ex) {
         throw ex.rethrowFromSystemServer();
      }

  省略代码...
  
  }

ActivityManagerService的attachApplication方法

    @Override
    public final void attachApplication(IApplicationThread thread, long startSeq) {
        synchronized (this) {
            //这里体现了Binder通信的优势:天然的带有调用者的身份信息uid,安全
            //获取调用端的pid
            int callingPid = Binder.getCallingPid();
            //获取调用端的uid
            final int callingUid = Binder.getCallingUid();
            //把pid/uid设置为AMS的
            final long origId = Binder.clearCallingIdentity();
            //进入
            attachApplicationLocked(thread, callingPid, callingUid, startSeq);
            //恢复成APP的
            Binder.restoreCallingIdentity(origId);
        }
    }

ActivityManagerService的attachApplicationLocked方法

    private final boolean attachApplicationLocked(IApplicationThread thread,
            int pid, int callingUid, long startSeq) {
            
                 省略代码...

                //以上代码创建Application对象
                //thread是IApplicationThread,APP传给AMS的代理对象,IApplicationThread的实现类是ActivityThread
                //所以实际调用了ActivityThread的bindApplication方法
                thread.bindApplication(processName, appInfo, providers,
                        app.instr.mClass,
                        profilerInfo, app.instr.mArguments,
                        app.instr.mWatcher,
                        app.instr.mUiAutomationConnection, testMode,
                        mBinderTransactionTrackingEnabled, enableTrackAllocation,
                        isRestrictedBackupMode || !normalMode, app.persistent,
                        new Configuration(getGlobalConfiguration()), app.compat,
                        getCommonServicesLocked(app.isolated),
                        mCoreSettingsObserver.getCoreSettingsLocked(),
                        buildSerial, isAutofillCompatEnabled);

                 省略代码...
                 
            try {
                //目标APP进程启动完成后,进入这里,走热启动流程。
                if (mStackSupervisor.attachApplicationLocked(app)) {
                    didSomething = true;
                }
            } catch (Exception e) {
                Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
                badApp = true;
            }
            
             省略代码...
             
            }

ActivityThread的bindApplication方法

        public final void bindApplication(String processName, ApplicationInfo appInfo,
                List<ProviderInfo> providers, ComponentName instrumentationName,
                ProfilerInfo profilerInfo, Bundle instrumentationArgs,
                IInstrumentationWatcher instrumentationWatcher,
                IUiAutomationConnection instrumentationUiConnection, int debugMode,
                boolean enableBinderTracking, boolean trackAllocation,
                boolean isRestrictedBackupMode, boolean persistent, Configuration config,
                CompatibilityInfo compatInfo, Map services, Bundle coreSettings,
                String buildSerial, boolean autofillCompatibilityEnabled) {
                
             省略代码...
             
            //进入
            sendMessage(H.BIND_APPLICATION, data);
        }

这里也是给Handler发消息,原因上面已经说过了,ApplicationThread是Binder对象处于子线程,ActivityThread位于主线程,从ApplicationThread跳转到ActivityThread需要进行线程切换,使用Handler
我们点击H.BIND_APPLICATION来到处理这条消息的地方:

ActivityThread内部的Handler H的handleMessage方法

                case BIND_APPLICATION:
                    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication");
                    AppBindData data = (AppBindData)msg.obj;
                    //进入
                    handleBindApplication(data);
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                    break;

ActivityThread的handleBindApplication方法

    private void handleBindApplication(AppBindData data) {
        // Register the UI Thread as a sensitive thread to the runtime.
        //把UI线程注册为运行时的虚拟机
        VMRuntime.registerSensitiveThread();
        
       省略代码...
             
       //在这里创建Application
       app = data.info.makeApplication(data.restrictedBackupMode, null);
       
       省略代码...
       
       //如果有则初始化ContentProvider
       installContentProviders(app, data.providers);
       
       省略代码...
       
          try {
                //回调Application的onCreate
                //进入
                mInstrumentation.callApplicationOnCreate(app);
            } catch (Exception e) {
                if (!mInstrumentation.onException(app, e)) {
                    throw new RuntimeException(
                      "Unable to create application " + app.getClass().getName()
                      + ": " + e.toString(), e);
                }
            }
            
        省略代码...
        
        }
        

Instrumentation的callApplicationOnCreate方法

    public void callApplicationOnCreate(Application app) {
        //回调Application的onCreate方法
        app.onCreate();
    }

到这里我们成功创建了目标app进程,接下来走热启动流程,让我们回到

ActivityManagerService的attachApplicationLocked方法

    private final boolean attachApplicationLocked(IApplicationThread thread,
            int pid, int callingUid, long startSeq) {
            
                 省略代码...

                //创建APP进程的流程
                thread.bindApplication(processName, appInfo, providers,
                        app.instr.mClass,
                        profilerInfo, app.instr.mArguments,
                        app.instr.mWatcher,
                        app.instr.mUiAutomationConnection, testMode,
                        mBinderTransactionTrackingEnabled, enableTrackAllocation,
                        isRestrictedBackupMode || !normalMode, app.persistent,
                        new Configuration(getGlobalConfiguration()), app.compat,
                        getCommonServicesLocked(app.isolated),
                        mCoreSettingsObserver.getCoreSettingsLocked(),
                        buildSerial, isAutofillCompatEnabled);

                 省略代码...
                 
            try {
                //这次我们走这里
                //目标APP进程启动完成后,进入这里,走热启动流程。
                if (mStackSupervisor.attachApplicationLocked(app)) {
                    didSomething = true;
                }
            } catch (Exception e) {
                Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
                badApp = true;
            }
            
             省略代码...
             
            }

ActivityStackSupervisor的attachApplicationLocked方法

    boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
    
                //省略代码...
                
                for (int i = 0; i < size; i++) {
                    final ActivityRecord activity = mTmpActivityList.get(i);
                    if (activity.app == null && app.uid == activity.info.applicationInfo.uid
                            && processName.equals(activity.processName)) {
                        try {
                            //大家注意这个方法
                            if (realStartActivityLocked(activity, app,
                                    top == activity /* andResume */, true /* checkConfig */)) {
                                didSomething = true;
                            }
                        } catch (RemoteException e) {
                            Slog.w(TAG, "Exception in new application when starting activity "
                                    + top.intent.getComponent().flattenToShortString(), e);
                            throw e;
                        }
                    }
                }
            }
        }
        if (!didSomething) {
            ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
        }
        return didSomething;
    }

这个realStartActivityLocked方法是不是很熟悉?
没错,这个就是热启动流程的入口方法!
热启动流程上面已经讲过,下面不再赘述了。

最后再总结一下冷启动流程:使用Socket通信向Zygote请求创建目标应用进程,然后走热启动流程来启动Activity。

权限验证

Binder通信天然的带有调用者的信息uid,用于验证调用者是否有权限、有资格调用被调用者,更安全。
ActivityManagerService的attachApplication方法

    @Override
    public final void attachApplication(IApplicationThread thread, long startSeq) {
        synchronized (this) {
            //这里体现了Binder通信的优势:天然的带有调用者的身份信息uid,安全
            //获取调用端的pid
            int callingPid = Binder.getCallingPid();
            //获取调用端的uid
            final int callingUid = Binder.getCallingUid();
            //把pid/uid设置为AMS自身的
            //origId是调用端的pid和uid组合而成的token,用于下面的恢复。
            final long origId = Binder.clearCallingIdentity();
            //进入
            attachApplicationLocked(thread, callingPid, callingUid, startSeq);
            //恢复成APP的
            Binder.restoreCallingIdentity(origId);
        }
    }

这几个方法是Native方法,实现于\frameworks\native\libs\binder\IPCThreadState.cpp文件。
APP启动流程分析(下)_第5张图片
APP启动流程分析(下)_第6张图片
总结起来,ActivityManagerService的attachApplication方法做了这几件事

  1. 取出APP的id
  2. 把Binder的id设置为AMS的
  3. 做一些操作(attachApplicationLocked方法)
  4. 把Binder的id恢复成APP的

为什么要这样做呢?
因为attachApplicationLocked方法里面做了一些验证,如果Binder的id不是AMS的id,验证不通过。

面试的时候如何回答startActivity流程?

把下图描述出来即可。
APP启动流程分析(下)_第7张图片

  1. Launcher如何跟AMS通信的?
  2. AMS发现目标应用进程没有创建的时候,是如何创建应用进程的?
  3. Zygote如何fork出我们的app进程的?
  4. app被fork出来后,是如何跟AMS通信的?

你可能感兴趣的:(Android启动流程,源码分析,移动开发,android)