Android进阶解密①——activity的启动过程

Activity的启动分为根activity启动和普通activity启动,根activity的启动过程包括了普通activity的启动过程,本文只介绍根activity的启动;

根Activity启动的整理流程:

  1. Launcher进程请求SystemServer进程的AMS
  2. AMS请求用户进程的ApplicationThread
  3. ApplicationThread请求ActivityThread,ActivityThread启动Activity

步骤1,Launcher请求AMS

Launcher进程 ~> AMS
在Launcher桌面点击应用图标会调用Launcher的startActivitySafely()
    boolean startActivitySafely(View v, Intent intent, Object tag) {
        boolean success = false;
        try {
            success = startActivity(v, intent, tag);
        }
        return success;
    }

  boolean startActivity(View v, Intent intent, Object tag) {
        //  分析1
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
        // 分析2
        startActivity(intent, opts.toBundle());
    }
  • 通过intent设置New Task的Flag,开启一个新的活动栈
  • 调用startActivity(),这个方法在Activity类中实现;

Activity:

startActivity()会调用startActivityForResult()

    public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
            @Nullable Bundle options) {
        if (mParent == null) {
            options = transferSpringboardActivityOptions(options);
            Instrumentation.ActivityResult ar =
                mInstrumentation.execStartActivity(
                    this, mMainThread.getApplicationThread(), mToken, this,
                    intent, requestCode, options);
        }    
    }

在Activity类中,将启动Activity的请求交给了Instrumentation类

Instrumentation:

    public ActivityResult execStartActivity(
            Context who, IBinder contextThread, IBinder token, Activity target,
            Intent intent, int requestCode, Bundle options) {

           int result = ActivityManager.getService()
                .startActivityAsUser(whoThread, who.getBasePackageName(), intent,
                        intent.resolveTypeIfNeeded(who.getContentResolver()),
                        token, resultWho,
                        requestCode, 0, null, options, user.getIdentifier());

    }

通过 ActivityManager.getService()拿到iActivityManager对象,iActivityManager是AMS在用户进程的代理,所以真实调用的其实是AMS的startActivityAsUser();
至此Launcher到AMS的流程分析完毕

步骤2,AMS到ApplicationThread

AMS ~> 用户进程

AMS:

    @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) {
            //  分析1
            userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
                userId, false, ALLOW_FULL_ONLY, "startActivity", null);

        return mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent,
                resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
                profilerInfo, null, null, bOptions, false, userId, null, null);
    }
  • 首先AMS会通过userId字段检查调用者的权限
  • 在AMS中调用了mActivityStarter的startActivityMayWait()

ActivityStarter:

    final 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, Bundle bOptions, boolean ignoreTargetSecurity, int userId,
            IActivityContainer iContainer, TaskRecord inTask, String reason) {
...
      //  分析1
       ProcessRecord callerApp = null;
       if (caller != null) { 
            callerApp = mService.getRecordForAppLocked(caller);
        }

           //  分析2
        ActivityRecord r = new ActivityRecord(mService, callerApp, callingPid, callingUid,
                callingPackage, intent, resolvedType, aInfo, mService.getGlobalConfiguration(),
                resultRecord, resultWho, requestCode, componentSpecified, voiceSession != null,
                mSupervisor, container, options, sourceRecord);

        return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags, true,
                options, inTask, outActivity);
    }

在Activity的第一个startActivity()中,主要做了两件事:

  • 通过AMS获取ProcessRecord对象,ProcessRecord用于记录调用者进程的信息;
  • 创建ActivityRecord对象,ActivityRecord用于记录启动Activity的信息,并传给下一个startActivity();
ActivityStarter的第二个startActivity()直接调用了startActivityUnchecked()

ActivityStarter.startActivityUnchecked():

    private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
            ActivityRecord[] outActivity) {
...
        // 分析1
        // Should this be considered a new task?
        int result = START_SUCCESS;
        if (mStartActivity.resultTo == null && mInTask == null && !mAddingToTask
                && (mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0) {
            newTask = true;
            result = setTaskFromReuseOrCreateNewTask(
                    taskToAffiliate, preferredLaunchStackId, topStack);
        } 
                  //分析2
                    mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity,
                        mOptions);
}

startActivityUnchecked()主要处理与栈管理的相关逻辑:

  • 通过intent的flag判断是否需要开启新的活动栈,如果条件满足,就会在setTaskFromReuseOrCreateNewTask()内部创建一个TaskRecord用来描述新的Activity任务栈;

  • 调用StackSupervisor.resumeFocusedStackTopActivityLocked();

StackSupervisor.resumeFocusedStackTopActivityLocked():
    boolean resumeFocusedStackTopActivityLocked(
            ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
        if (targetStack != null && isFocusedStack(targetStack)) {
            return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
        }
        //  分析1
        final ActivityRecord r = mFocusedStack.topRunningActivityLocked();
        if (r == null || r.state != RESUMED) {
            //  分析2
            mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
        } else if (r.state == RESUMED) {
            // Kick off any lingering app transitions form the MoveTaskToFront operation.
            mFocusedStack.executeAppTransition(targetOptions);
        }
        return false;
    }
  • 获取要启动的Activity信息(ActivityRecord)
  • 调用ActivityStack.resumeTopActivityUncheckedLocked();
ActivityStack.resumeTopActivityUncheckedLocked():
    boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
        boolean result = false;
        try {
            result = resumeTopActivityInnerLocked(prev, options);
        }
        return result;
    }


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

StackSupervisor.startSpecificActivityLocked():

   void startSpecificActivityLocked(ActivityRecord r,
            boolean andResume, boolean checkConfig) {
        //  分析1
        ProcessRecord app = mService.getProcessRecordLocked(r.processName,
                r.info.applicationInfo.uid, true);
                // 分析2
                realStartActivityLocked(r, app, andResume, checkConfig);
                return;
...
    }
  • 获取启动activity进程信息(ProcessRecord)
  • 调用realStartActivityLocked(), real start
StackSupervisor.realStartActivityLocked():
    final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
            boolean andResume, boolean checkConfig) throws RemoteException {
...
            app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
                    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, !andResume,
                    mService.isNextTransitionForward(), profilerInfo);
...
      }
  • 调用ProcessRecord的thread成员变量的scheduleLaunchActivity(),app.thread是用户进程的ApplicationThread在AMS进程的代理,实际调用的是用户进程的ApplicationThread.scheduleLaunchActivity()

步骤3,ApplicationThread通知ActivityThread启动Activity

ApplicationThread ~> ActivityThread

ApplicationThread

    private class ApplicationThread extends IApplicationThread.Stub {
...
        public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
                ActivityInfo info, Configuration curConfig, Configuration overrideConfig,
                CompatibilityInfo compatInfo, String referrer, IVoiceInteractor voiceInteractor,
                int procState, Bundle state, PersistableBundle persistentState,
                List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents,
                boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) {
...
            sendMessage(H.LAUNCH_ACTIVITY, r);
        }
...
  }
  • ApplicationThread是ActivityThread的一个内部类,这个类继承了aidl的Stub类,是一个Binder对象,用于和AMS进程的进程间通信,是AMS进程app.thread代理对象的真实对象;
  • ApplicationThread发送了一个主线程Handler消息,H

主线程的消息循环机制会处理到这个消息:

处理消息的地方是H的handleMessage里面,对应的处理逻辑:

        public void handleMessage(Message msg) {
            if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
            switch (msg.what) {
                case LAUNCH_ACTIVITY: {
                    final ActivityClientRecord r = (ActivityClientRecord) msg.obj;
                    r.packageInfo = getPackageInfoNoCheck(
                            r.activityInfo.applicationInfo, r.compatInfo);
                    handleLaunchActivity(r, null, "LAUNCH_ACTIVITY");
                } break;
        ...
    }


    private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
        //  分析1
        Activity a = performLaunchActivity(r, customIntent);
            //  分析2
            handleResumeActivity(r.token, false, r.isForward,
                    !r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);
        }
    }
  • 调用performLaunchActivity()创建activity对象,并做初始化操作:构建activity对象,构建Application对象,调用activity的onCreate,onStart()
  • 将activity的状态设置为resume;
performLaunchActivity():

这个方法超级重要,是启动Activity的核心实现方法,看代码:

    private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
...
            //  分析1
            Activity activity = null;
            java.lang.ClassLoader cl = appContext.getClassLoader();
            activity = mInstrumentation.newActivity(
                    cl, component.getClassName(), r.intent);

          //  分析2
           Application app = r.packageInfo.makeApplication(false, mInstrumentation);

             //   分析3
             mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);

             //   分析4
                if (!r.activity.mFinished) {
                    activity.performStart();
                    r.stopped = false;
                }

             //   分析5
                if (!r.activity.mFinished) {
                    if (r.isPersistable()) {
                        if (r.state != null || r.persistentState != null) {
                            mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
                                    r.persistentState);
                        }
                    } else if (r.state != null) {
                        mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
                    }
                }
...
    }
  • 通过ClassLoader创建一个Activity的实例
  • 尝试构建Application对象
  • 调用Activity的onCreate
  • 调用Activity的onStart
  • 判断是否需要调用RestoreInstanceState()恢复数据