当前位置:   article > 正文

Activity(一)—— Activity的启动流程_activity启动流程

activity启动流程

Activity 的启动过程分为两种:一种是根 Activity 的启动过程,另一种是普通 Activity 的启动过程。Activity 指的是应用程序启动的第一个 Activity,因此,根 Activity 的启动过程一般情况下也可以理解为应用程序的启动过程。 普通 Activity 指的是除应用程序启动的第一个 Activity 之外的其他 Activity

由于根 Activity 的启动过程比较复杂,以下分为三部分讲解:

  • Launcher 请求 AMS 过程;
  • AMSApplicationThread 的调用过程;
  • ActivityThread 启动 Activity

1 Launcher 请求 AMS 过程

Launcher 启动后会讲已安装应用程序的快捷图标显示到桌面上,这些应用程序的快捷图标就是启动根 Activity 的入口。当我们点击某个应用题程序的快捷图标时,就会通过 Launcher 请求 AMS 来启动应用程序。

以下是 Launcher 请求 AMS时序图

Launcher请求AMS的时序图

点击应用程序的快捷图标时,就会调用 Launcher.startActivitySafely 方法:

// /packages/apps/Launcher3/src/com/android/launcher3/Launcher.java
public boolean startActivitySafely(View v, Intent intent, ItemInfo item,
                                   @Nullable String sourceContainer) {
    ...
    boolean success = super.startActivitySafely(v, intent, item, sourceContainer); // 1
    ...
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

Launcher 继承自 BaseDraggingActivity,注释 1 处调用的 super.startActivitySafely 实际上调用的是 BaseDraggingActivity.startActivitySafely 方法:

// /packages/apps/Launcher3/src/com/android/launcher3/BaseDraggingActivity.java
public boolean startActivitySafely(View v, Intent intent, @Nullable ItemInfo item,
                                   @Nullable String sourceContainer) {
    ...
    // Prepare intent
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // 1
    if (v != null) {
        intent.setSourceBounds(getViewBounds(v));
    }
    try {
        ...
        if (isShortcut) {
            // Shortcuts need some special checks due to legacy reasons.
            startShortcutIntentSafely(intent, optsBundle, item, sourceContainer);
        } else if (user == null || user.equals(Process.myUserHandle())) {
            // Could be launching some bookkeeping activity
            if (TestProtocol.sDebugTracing) {
                android.util.Log.d(TestProtocol.NO_START_TAG, "startActivitySafely 2");
            }
            startActivity(intent, optsBundle); // 2
            AppLaunchTracker.INSTANCE.get(this).onStartApp(intent.getComponent(),
                                                           Process.myUserHandle(), 
                                                           sourceContainer);
        } else {
            ...
        }
        ...
    } catch (ActivityNotFoundException|SecurityException e) {
        ...
    }
    return false;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

在注释 1 处将 Flag 设置为 Intent.FLAG_ACTIVITY_NEW_TASK,这样根 Activity 会在新的任务栈中启动。在注释 2 处调用 startActivity 方法,这个 startActivity 方法在 Activity 中实现,这是因为 BaseDraggingActivity 继承自 BaseActivity,而 BaseActivity 继承自 Activity,以下是 Activity.startActivity 方法的源码:

// /frameworks/base/core/java/android/app/Activity.java
@Override
public void startActivity(Intent intent, @Nullable Bundle options) {
    if (options != null) {
        startActivityForResult(intent, -1, options); // 1
    } else {
        // Note we want to go through this call for compatibility with
        // applications that may have overridden the method.
        startActivityForResult(intent, -1); // 2
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

startActivity 方法中会调用 startActivityForResult 方法,它的第二个参数为 -1,表示 Launcher 不需要知道 Activity 启动的结果,startActivityForResult 的代码如下所示:

// /frameworks/base/core/java/android/app/Activity.java
@Override
@UnsupportedAppUsage
public void startActivityForResult(
    String who, Intent intent, int requestCode, @Nullable Bundle options) {
    Uri referrer = onProvideReferrer();
    if (referrer != null) {
        intent.putExtra(Intent.EXTRA_REFERRER, referrer);
    }
    options = transferSpringboardActivityOptions(options);
    Instrumentation.ActivityResult ar =
        mInstrumentation.execStartActivity(
        this, mMainThread.getApplicationThread(), mToken, who,
        intent, requestCode, options); // 1
    if (ar != null) {
        mMainThread.sendActivityResult(
            mToken, who, requestCode,
            ar.getResultCode(), ar.getResultData());
    }
    cancelInputsAndStartExitTransition(options);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

注释 1 处调用 Instrumentation.execStartActivity 方法,Instrumentation 主要用来监控应用程序和系统的交互,Instrumentation.execStartActivity 方法的代码如下所示:

// /frameworks/base/core/java/android/app/Instrumentation.java
@UnsupportedAppUsage
public ActivityResult execStartActivity(
    Context who, IBinder contextThread, IBinder token, String target,
    Intent intent, int requestCode, Bundle options) {
    ...
    try {
        intent.migrateExtraStreamToClipData();
        intent.prepareToLeaveProcess(who);
        int result = ActivityTaskManager.getService()
            .startActivity(whoThread, who.getBasePackageName(), intent,
                           intent.resolveTypeIfNeeded(who.getContentResolver()),
                           token, target, requestCode, 0, null, options); // 1
        checkStartActivityResult(result, intent);
    } catch (RemoteException e) {
        throw new RuntimeException("Failure from system", e);
    }
    return null;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

注释 1 处首先调用 ActivityTaskManager.getService() 方法获取 ActivityManagerService 实例,接着调用它的 startActivity 方法,首先来看一下 ActivityTaskManager.getService 方法做了什么:

// /frameworks/base/core/java/android/app/ActivityTaskManager.java
public static IActivityTaskManager getService() {
    return IActivityTaskManagerSingleton.get();
}

@UnsupportedAppUsage(trackingBug = 129726065)
private static final Singleton<IActivityTaskManager> IActivityTaskManagerSingleton =
    new Singleton<IActivityTaskManager>() {
    @Override
    protected IActivityTaskManager create() {
        final IBinder b = ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE); // 1
        return IActivityTaskManager.Stub.asInterface(b); // 2
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

ActivityTaskManager.getService() 方法调用了 IActivityTaskManagerSingleton.get() 方法。IActivityTaskManagerSingleton 是一个 Singleton 类,在注释 1 处得到 activity_taskService 引用,也就是 IBinder 类型的 AMS 引用。接着在注释 2 处将它转换成 IActivityTaskManager 类型的对象,这段代码采用的是 AIDLIActivityManager.java 类是由 AIDL 工具在编译时自动生成的,IActivityManager.aidl 的文件路径为 frameworks/base/core/java/android/app/IActivityManager.aidl。要实现进程间通信,服务器端也就是 AMS 只需要继承 IActivityManager.Stub 类并且实现相应的方法就可以了。

2 AMSApplicationThread 的调用过程

Launcher 请求 AMS 后,代码逻辑已经进入到 AMS 中,接着是 AMSApplicationThread 的调用流程:

AMS到ApplicationThread的调用过程

ActivityManagerService.startActivity 方法如下所示:

// /frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
@Override
public int startActivity(IApplicationThread caller, String callingPackage,
                         Intent intent, String resolvedType, IBinder resultTo, 
                         String resultWho, int requestCode,
                         int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
    return mActivityTaskManager.startActivity(caller, callingPackage, intent, resolvedType,
                                              resultTo, resultWho, requestCode, startFlags, 
                                              profilerInfo, bOptions); // 1
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

在注释 1 处调用的是 ActivityTaskManagerService.startActivity 方法:

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

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

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("startActivityAsUser"); // 2 判断调用者进程是否被隔离
	// 3 检查调用者权限
    userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
                                                          Binder.getCallingPid(), 
                                                          Binder.getCallingUid(), 
                                                          "startActivityAsUser"); 

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

}

ActivityStartController getActivityStartController() {
    return mActivityStartController;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51

注释 1 处 的ActivityTaskManagerService.startActivity 方法中调用了 ActivityTaskManagerService.startActivityAsUser 方法,后者比前者多了一个参数 UserHandle.getCallingUserId(),这个方法或获得调用着的 UserIdActivityManagerService 根据这个 UserId 来确定调用着的权限。

注释 2 处判断调用着进程是否被隔离。注释 3 处检查调用着是否有权限。注释 4getActivityStartController 方法返回的是 ActivityStartController 实例,ActivityStartController.obtainStarter 方法返回的是 ActivityStarter 实例,其中参数 startActivityAsUser 代表启动的理由:

// /frameworks/base/services/core/java/com/android/server/wm/ActivityStartController.java
ActivityStarter obtainStarter(Intent intent, String reason) {
    return mFactory.obtain().setIntent(intent).setReason(reason);
}
  • 1
  • 2
  • 3
  • 4

以下是 ActivityStarter.execute 相关代码:

// /frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java
int execute() {
    try {
        // TODO(b/64750076): Look into passing request directly to these methods to allow
        // for transactional diffs and preprocessing.
        if (mRequest.mayWait) {
            return startActivityMayWait(mRequest.caller, mRequest.callingUid,
                                        mRequest.callingPackage, mRequest.realCallingPid, 
                                        mRequest.realCallingUid, mRequest.intent, 
                                        mRequest.resolvedType, mRequest.voiceSession, 
                                        mRequest.voiceInteractor, mRequest.resultTo,
                                        mRequest.resultWho, mRequest.requestCode, 
                                        mRequest.startFlags, mRequest.profilerInfo, 
                                        mRequest.waitResult, mRequest.globalConfig,
                                        mRequest.activityOptions, mRequest.ignoreTargetSecurity, 
                                        mRequest.userId, mRequest.inTask, mRequest.reason,
                                        mRequest.allowPendingRemoteAnimationRegistryLookup,
                                        mRequest.originatingPendingIntent, 
                                        mRequest.allowBackgroundActivityStart);
        } else {
            return startActivity(mRequest.caller, mRequest.intent, mRequest.ephemeralIntent,
                                 mRequest.resolvedType, mRequest.activityInfo, 
                                 mRequest.resolveInfo, mRequest.voiceSession, 
                                 mRequest.voiceInteractor, mRequest.resultTo,
                                 mRequest.resultWho, mRequest.requestCode, mRequest.callingPid,
                                 mRequest.callingUid, mRequest.callingPackage, 
                                 mRequest.realCallingPid, mRequest.realCallingUid, 
                                 mRequest.startFlags, mRequest.activityOptions,
                                 mRequest.ignoreTargetSecurity, mRequest.componentSpecified,
                                 mRequest.outActivity, mRequest.inTask, mRequest.reason,
                                 mRequest.allowPendingRemoteAnimationRegistryLookup,
                                 mRequest.originatingPendingIntent, 
                                 mRequest.allowBackgroundActivityStart);
        }
    } finally {
        onExecutionComplete();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38

ActivityStarter 是加载 Activity 的控制类,会收集所有的逻辑来决定如何将 IntentFlags 转换为 Activity,并将 ActivityTask 以及 Stack 相关联。ActivityStarter.startActivityMayWait 方法和 ActivityStarter.startActivityMayWait 方法调用了 ActivityStarter.startActivity 方法:

// /frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java
private int startActivityMayWait(IApplicationThread caller, int callingUid,
                                 String callingPackage, int requestRealCallingPid, 
                                 int requestRealCallingUid, Intent intent, String resolvedType, 
                                 IVoiceInteractionSession voiceSession,
                                 IVoiceInteractor voiceInteractor, IBinder resultTo, 
                                 String resultWho, int requestCode, int startFlags, 
                                 ProfilerInfo profilerInfo, WaitResult outResult,
                                 Configuration globalConfig, SafeActivityOptions options, 
                                 boolean ignoreTargetSecurity, int userId, TaskRecord inTask, 
                                 String reason, 
                                 boolean allowPendingRemoteAnimationRegistryLookup,
                                 PendingIntentRecord originatingPendingIntent, 
                                 boolean allowBackgroundActivityStart) {
    ...
        int res = startActivity(caller, intent, ephemeralIntent, resolvedType, aInfo, rInfo,
                                voiceSession, voiceInteractor, resultTo, resultWho, requestCode, 
                                callingPid, callingUid, callingPackage, realCallingPid, 
                                realCallingUid, startFlags, options, ignoreTargetSecurity, 
                                componentSpecified, outRecord, inTask, reason,
                                allowPendingRemoteAnimationRegistryLookup, 
                                originatingPendingIntent, allowBackgroundActivityStart);

    ...
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

以下是 ActivityStarter.startActivity 的相关源码:

// /frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java
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,
                          PendingIntentRecord originatingPendingIntent, 
                          boolean allowBackgroundActivityStart) {
	// 1 判断启动的理由不为空
    if (TextUtils.isEmpty(reason)) {
        throw new IllegalArgumentException("Need to specify a reason.");
    }
    ...
    mLastStartActivityResult = startActivity(caller, intent, ephemeralIntent, resolvedType,
                                             aInfo, rInfo, voiceSession, voiceInteractor, 
                                             resultTo, resultWho, requestCode, callingPid, 
                                             callingUid, callingPackage, realCallingPid, 
                                             realCallingUid, startFlags, options, 
                                             ignoreTargetSecurity, componentSpecified, 
                                             mLastStartActivityRecord, inTask, 
                                             allowPendingRemoteAnimationRegistryLookup, 
                                             originatingPendingIntent,
                                             allowBackgroundActivityStart); // 2

    ...
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

在注释 1 处判断启动的理由不为空,如果为空则抛出 IllegalArgumentException 异常,接着,在注释 2 处调用了 startActivity 方法:

// /frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java
private final ActivityTaskManagerService mService;
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,
                          PendingIntentRecord originatingPendingIntent, 
                          boolean allowBackgroundActivityStart) {
    mSupervisor.getActivityMetricsLogger().notifyActivityLaunching(intent);
    int err = ActivityManager.START_SUCCESS;
    // Pull the optional Ephemeral Installer-only bundle out of the options early.
    final Bundle verificationBundle
        = options != null ? options.popAppVerificationBundle() : null;

    WindowProcessController callerApp = null;
    if (caller != null) { // 1
        // 得到 Launcher 进程
        callerApp = mService.getProcessController(caller); // 2
        if (callerApp != null) {
            // 获取 Launcher 进程的 pid 和 uid
            callingPid = callerApp.getPid();
            callingUid = callerApp.mInfo.uid;
        } else {
            Slog.w(TAG, "Unable to find app for caller " + caller
                   + " (pid=" + callingPid + ") when starting: "
                   + intent.toString());
            err = ActivityManager.START_PERMISSION_DENIED;
        }
    }
	...
    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; // 3
    }
    ...
    mService.onStartActivitySetDidAppSwitch();
    mController.doPendingActivityLaunches(false);

    final int res = startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
                                  true /* doResume */, checkedOptions, inTask, outActivity, 
                                  restrictedBgActivity); // 4
    mSupervisor.getActivityMetricsLogger().notifyActivityLaunched(res, outActivity[0]);
    return res;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55

注释 1 处判断 IApplicationThread 类型的 call 是否为 null,这个 call 是方法调用传进来的,指的是 Launcher 所在的应用程序进程的 ApplicationThread 对象,在注释 2 处调用 ActivityManagerService.getProcessController 方法得到的是代表 Launcher 进程的 callerApp 对象,它是 WindowProcessController 类型的。ActivityRecord 用于描述一个 Activity,用来记录一个 Activity 的所有信息。在注释 4 处将创建的 ActivityRecord 赋值给 ActivityRecord[] 类型的 outActivity,这个 outActivity 会作为注释 4 处的 startActivity 方法的参数传递下去:

// /frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java
private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
                          IVoiceInteractionSession voiceSession, 
                          IVoiceInteractor voiceInteractor, int startFlags, boolean doResume, 
                          ActivityOptions options, TaskRecord inTask,
                          ActivityRecord[] outActivity, boolean restrictedBgActivity) {
    int result = START_CANCELED;
    final ActivityStack startedActivityStack;
    try {
        mService.mWindowManager.deferSurfaceLayout();
        result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
                                        startFlags, doResume, options, inTask, outActivity, 
                                        restrictedBgActivity); // 1
    } 
    ...
    return result;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

在注释 1 处调用了 ActivityStarter.startActivityUnchecked 方法:

// /frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
                                   IVoiceInteractionSession voiceSession, 
                                   IVoiceInteractor voiceInteractor, int startFlags, 
                                   boolean doResume, ActivityOptions options, TaskRecord inTask,
                                   ActivityRecord[] outActivity, boolean restrictedBgActivity) {
	...
    if (mStartActivity.resultTo == null && mInTask == null && !mAddingToTask
        && (mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0) { // 1
        newTask = true;
        result = setTaskFromReuseOrCreateNewTask(taskToAffiliate); // 2
    } else if (mSourceRecord != null) {
        result = setTaskFromSourceRecord();
    } else if (mInTask != null) {
        result = setTaskFromInTask();
    } else {
        // This not being started from an existing activity, and not part of a new task...
        // just put it in the top task, though these days this case should never happen.
        result = setTaskToCurrentTopOrCreateNewTask();
    }
    ...
    if (mDoResume) {
        final ActivityRecord topTaskActivity =
            mStartActivity.getTaskRecord().topRunningActivityLocked();
        if (!mTargetStack.isFocusable()
            || (topTaskActivity != null && topTaskActivity.mTaskOverlay
                && mStartActivity != topTaskActivity)) {
            ...
        } else {
            if (mTargetStack.isFocusable()
                && !mRootActivityContainer.isTopDisplayFocusedStack(mTargetStack)) {
                mTargetStack.moveToFront("startActivityUnchecked");
            }
            mRootActivityContainer.resumeFocusedStacksTopActivities(
                mTargetStack, mStartActivity, mOptions); // 3
        }
    }
    ...

    return START_SUCCESS;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41

startActivityUnchecked 方法主要处理和栈管理相关的逻辑,在注释 1 处可以知道,启动根 Activity 时会将 IntentFlag 设置为 FLAG_ACTIVITY_NEW_TASK ,这样注释 1 处的条件就会判断满足,接着执行注释 2 处的 setTaskFromReuseOrCreateNewTask 方法,其内部会创建一个新的 TaskRecord,用来描述 Activity 任务栈。Activity 的任务栈是以恶假想的恶魔行,并不是真实存在的。注释 3 处会调用 RootActivityContainer.resumeFocusedStacksTopActivities 方法,其代码如下所示:

// /frameworks/base/services/core/java/com/android/server/wm/RootActivityContainer.java
boolean resumeFocusedStacksTopActivities(
    ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {

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

    boolean result = false;
    if (targetStack != null && (targetStack.isTopStackOnDisplay()
                                || getTopDisplayFocusedStack() == targetStack)) {
        result = targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
    }

    for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
        boolean resumedOnDisplay = false;
        final ActivityDisplay display = mActivityDisplays.get(displayNdx);
        for (int stackNdx = display.getChildCount() - 1; stackNdx >= 0; --stackNdx) {
            final ActivityStack stack = display.getChildAt(stackNdx);
            final ActivityRecord topRunningActivity = stack.topRunningActivityLocked(); // 1
            if (!stack.isFocusableAndVisible() || topRunningActivity == null) {
                continue;
            }
            if (stack == targetStack) {
                // Simply update the result for targetStack because the targetStack had
                // already resumed in above. We don't want to resume it again, especially in
                // some cases, it would cause a second launch failure if app process was dead.
                resumedOnDisplay |= result;
                continue;
            }
            if (display.isTopStack(stack) && topRunningActivity.isState(RESUMED)) {
                // Kick off any lingering app transitions form the MoveTaskToFront operation,
                // but only consider the top task and stack on that display.
                stack.executeAppTransition(targetOptions);
            } else {
                resumedOnDisplay |= topRunningActivity.makeActiveIfNeeded(target);
            }
        }
        if (!resumedOnDisplay) { // 2
            final ActivityStack focusedStack = display.getFocusedStack();
            if (focusedStack != null) {
                focusedStack.resumeTopActivityUncheckedLocked(target, targetOptions); // 3
            }
        }
    }

    return result;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48

在注释 1 处调用 ActivityStack.topRunningActivityLocked 放获取要启动的 Activity 所在栈的栈顶的不是处于停止状态的 ActivityRecoard。在注释 2 处,如果 ActivityRecord 不是 null 或者要启动的 Activity 的状态不是 RESUMED,就会调用注释 3 处的 ActivityStack.resumeTopActivityUncheckedLocked 方法,如下所示:

// /frameworks/base/services/core/java/com/android/server/wm/ActivityStack.java
@GuardedBy("mService")
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
    if (mInResumeTopActivity) {
        // Don't even start recursing.
        return false;
    }

    boolean result = false;
    try {
        // Protect against recursion.
        mInResumeTopActivity = true;
        result = resumeTopActivityInnerLocked(prev, options); // 1
        final ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */);
        if (next == null || !next.canTurnScreenOn()) {
            checkReadyForSleep();
        }
    } finally {
        mInResumeTopActivity = false;
    }

    return result;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

查看注释 1 处的 resumeTopActivityInnerLocked 方法:

// /frameworks/base/services/core/java/com/android/server/wm/ActivityStack.java
@GuardedBy("mService")
private boolean  (ActivityRecord prev, ActivityOptions options) {
    ...
        if (DEBUG_STATES) Slog.d(TAG_STATES, "resumeTopActivityLocked: Restarting " + next);
        mStackSupervisor.startSpecificActivityLocked(next, true, true); // 1
    ...

    return true;
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

在注释 1 处调用了 ActivityStackSupervisor.startSpecificActivityLocked 方法,代码如下所示:

// /frameworks/base/services/core/java/com/android/server/wm/ActivityStackSupervisor.java
void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) {
    // Is this activity's application already running?
    final WindowProcessController wpc =
        mService.getProcessController(r.processName, r.info.applicationInfo.uid); // 1

    boolean knownToBeDead = false;
    if (wpc != null && wpc.hasThread()) { // 2
        try {
            realStartActivityLocked(r, wpc, andResume, checkConfig); // 3
            return;
        } catch (RemoteException e) {
            Slog.w(TAG, "Exception when starting activity "
                   + r.intent.getComponent().flattenToShortString(), e);
        }

        // If a dead object exception was thrown -- fall through to
        // restart the application.
        knownToBeDead = true;
    }

    ...
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

在注释 1 处获取即将启动的 Activity 所在的应用程序进程,在注释 2 出判断要启动的 Activity 所在的应用程序进程如果已经运行的话,就会调用注释 3 处的 realStartActivityLocked 方法,这个方法的第二个参数表示的是要启动的 Activity 所在的应用程序进程的 WindowProcessController。以下是 realStartActivityLocked 的相关源码:

// /frameworks/base/services/core/java/com/android/server/wm/ActivityStackSupervisor.java
final ActivityTaskManagerService mService;
boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
                                boolean andResume, boolean checkConfig) throws RemoteException {
    ...
            // Schedule transaction.
            mService.getLifecycleManager().scheduleTransaction(clientTransaction); // 1
   ...
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

注释 1 处的 ActivityTaskManagerService.getLifecycleManager() 方法返回的是 ClientLifecycleManager 对象,以下是 ClientLifecycleManager.scheduleTransaction 方法的源码:

// /frameworks/base/services/core/java/com/android/server/wm/ClientLifecycleManager.java
void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
    final IApplicationThread client = transaction.getClient(); // 1
    transaction.schedule(); // 2
    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();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

注释 1 处获取 IApplicationThread 的实例,它的实现类是 ActivityThread 的内部类 ApplicationThreadApplicationThread 继承了 IApplicationThread.Stub。这段代码值得是要在目标进程中启动 Activity 在注释 2 处调用 ClientTransaction.schedule 方法:

// frameworks/base/core/java/android/app/servertransaction/ClientTransaction.java
public void schedule() throws RemoteException {
    mClient.scheduleTransaction(this); // 1
}
  • 1
  • 2
  • 3
  • 4

在注释 1 处调用的是 IApplicationThread.scheduleTransaction 方法,也就是它的实现类 ApplicationThread.scheduleTransaction 方法:

// /frameworks/base/core/java/android/app/ActivityThread.java
@Override
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
    ActivityThread.this.scheduleTransaction(transaction); // 1
}
  • 1
  • 2
  • 3
  • 4
  • 5

到此时,便进入了 ActivityThread 的处理逻辑中。

当前代码运行在 AMS 所在的进程,即 system_server 进程中,通过 ApplicationThread 来与应用程序进程进行 Binder 通信。换句话说,ApplicationThreadAMS 所在进程 system_server 与应用程序进程的通信桥梁。

AMS和应用程序进程通信

3 ActivityThread 启动 Activity 的过程

以下是 ActivityThread 启动 Activity 的时序图:

ActivityThread启动Activity的过程

上一节中讲到:

// /frameworks/base/core/java/android/app/ActivityThread.java
private class ApplicationThread extends IApplicationThread.Stub {
    @Override
    public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
        ActivityThread.this.scheduleTransaction(transaction); // 1
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

注释 1 处调用了 ActivityThread.this.scheduleTransaction 方法,ActivityThread 继承自 ClientTransactionHandler,因此这里调用的是 ClientTransactionHandler.scheduleTransaction 方法,以下是相关源码:

// /frameworks/base/core/java/android/app/ClientTransactionHandler.java
void scheduleTransaction(ClientTransaction transaction) {
    transaction.preExecute(this);
    sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction); // 1
}
  • 1
  • 2
  • 3
  • 4
  • 5

注释 1 处的 ActivityThread.HHandler 的子类,以下是 ActivityThread.sendMessage 方法的源码和关于 ActivityThread.H.EXECUTE_TRANSACTION 的相关处理:

// /frameworks/base/core/java/android/app/ActivityThread.java
void sendMessage(int what, Object obj) {
    sendMessage(what, obj, 0, 0, false);
}

private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
    if (DEBUG_MESSAGES) {
        Slog.v(TAG,
               "SCHEDULE " + what + " " + mH.codeToString(what) + ": " + arg1 + " / " + obj);
    }
    Message msg = Message.obtain();
    msg.what = what;
    msg.obj = obj;
    msg.arg1 = arg1;
    msg.arg2 = arg2;
    if (async) {
        msg.setAsynchronous(true);
    }
    mH.sendMessage(msg);
}

class H extends Handler {
    ...
    public static final int EXECUTE_TRANSACTION = 159;
	...
    public void handleMessage(Message msg) {
        if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
        switch (msg.what) {
            ...
            case EXECUTE_TRANSACTION:
                final ClientTransaction transaction = (ClientTransaction) msg.obj;
                mTransactionExecutor.execute(transaction); // 1
                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;
				...
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44

在注释 1 处调用了 TransactionExecutor.execute 方法

// /frameworks/base/core/java/android/app/servertransaction/TransactionExecutor.java
public void execute(ClientTransaction transaction) {
    ...
    executeCallbacks(transaction); // 1

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

@VisibleForTesting
public void executeCallbacks(ClientTransaction transaction) {
    ...
    final int size = callbacks.size();
    for (int i = 0; i < size; ++i) {
        final ClientTransactionItem item = callbacks.get(i);
        ...
        item.execute(mTransactionHandler, token, mPendingActions); // 2
        ..
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

注释 2 处调用了 ClientTransactionItem.execute 方法,该方法在其子类 LaunchActivityItem 中实现,以下是 LaunchActivityItem.execute 方法:

// /frameworks/base/core/java/android/app/servertransaction/LaunchActivityItem.java) 
@Override
public void execute(ClientTransactionHandler client, IBinder token,
                    PendingTransactionActions pendingActions) {
    Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
    ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
                                                      mOverrideConfig, mCompatInfo, mReferrer, 
                                                      mVoiceInteractor, mState, 
                                                      mPersistentState,
                                                      mPendingResults, mPendingNewIntents, 
                                                      mIsForward,
                                                      mProfilerInfo, client, mAssistToken);
    client.handleLaunchActivity(r, pendingActions, null /* customIntent */); // 1
    Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

注释 1 处的 clientClientTransactionHandler 的子类 ActivityThread,查看 ActivityThread.handleLauncherActivity 的源码,主要是调用了 ActivityThread.performLaunchActivity 方法:

// /frameworks/base/core/java/android/app/ActivityThread.java
@Override
public Activity handleLaunchActivity(ActivityClientRecord r,
                                     PendingTransactionActions pendingActions, 
                                     Intent customIntent) {
    ...
    WindowManagerGlobal.initialize();
    
	// 1 启动 Activity
    final Activity a = performLaunchActivity(r, customIntent);

    if (a != null) {
        r.createdConfig = new Configuration(mConfiguration);
        reportSizeConfigurations(r);
        if (!r.activity.mFinished && pendingActions != null) {
            pendingActions.setOldState(r.state);
            pendingActions.setRestoreInstanceState(true);
            pendingActions.setCallOnPostCreate(true);
        }
    } else {
        // If there was an error, for any reason, tell the activity manager to stop us.
        try {
            // 停止 Activity 的启动
            ActivityTaskManager.getService()
                .finishActivity(r.token, Activity.RESULT_CANCELED, null,
                                Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
        } catch (RemoteException ex) {
            throw ex.rethrowFromSystemServer();
        }
    }

    return a;
}

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    ActivityInfo aInfo = r.activityInfo; // 2 获取 ActivityInfo 类
    if (r.packageInfo == null) {
        // 3 获取 APK 文件描述类 LoadApk
        r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
                                       Context.CONTEXT_INCLUDE_CODE); 
    }

    ComponentName component = r.intent.getComponent(); // 4
    ...
    // 5 创建要启动的 Activity 的上下文环境
    ContextImpl appContext = createBaseContextForActivity(r); 
    Activity activity = null;
    try {
        java.lang.ClassLoader cl = appContext.getClassLoader();
        // 6 用类加载器创建该 Activity 的实例
        activity = mInstrumentation.newActivity(cl, component.getClassName(), r.intent);
        ...
    } catch (Exception e) {
        ...
    }

    try {
        // 7 创建 Application
        Application app = r.packageInfo.makeApplication(false, mInstrumentation);
        ...
        if (activity != null) {
            ...
            // 8 初始化 Activity
            activity.attach(appContext, this, getInstrumentation(), r.token,
                            r.ident, app, r.intent, r.activityInfo, title, r.parent,
                            r.embeddedID, r.lastNonConfigurationInstances, config,
                            r.referrer, r.voiceInteractor, window, r.configCallback,
                            r.assistToken);
            ...
            if (r.isPersistable()) {
                mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState); // 9
            } else {
                mInstrumentation.callActivityOnCreate(activity, r.state);
            }
            ...
        }
        ...
    } catch (SuperNotCalledException e) {
        throw e;

    } catch (Exception e) {
        ....
    }
    return activity;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85

注释 1 处调用了 ActivityThread.performLaunchActivity 方法来启动 Activity。注释 2 处用来获取 ActivityInfo,用来存储代码以及 AndroidManifest 设置的 ActivityReceiver 节点信息,比如,ActivitythemelaunchMode。在注释 3 处获取 APK 文件的描述类 LoadedApk。在注释 4 处获取要启动的 ActivityComponentName 类,在 ComponentName 类中保存了该 Activity 的包名和类名。在注释 5 处用来创建要启动的 Activity 的上下文环境。在注释 6 处根据 ComponentName 中存储的 Activity 类名,用类加载器来创建该 Activity 的实例 。注释 7 处用来创建 ApplicationLoadedApk.makeApplication 方法内部会调用 Application.onCreate 方法。注释 8 处调用 Activity.attach 方法初始化 Activity,在 Activity.attach 方法中会创建 Window 对象(PhoneWindow)并与 Activity 自身进行关联。在注释 9 处调用 Instrumentation.callActivityOnCreate 方法来启动 Activity

// /frameworks/base/core/java/android/app/Instrumentation.java
public void callActivityOnCreate(Activity activity, Bundle icicle,
                                 PersistableBundle persistentState) {
    prePerformCreate(activity);
    activity.performCreate(icicle, persistentState); // 1
    postPerformCreate(activity);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

注释 1 处调用了 Activity.performCreate 方法,在 Activity.performCreate 方法中又调用了 Activity.onCreate 方法,到这里,根 Activity 就启动了,以下是相关源码:

// /frameworks/base/core/java/android/app/Activity.java
@UnsupportedAppUsage
final void performCreate(Bundle icicle, PersistableBundle persistentState) {
    dispatchActivityPreCreated(icicle);
    mCanEnterPictureInPicture = true;
    restoreHasCurrentPermissionRequest(icicle);
    // 1
    if (persistentState != null) {
        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());
    dispatchActivityPostCreated(icicle);
}

@MainThread
@CallSuper
protected void onCreate(@Nullable Bundle savedInstanceState) {
    if (DEBUG_LIFECYCLE) Slog.v(TAG, "onCreate " + this + ": " + savedInstanceState);

    if (mLastNonConfigurationInstances != null) {
        mFragments.restoreLoaderNonConfig(mLastNonConfigurationInstances.loaders);
    }
    if (mActivityInfo.parentActivityName != null) {
        if (mActionBar == null) {
            mEnableDefaultActionBarUp = true;
        } else {
            mActionBar.setDefaultDisplayHomeAsUpEnabled(true);
        }
    }
    if (savedInstanceState != null) {
        mAutoFillResetNeeded = savedInstanceState.getBoolean(AUTOFILL_RESET_NEEDED, false);
        mLastAutofillId = savedInstanceState.getInt(LAST_AUTOFILL_ID,
                                                    View.LAST_APP_AUTOFILL_ID);

        if (mAutoFillResetNeeded) {
            getAutofillManager().onCreate(savedInstanceState);
        }

        Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
        mFragments.restoreAllState(p, mLastNonConfigurationInstances != null
                                   ? mLastNonConfigurationInstances.fragments : null);
    }
    mFragments.dispatchCreate();
    dispatchActivityCreated(savedInstanceState);
    if (mVoiceInteractor != null) {
        mVoiceInteractor.attachActivity(this);
    }
    mRestoredFromBundle = savedInstanceState != null;
    mCalled = true;

}

public void onCreate(@Nullable Bundle savedInstanceState,
                     @Nullable PersistableBundle persistentState) {
    onCreate(savedInstanceState);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64

4 总结

Activity 启动过程中会涉及到 4 个进程,分别是 Zygote 进程、system_server 进程(AMS)、Launcher 进程和应用程序进程。它们的关系如下所示:

根Activity启动过程中涉及到的进程之间的关系

首先 Launcher 进程向 AMS 请求创建根 ActivityAMS 会判断根 Activity 所需要的应用程序进程是否存在并启动,如果不存在就会请求 Zygote 进程创建应用程序进程。应用程序进程启动后,AMS 会请求创建并启动根 Activity

以下是 4 个进程调用的时序图:

根Activity启动过程中进程调用时序图

如果是普通的 Activity 的启动过程,会涉及到两个进程,AMS 所在的进程(system_server 进程)和应用程序进程。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/528860
推荐阅读
相关标签
  

闽ICP备14008679号