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

2020-09-18  本文已影响0人  leap_
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());
    }

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

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()中,主要做了两件事:

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()主要处理与栈管理的相关逻辑:

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

步骤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);
        }
...
  }

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

处理消息的地方是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的核心实现方法,看代码:

    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);
                    }
                }
...
    }
上一篇 下一篇

猜你喜欢

热点阅读