Activity 的 "启动流程"


# 核心源码( Android 9.0 )

Source Path(/packages/apps/Launcher3/)
BaseDraggingActivity.java src/com/android/launcher3/BaseDraggingActivity.java
ItemClickHandler.java src/com/android/launcher3/touch/ItemClickHandler.java
Launcher.java src/com/android/launcher3/Launcher.java
Source Path(/framework/base/)
Activity.java core/java/android/app/Activity.java
ActivityManager.java core/java/android/app/ActivityManager.java
ActivityThread.java core/java/android/app/ActivityThread.java
ClientTransaction.java core/java/android/app/servertransaction/ClientTransaction.java
ClientTransactionHandler.java core/java/android/app/ClientTransactionHandler.java
Instrumentation.java core/java/android/app/Instrumentation.java
LaunchActivityItem.java core/java/android/app/servertransaction/LaunchActivityItem.java
PauseActivityItem.java core/java/android/app/servertransaction/PauseActivityItem.java
Process.java core/java/android/os/Process.java
TransactionExecutor.java core/java/android/app/servertransaction/TransactionExecutor.java
ActivityManagerService.java services/core/java/com/android/server/am/ActivityManagerService.java
ActivityStack.java services/core/java/com/android/server/am/ActivityStack.java
ActivityStarter.java services/core/java/com/android/server/am/ActivityStarter.java
ActivityStartController.java services/core/java/com/android/server/am/ActivityStartController.java
ActivityStackSupervisor.java services/core/java/com/android/server/am/ActivityStackSupervisor.java
ClientLifecycleManager.java services/core/java/com/android/server/am/ClientLifecycleManager.java


一、前言

点击 Launcher 界面的应用图标,运行各种眼花缭乱,功能强大的应用,是我们的日常行为,作为一名系统工程师,我们有必要一起深入研究一下,当我们点击 APK 图标,直到应用的主界面最后显示出来,这期间从源码角度到底发生了什么,处理逻辑是什么样的?

这个流程个人觉得是非常必要深刻理解的,比如有时当我们点击应用出现了 卡顿黑白屏 现象,这些是应用本身的问题,还是系统的问题?当你分析此类问题的时候,如果对 Activity 的启动流程不熟悉,分析起来会狠吃力,并且未必能深入分析得到最根本的原因。

废话不多说,为了更方便并且细致的分析源码流程,我们选取 Launcher 界面点击应用 为切入点进行分析(通过一个特定场景/操作是研究源码最好的做法),接下来直接进入正题。(各位狮子们,这也是很多面试官喜欢提问的问题)


二、Launcher 的 onPause 流程

我们既然要启动新的 APK 置于前台,那么当前活动必然要被切换到后台,所以首先涉及到的就是 Launcher 的 onPause 流程。Activity 的生命周期可以阅读 【 Android ‘四大组件’ 】篇 – Activity 的 “生命周期” 一文。

2.1 ItemClickHandler.onClick

当点击应用程序 Launcher 的某个图标时,回调接口 ItemClickHandler 会执行 onClick() 方法中的 startAppShortcutOrInfoActivity

// packages/apps/Launcher3/src/com/android/launcher3/Launcher.java

public View createShortcut(ViewGroup parent, ShortcutInfo info) {
    BubbleTextView favorite = (BubbleTextView) LayoutInflater.from(parent.getContext())
            .inflate(R.layout.app_icon, parent, false);
    favorite.applyFromShortcutInfo(info);
    favorite.setOnClickListener(ItemClickHandler.INSTANCE);
    favorite.setOnFocusChangeListener(mFocusHandler);
    return favorite;
}


// packages/apps/Launcher3/src/com/android/launcher3/touch/ItemClickHandler.java

public class ItemClickHandler {
    public static final OnClickListener INSTANCE = ItemClickHandler::onClick;

    private static void onClick(View v) {
        ... ...
        if (tag instanceof ShortcutInfo) {
            onClickAppShortcut(v, (ShortcutInfo) tag, launcher);
        } else if (tag instanceof FolderInfo) {
            if (v instanceof FolderIcon) {
                onClickFolderIcon(v);
            }
        } else if (tag instanceof AppInfo) {
            // 执行 startAppShortcutOrInfoActivity 方法
            startAppShortcutOrInfoActivity(v, (AppInfo) tag, launcher);
        } else if (tag instanceof LauncherAppWidgetInfo) {
            if (v instanceof PendingAppWidgetHostView) {
                onClickPendingWidget((PendingAppWidgetHostView) v, launcher);
            }
        }
    }
    ... ...
}

2.2 ItemClickHandler.startAppShortcutOrInfoActivity

// packages/apps/Launcher3/src/com/android/launcher3/touch/ItemClickHandler.java

private static void startAppShortcutOrInfoActivity(View v, ItemInfo item, Launcher launcher) {
    Intent intent;
    if (item instanceof PromiseAppInfo) {
        PromiseAppInfo promiseAppInfo = (PromiseAppInfo) item;
        intent = promiseAppInfo.getMarketIntent(launcher);
    } else {
        intent = item.getIntent();
    }
    if (intent == null) {
        throw new IllegalArgumentException("Input must have a valid intent");
    }
    if (item instanceof ShortcutInfo) {
        ShortcutInfo si = (ShortcutInfo) item;
        if (si.hasStatusFlag(ShortcutInfo.FLAG_SUPPORTS_WEB_UI)
                && intent.getAction() == Intent.ACTION_VIEW) {
            intent = new Intent(intent);
            intent.setPackage(null);
        }
    }
    // 执行 startActivitySafely 方法
    launcher.startActivitySafely(v, intent, item);
}

2.3 Launcher.startActivitySafely

代码最终走到 Launcher 的 startActivitySafely() 方法。

// packages/apps/Launcher3/src/com/android/launcher3/Launcher.java

public boolean startActivitySafely(View v, Intent intent, ItemInfo item) {
    // 调用父类 BaseDraggingActivity 的 startActivitySafely 方法
    boolean success = super.startActivitySafely(v, intent, item);
    if (success && v instanceof BubbleTextView) {
        BubbleTextView btv = (BubbleTextView) v;
        btv.setStayPressed(true);
        setOnResumeCallback(btv);
    }
    return success;    // 表示启动新应用程序的 Activity 成功
}

2.4 BaseDraggingActivity.startActivitySafely

// packages/apps/Launcher3/src/com/android/launcher3/BaseDraggingActivity.java

public boolean startActivitySafely(View v, Intent intent, ItemInfo item) {
    ... ...
    // 添加标志,表示要在一个新的 Task 中启动这个 Activity
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    if (v != null) {
        intent.setSourceBounds(getViewBounds(v));
    }
    try {
        boolean isShortcut = Utilities.ATLEAST_MARSHMALLOW
                                && (item instanceof ShortcutInfo)
                                && (item.itemType == Favorites.ITEM_TYPE_SHORTCUT
                                || item.itemType == Favorites.ITEM_TYPE_DEEP_SHORTCUT)
                                && !((ShortcutInfo) item).isPromise();
        if (isShortcut) {
            startShortcutIntentSafely(intent, optsBundle, item);
        } else if (user == null || user.equals(Process.myUserHandle())) {
            startActivity(intent, optsBundle);    // 调用 Activity.startActivity 方法
        } else {
            LauncherAppsCompat.getInstance(this).startActivityForProfile(
                    intent.getComponent(), user, intent.getSourceBounds(), optsBundle);
        }
        getUserEventDispatcher().logAppLaunch(v, intent);
        return true;
    } catch (ActivityNotFoundException|SecurityException e) {
        Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
        Log.e(TAG, "Unable to launch. tag=" + item + " intent=" + intent, e);
    }
    return false;
}

2.5 Activity.startActivity

// framework/base/core/java/android/app/Activity.java

public void startActivity(Intent intent, @Nullable Bundle options) {
    if (options != null) {
        startActivityForResult(intent, -1, options);    // options 表示 Launcher 启动 Activity 时的动画效果
    } else {
        startActivityForResult(intent, -1);
    }
}

2.6 Activity.startActivityForResult

// framework/base/core/java/android/app/Activity.java

public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
        @Nullable Bundle options) {
    // mParent 代表目前 Launcher Activity 的状态
    if (mParent == null) {    // 第一次启动 Activity,走此条分支
        options = transferSpringboardActivityOptions(options);
        // 执行 mInstrumentation.execStartActivity() 方法
        Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity(this, 
                        mMainThread.getApplicationThread(), mToken,
                        this, intent, requestCode, options);
        ... ...
    } else {
        if (options != null) {
            // 最终会调用 mInstrumentation.execStartActivity() 方法
            mParent.startActivityFromChild(this, intent, requestCode, options);
        } else {
            mParent.startActivityFromChild(this, intent, requestCode);
        }
    }
}

mMainThread 是 Activity 类的 成员变量,它的类型是 ActivityThread,它代表的是应用程序的 主线程

// frameworks/base/core/java/android/app/ActivityThread.java

public final class ActivityThread extends ClientTransactionHandler {
    ... ...
    final ApplicationThread mAppThread = new ApplicationThread();
    ... ...
    private class ApplicationThread extends IApplicationThread.Stub {...}
    ... ...
    public ApplicationThread getApplicationThread()
    {
        return mAppThread;
    }
    ... ...
}

mMainThread.getApplicationThread() 获得的是 ApplicationThread 内部成员变量,它是一个 Binder 对象。这个对象是干嘛用的,我们后面会讲解到。

2.7 Instrumentation.execStartActivity

Instrumentation 是 Android 系统中启动 Activity 的一个实际操作类,它用来监控应用程序和系统的交互。

// frameworks/base/core/java/android/app/Instrumentation.java

public ActivityResult execStartActivity( Context who, IBinder contextThread, IBinder token,
                        Activity target, Intent intent, int requestCode, Bundle options) {
    ... ...
    try {
        intent.migrateExtraStreamToClipData();
        intent.prepareToLeaveProcess(who);
        // 通过 ActivityManager.getService() 方法可以获得 ActivityManagerService 提供的服务
        int result = ActivityManager.getService().startActivity(whoThread,
                            who.getBasePackageName(), intent, 
                            intent.resolveTypeIfNeeded(who.getContentResolver()),
                            token, target != null ? target.mEmbeddedID : null, 
                            requestCode, 0, null, options);
        checkStartActivityResult(result, intent);
    } catch (RemoteException e) {
        throw new RuntimeException("Failure from system", e);
    }
    return null;
}

我们研究下 ActivityManager.getService() 方法:

// frameworks/base/core/java/android/app/ActivityManager.java

public static IActivityManager getService() {
    return IActivityManagerSingleton.get();    // 获取 IActivityManager 单例
}

private static final Singleton<IActivityManager> IActivityManagerSingleton =
        new Singleton<IActivityManager>() {
            @Override
            protected IActivityManager create() {
                final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
                final IActivityManager am = IActivityManager.Stub.asInterface(b);
                return am;
            }
        };

// frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

public class ActivityManagerService extends IActivityManager.Stub
        implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {

我们发现 ActivityManagerServiceActivityManger 的 Binder 通信采用了 AIDL 的方式。

ActivityManager.getService().startActivity 方法实际上调用到了 ActivityManagerServicestartActivity() 方法。

如果对于 AIDL 不了解,你可以查看 【 Android ‘核心机制’ 】篇 – 无处不在的 “AIDL” 一文。

2.8 ActivityManagerService.startActivity

下面看看 ActivityManagerServicestartActivity 方法:

// frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.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) {
    // 调转到 startActivityAsUser 方法
    return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
            resultWho, requestCode, startFlags, profilerInfo, bOptions,
            UserHandle.getCallingUserId());
}

2.9 ActivityManagerService.startActivityAsUser

// frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

// Android P 新增,这边的流程与以前的就完全不一样了,但最终调取的方法还是一样的,细心跟一下
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) {
    // 继续调 startActivityAsUser 方法
    return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
            resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
            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");

    // 在 Android P 之前调用的是 ActivityStartController.startActivityMayWait 方法
    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)      // 设置了 mRequest.mayWait = true,后面会用到
            .execute();
}

2.10 ActivityStartController.obtainStarter

// frameworks/base/services/core/java/com/android/server/am/ActivityStartController.java

import com.android.server.am.ActivityStarter.Factory;
private final Factory mFactory;

ActivityStarter obtainStarter(Intent intent, String reason) {
    // obtain()、setIntent()、setReason() 分别干了什么,下面一一说明
    return mFactory.obtain().setIntent(intent).setReason(reason);
}

这边用到了工厂模式,我们跟一下具体的处理流程。

2.10.1 DefaultFactory.obtain

// frameworks/base/services/core/java/com/android/server/am/ActivityStarter.java

interface Factory {
    void setController(ActivityStartController controller);
    ActivityStarter obtain();
    void recycle(ActivityStarter starter);
}

// DefaultFactory 为实现类
static class DefaultFactory implements Factory {
    ... ...
    @Override
    public ActivityStarter obtain() {
        ActivityStarter starter = mStarterPool.acquire();

        // obtain() 方法最终返回的是 ActivityStarter 的实例
        if (starter == null) {
            starter = new ActivityStarter(mController, mService, mSupervisor, mInterceptor);
        }
        return starter;
    }
    ... ...
}

2.10.2 ActivityStarter.setIntent

// frameworks/base/services/core/java/com/android/server/am/ActivityStarter.java

ActivityStarter setIntent(Intent intent) {
    mRequest.intent = intent;        // 为 mRequest 赋值 
    return this;
}

2.10.3 ActivityStarter.setReason

// frameworks/base/services/core/java/com/android/server/am/ActivityStarter.java

ActivityStarter setReason(String reason) {
    mRequest.reason = reason;        // 为 mRequest 赋值
    return this;
}

mActivityStartController.obtainStarter() 方法最终获得一个包含所有启动信息的 ActivityStarter 对象,然后作了各种赋值处理,最后执行 execute 方法。

2.11 ActivityStarter.execute

// frameworks/base/services/core/java/com/android/server/am/ActivityStarter.java

// 上面执行了 setMayWait(userId) 方法
ActivityStarter setMayWait(int userId) {
    mRequest.mayWait = true;
    mRequest.userId = userId;
    return this;
}

int execute() {
    try {
        if (mRequest.mayWait) {    // setMayWait() 方法中置为 true
            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,
                    mRequest.originatingPendingIntent);
        } 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);
        }
    } finally {
        onExecutionComplete();
    }
}

绕了一圈还,最终还是走到了 startActivityMayWait() 方法!

2.12 流程小结


ezc89s.png


2.13 ActivityStarter.startActivityMayWait

// frameworks/base/services/core/java/com/android/server/am/ActivityStarter.java

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,
        PendingIntentRecord originatingPendingIntent) {
    // Refuse possible leaked file descriptors
    if (intent != null && intent.hasFileDescriptors()) {
        throw new IllegalArgumentException("File descriptors passed in Intent");
    }
    mSupervisor.getActivityMetricsLogger().notifyActivityLaunching();
    boolean componentSpecified = intent.getComponent() != null;

    final int realCallingPid = Binder.getCallingPid();
    final int realCallingUid = Binder.getCallingUid();
    ... ...
    // 解析 Intent 的数据
    ResolveInfo rInfo = mSupervisor.resolveIntent(intent, resolvedType, userId,
            0 /* matchFlags */,
                    computeResolveFilterUid(
                            callingUid, realCallingUid, mRequest.filterCallingUid));
    ... ...
    // 收集 intent 中的相关信息
    ActivityInfo aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags, profilerInfo);

    synchronized (mService) {
        ... ...
        // 用于记录 Activity 的数据
        final ActivityRecord[] outRecord = new ActivityRecord[1];
        // 启动 Activity
        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);

        Binder.restoreCallingIdentity(origId);
        ... ...
        mSupervisor.getActivityMetricsLogger().notifyActivityLaunched(res, outRecord[0]);
        return res;
    }
}

2.14 ActivityStarter.startActivity -01

// frameworks/base/services/core/java/com/android/server/am/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) {
    ... ...
    // 跳转 startActivity
    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);
    ... ...
    return getExternalResult(mLastStartActivityResult);
}

2.15 ActivityStarter.startActivity -02

// frameworks/base/services/core/java/com/android/server/am/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, boolean allowPendingRemoteAnimationRegistryLookup,
        PendingIntentRecord originatingPendingIntent) {
    ... ...
    // 跳转 startActivity
    return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
            true /* doResume */, checkedOptions, inTask, outActivity);
}

2.16 ActivityStarter.startActivity -03

// frameworks/base/services/core/java/com/android/server/am/ActivityStarter.java

private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
            ActivityRecord[] outActivity) {
    int result = START_CANCELED;
    try {
        // 暂停布局
        mService.mWindowManager.deferSurfaceLayout();
        // 调用 startActivityUnchecked 方法
        result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
                startFlags, doResume, options, inTask, outActivity);
    } finally {
        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;
}

调用了 3 次 startActivity() ,最终执行了 startActivityUnchecked() 方法,这个方法里会根据 启动标志位Activity 启动模式来决定如何启动一个 Activity。

2.17 ActivityStarter.startActivityUnchecked

// frameworks/base/services/core/java/com/android/server/am/ActivityStarter.java

private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
        IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
        int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
        ActivityRecord[] outActivity) {

    // 初始化启动 Activity 的各种配置,会先重置再重新配置,其中包括 ActivityRecord、Intent 等
    setInitialState(r, options, inTask, doResume, startFlags, sourceRecord, voiceSession,
            voiceInteractor);

    // 计算出启动的 FLAG,并将计算的值赋值给 mLaunchFlags
    computeLaunchingTaskFlags();
    computeSourceStack();
    // 将 mLaunchFlags 设置给 Intent,达到设定 Activity 的启动方式的目的
    mIntent.setFlags(mLaunchFlags);
    // 获取是否有可以复用的 activity
    ActivityRecord reusedActivity = getReusableIntentActivity();
    ... ...
    // 可复用 Activity 不为空
    if (reusedActivity != null) {
        ... ...
    }
    ... ...
    mTargetStack.startActivityLocked(mStartActivity, topFocused, newTask, mKeepCurTransition,
            mOptions);
    if (mDoResume) {
        final ActivityRecord topTaskActivity =
                mStartActivity.getTask().topRunningActivityLocked();
        if (!mTargetStack.isFocusable()
                || (topTaskActivity != null && topTaskActivity.mTaskOverlay
                && mStartActivity != topTaskActivity)) {
            ... ...
        } else {
            if (mTargetStack.isFocusable() && !mSupervisor.isFocusedStack(mTargetStack)) {
                mTargetStack.moveToFront("startActivityUnchecked");
            }
            // 调用 resumeFocusedStackTopActivityLocked() 方法
            mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity,
                    mOptions);
        }
    } else if (mStartActivity != null) {
        mSupervisor.mRecentTasks.add(mStartActivity.getTask());
    }
    ... ...
    return START_SUCCESS;
}

2.18 ActivityStackSupervisor.resumeFocusedStackTopActivityLocked

// frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java

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

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

    if (targetStack != null && isFocusedStack(targetStack)) {
        // 调用 resumeTopActivityUncheckedLocked 方法
        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)) {
        mFocusedStack.executeAppTransition(targetOptions);
    }

    return false;
}

2.19 ActivityStack.resumeTopActivityUncheckedLocked

// frameworks/base/services/core/java/com/android/server/am/ActivityStack.java

boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
    if (mStackSupervisor.inResumeTopActivity) {
        // Don't even start recursing.
        return false;
    }

    boolean result = false;
    try {
        // Protect against recursion.
        mStackSupervisor.inResumeTopActivity = true;
        result = resumeTopActivityInnerLocked(prev, options);    // 关键方法

        final ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */);
        if (next == null || !next.canTurnScreenOn()) {
            checkReadyForSleep();
        }
    } finally {
        mStackSupervisor.inResumeTopActivity = false;
    }

    return result;
}

2.20 ActivityStack.resumeTopActivityInnerLocked

// frameworks/base/services/core/java/com/android/server/am/ActivityStack.java

private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
    if (!mService.mBooting && !mService.mBooted) {
        // Not ready yet!
        return false;
    }
    ... ...
    boolean pausing = mStackSupervisor.pauseBackStacks(userLeaving, next, false);
    if (mResumedActivity != null) {
        if (DEBUG_STATES) Slog.d(TAG_STATES,
                "resumeTopActivityLocked: Pausing " + mResumedActivity);
        // 先执行 startPausingLocked() 方法
        pausing |= startPausingLocked(userLeaving, false, next, false);
    }
    ... ...
    ActivityStack lastStack = mStackSupervisor.getLastStack();
    if (next.app != null && next.app.thread != null) {
        ... ...
        synchronized(mWindowManager.getWindowManagerLock()) {
            ... ...
            try {
                ... ...    
            } catch (Exception e) {
                ... ...
                // 执行 startSpecificActivityLocked() 方法
                mStackSupervisor.startSpecificActivityLocked(next, true, false);
                return true;
            }
        }

        try {
            next.completeResumeLocked();
        } catch (Exception e) {
            requestFinishActivityLocked(next.appToken, Activity.RESULT_CANCELED, null,
                    "resume-exception", true);
            if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
            return true;
        }
    } else {
        ... ...
        // 执行 startSpecificActivityLocked() 方法
        mStackSupervisor.startSpecificActivityLocked(next, true, true);
    }

    if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
    return true;
}

resumeTopActivityInnerLocked 方法中会去判断是否有 Activity 处于 Resume 状态。

如果有的话会先让这个 Activity 执行 Pausing 过程(其实也就是本案例中 LauncheronPause 流程),然后再执行 startSpecificActivityLocked 方法来启动需要启动的 Activity。

2.21 ActivityStack.startPausingLocked

我们先分析 startPausingLocked() 源码,应用的启动流程 startSpecificActivityLocked() 放在第三节讨论!

// frameworks/base/services/core/java/com/android/server/am/ActivityStack.java

// 栈顶 Activity 执行 onPause 方法退出
final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping,
        ActivityRecord resuming, boolean pauseImmediately) {
    ... ...
    ActivityRecord prev = mResumedActivity;
    ... ...
    // 把 prev 赋值给 mPausingActivity,这个值在 Activity 启动过程中会用到,
    // 这边其实就是将 mResumedActivity 赋值给 mPausingActivity,就是我们的 Launcher。
    mPausingActivity = prev;
    ... ...
    if (prev.app != null && prev.app.thread != null) {
        try {
            EventLogTags.writeAmPauseActivity(prev.userId, System.identityHashCode(prev),
                    prev.shortComponentName, "userLeaving=" + userLeaving);
            mService.updateUsageStats(prev, false);
            /*
             * Android P 在这里引入了 ClientLifecycleManager 和 ClientTransactionHandler 来辅助
             * 管理 Activity 生命周期,它会发送 EXECUTE_TRANSACTION 消息
             * 到 ActivityThread.H 里面继续处理。

             * 通过 ClientLifecycleManager 的 scheduleTransaction 方法把 PauseActivityItem
             * 事件加入到执行计划中,开始栈顶的 pausing 过程。
             */
            mService.getLifecycleManager().scheduleTransaction(prev.app.thread, prev.appToken,
                    PauseActivityItem.obtain(prev.finishing, userLeaving,
                                    prev.configChangeFlags, pauseImmediately));
        } catch (Exception e) {
            // Ignore exception, if process died other code will cleanup.
            Slog.w(TAG, "Exception thrown during pause", e);
            mPausingActivity = null;
            mLastPausedActivity = null;
            mLastNoHistoryActivity = null;
        }
    } else {
        mPausingActivity = null;
        mLastPausedActivity = null;
        mLastNoHistoryActivity = null;
    }
    ... ...
}

2.22 ClientLifecycleManager.scheduleTransaction

// frameworks/base/services/core/java/com/android/server/am/ClientLifecycleManager.java

class ClientLifecycleManager {
    void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
        final IApplicationThread client = transaction.getClient();
        transaction.schedule();
        if (!(client instanceof Binder)) {
            transaction.recycle();
        }
    }
    ... ...
}

// frameworks/base/core/java/android/app/servertransaction/ClientTransaction.java

public class ClientTransaction implements Parcelable, ObjectPoolItem {

    /** Target client. */
    private IApplicationThread mClient;

    public void schedule() throws RemoteException {
        mClient.scheduleTransaction(this);
    }
}

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

2.23 ActivityThread.scheduleTransaction

// frameworks/base/core/java/android/app/ActivityThread.java

public final class ActivityThread extends ClientTransactionHandler {

    private class ApplicationThread extends IApplicationThread.Stub {
        ... ...    
        public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
            ActivityThread.this.scheduleTransaction(transaction);
        }
    }
}

2.24 流程小结


ezjGo4.png


2.25 ClientTransactionHandler.scheduleTransaction

ActivityThread 类中并没有定义 scheduleTransaction 方法,所以调用的是他父类 ClientTransactionHandlerscheduleTransaction 方法。

// frameworks/base/core/java/android/app/ClientTransactionHandler.java

public abstract class ClientTransactionHandler {

    abstract void sendMessage(int what, Object obj);

    void scheduleTransaction(ClientTransaction transaction) {
        transaction.preExecute(this);
        // 调用了 sendMessage 方法,这个方法是一个抽象方法,
        // 它的实现是在 ClientTransactionHandler 派生类的 ActivityThread 中。
        sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
    }
}

2.26 ActivityThread.sendMessage

// frameworks/base/core/java/android/app/ActivityThread.java

public final class ActivityThread extends ClientTransactionHandler {

    private final TransactionExecutor mTransactionExecutor = new TransactionExecutor(this);

    void sendMessage(int what, Object obj) {
        sendMessage(what, obj, 0, 0, false);
    }

    private void sendMessage(int what, Object obj, int arg1) {
        sendMessage(what, obj, arg1, 0, false);
    }

    private void sendMessage(int what, Object obj, int arg1, int arg2) {
        sendMessage(what, obj, arg1, arg2, false);
    }

    private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
        Message msg = Message.obtain();
        msg.what = what;
        msg.obj = obj;
        msg.arg1 = arg1;
        msg.arg2 = arg2;
        if (async) {
            msg.setAsynchronous(true);
        }
        // ActivityThread.sendMessage 方法会把消息发送给内部名字叫 H 的 Handler
        mH.sendMessage(msg);
    }

    class H extends Handler {
        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;
                    // Handler H 的实例接收到 EXECUTE_TRANSACTION 消息后调用 
                    // TransactionExecutor.execute 方法切换 Activity 状态。
                    mTransactionExecutor.execute(transaction);
                    if (isSystem()) {
                        transaction.recycle();
                    }
                    // TODO(lifecycler): Recycle locally scheduled transactions.
                    break;
            }
        }
    }
}

2.27 TransactionExecutor.execute

// frameworks/base/core/java/android/app/servertransaction/TransactionExecutor.java

public class TransactionExecutor {

    public void execute(ClientTransaction transaction) {
        final IBinder token = transaction.getActivityToken();
        log("Start resolving transaction for client: " + mTransactionHandler + ", token: " + token);

        executeCallbacks(transaction);    // 重要方法 1
        executeLifecycleState(transaction);    // 重要方法 2

        mPendingActions.clear();
        log("End resolving transaction");
    }

    // 重要方法 1
    public void executeCallbacks(ClientTransaction transaction) {
        final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
        if (callbacks == null) {
            // No callbacks to execute, return early.
            return;
        }

        final int size = callbacks.size();
        for (int i = 0; i < size; ++i) {
            final ClientTransactionItem item = callbacks.get(i);
            ... ...
            item.execute(mTransactionHandler, token, mPendingActions);
            item.postExecute(mTransactionHandler, token, mPendingActions);
            ... ...
        }
    }

    // 重要方法 2
    /** Transition to the final state if requested by the transaction. */
    private void executeLifecycleState(ClientTransaction transaction) {
        final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
        ... ...
        // 执行当前生命周期状态之前的状态
        cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */);

        // Execute the final transition with proper parameters.
        lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
        lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
    }

}

前面在 ActivityStack.startPausingLocked 方法里面 scheduleTransaction 传递的是 PauseActivityItem 对象,所以 executeLifecycleState 方法里调用的 execute 方法其实是 PauseActivityItem.execute方法。

2.28 PauseActivityItem.execute

// frameworks/base/core/java/android/app/servertransaction/PauseActivityItem.java

public class PauseActivityItem extends ActivityLifecycleItem {

    @Override
    public void execute(ClientTransactionHandler client, IBinder token,
            PendingTransactionActions pendingActions) {
        // 跳转到 ActivityThread.handlePauseActivity 方法
        client.handlePauseActivity(token, mFinished, mUserLeaving, mConfigChanges, pendingActions,
                "PAUSE_ACTIVITY_ITEM");
    }
}

2.29 ActivityThread.handlePauseActivity

// frameworks/base/core/java/android/app/ActivityThread.java

@Override
public void handlePauseActivity(IBinder token, boolean finished, boolean userLeaving,
        int configChanges, PendingTransactionActions pendingActions, String reason) {
    ActivityClientRecord r = mActivities.get(token);
    if (r != null) {
        ... ...
        performPauseActivity(r, finished, reason, pendingActions);
        ... ...
    }
}

2.30 ActivityThread.performPauseActivity

// frameworks/base/core/java/android/app/ActivityThread.java

final Bundle performPauseActivity(IBinder token, boolean finished, String reason,
        PendingTransactionActions pendingActions) {
    ActivityClientRecord r = mActivities.get(token);
    return r != null ? performPauseActivity(r, finished, reason, pendingActions) : null;
}

private Bundle performPauseActivity(ActivityClientRecord r, boolean finished, String reason,
        PendingTransactionActions pendingActions) {
    ... ...
    performPauseActivityIfNeeded(r, reason);
    ... ...
    return shouldSaveState ? r.state : null;
}

2.31 ActivityThread.performPauseActivityIfNeeded

// frameworks/base/core/java/android/app/ActivityThread.java

private void performPauseActivityIfNeeded(ActivityClientRecord r, String reason) {
    if (r.paused) {
        // You are already paused silly...
        return;
    }

    try {
        r.activity.mCalled = false;
        mInstrumentation.callActivityOnPause(r.activity);    // 关键方法
        if (!r.activity.mCalled) {
            throw new SuperNotCalledException("Activity " + safeToComponentShortString(r.intent)
                    + " did not call through to super.onPause()");
        }
    } catch (SuperNotCalledException e) {
        throw e;
    } catch (Exception e) {
        if (!mInstrumentation.onException(r.activity, e)) {
            throw new RuntimeException("Unable to pause activity "
                    + safeToComponentShortString(r.intent) + ": " + e.toString(), e);
        }
    }
    r.setState(ON_PAUSE);
}

2.32 Instrumentation.callActivityOnPause

// frameworks/base/core/java/android/app/Instrumentation.java

public void callActivityOnPause(Activity activity) {
    activity.performPause();      // 直接调用 Activity.performPause 方法
}

2.33 Activity.performPause

// frameworks/base/core/java/android/app/Activity.java

public class Activity extends ContextThemeWrapper
        implements LayoutInflater.Factory2,
        Window.Callback, KeyEvent.Callback,
        OnCreateContextMenuListener, ComponentCallbacks2,
        Window.OnWindowDismissedCallback, WindowControllerCallback,
        AutofillManager.AutofillClient {

    final void performPause() {
        ... ...
        onPause();
        ... ...
    }
}

2.34 流程小结


mWmLKx.png


至此,Launcher 的 onPause() 流程分析结束!同时,我们需要明白一点:在启动一个 Activity 的时候最先被执行的是栈顶的 Activity 的 onPause 方法。


三、启动进程

Launcher 的 onPause() 流程分析完,接下来我们看看新进程的启动流程:startSpecificActivityLocked() 方法。在这个方法中会去根据 进程线程 是否存在判断 App 是否已经启动。

3.1 ActivityStackSupervisor.startSpecificActivityLocked

// frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java

void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) {
    // Is this activity's application already running?
    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)) {
                app.addPackage(r.info.packageName, r.info.applicationInfo.longVersionCode,
                        mService.mProcessStats);
            }
            realStartActivityLocked(r, app, andResume, checkConfig);
            return;
        } catch (RemoteException e) {
            Slog.w(TAG, "Exception when starting activity "
                    + r.intent.getComponent().flattenToShortString(), e);
        }
    }

    // 启动新的进程,mService 为 ActivityManagerService
    mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
            "activity", r.intent.getComponent(), false, false, true);
}

如果已经启动,就会调用 ActivityManagerService.realStartActivityLocked 方法继续处理。

如果没有启动,则会调用 ActivityManagerService.startProcessLocked 方法创建新的进程处理。

3.2 ActivityManagerService.startProcessLocked -01

// frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

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

3.3 ActivityManagerService.startProcessLocked -02

// frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

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

3.3 ActivityManagerService.startProcessLocked -03

// frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

private final boolean startProcessLocked(ProcessRecord app,
        String hostingType, String hostingNameStr, String abiOverride) {
    return startProcessLocked(app, hostingType, hostingNameStr,
            false /* disableHiddenApiChecks */, abiOverride);
}

3.4 ActivityManagerService.startProcessLocked -04

// frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

private final boolean startProcessLocked(ProcessRecord app, String hostingType,
        String hostingNameStr, boolean disableHiddenApiChecks, String abiOverride) {

    try {
        ... ...
        return startProcessLocked(hostingType, hostingNameStr, entryPoint, app, uid, gids,
                runtimeFlags, mountExternal, seInfo, requiredAbi, instructionSet, invokeWith,
                startTime);
    } catch (RuntimeException e) {
        forceStopPackageLocked(app.info.packageName, UserHandle.getAppId(app.uid), false,
                false, true, false, false, UserHandle.getUserId(app.userId), "start failure");
        return false;
    }
}

3.5 ActivityManagerService.startProcessLocked -05

// frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

private boolean startProcessLocked(String hostingType, String hostingNameStr, String entryPoint,
        ProcessRecord app, int uid, int[] gids, int runtimeFlags, int mountExternal,
        String seInfo, String requiredAbi, String instructionSet, String invokeWith,
        long startTime) {
    ... ...
    final ProcessStartResult startResult = startProcess(hostingType, entryPoint, app,
                    uid, gids, runtimeFlags, mountExternal, seInfo, requiredAbi, instructionSet,
                    invokeWith, startTime);
    ... ...
}

3.6 ActivityManagerService.startProcess

// frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

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")) {
            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 {
            // 执行 Process.start 方法
            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);
    }
}

到这里,我们就明白了:ActivityManagerService.startProcessLocked 方法经过多次跳转最终会通过 Process.start 方法来为应用创建进程。


mWK4Vf.png


进程的创建流程和源码分析,这边我们就不再讨论了!在 【 Android ‘进程线程’ 】篇 – 聊聊 “进程” 如何 “创建” 一文中,我们作了详细的分析!


四、Activity 进程

我们在进程创建的博文中,讨论过源码最后会执行到 ActivityThread.main 方法,执行主线程的初始化工作。

4.1 初始化主线程

// frameworks/base/core/java/android/app/ActivityThread.java

public static void main(String[] args) {
    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");

    CloseGuard.setEnabled(false);

    Environment.initForCurrentUser();

    EventLogger.setReporter(new EventLoggingReporter());

    final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
    TrustedCertificateStore.setDefaultUserDirectory(configDir);

    Process.setArgV0("<pre-initialized>");

    Looper.prepareMainLooper();    // 创建主线程 looper

    long startSeq = 0;
    if (args != null) {
        for (int i = args.length - 1; i >= 0; --i) {
            if (args[i] != null && args[i].startsWith(PROC_START_SEQ_IDENT)) {
                startSeq = Long.parseLong(
                        args[i].substring(PROC_START_SEQ_IDENT.length()));
            }
        }
    }
    ActivityThread thread = new ActivityThread();    // 初始化 ActivityThread
    thread.attach(false, startSeq);    // attach 到系统进程

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

    if (false) {
        Looper.myLooper().setMessageLogging(new
                LogPrinter(Log.DEBUG, "ActivityThread"));
    }

    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
    Looper.loop();    // 主线程启动,进入循环状态

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

4.2 启动 Activity

// frameworks/base/core/java/android/app/ActivityThread.java

private void attach(boolean system, long startSeq) {
    sCurrentActivityThread = this;
    mSystemThread = system;
    if (!system) {
        ... ...
        final IActivityManager mgr = ActivityManager.getService();
        try {
            // 通过 ActivityManagerService 为这个应用绑定一个 Application
            mgr.attachApplication(mAppThread, startSeq);
        } catch (RemoteException ex) {
            throw ex.rethrowFromSystemServer();
        }
        // 添加一个垃圾回收观察者,每当系统触发垃圾回收的时候就会在 run 方法里面
        // 去计算应用使用了多少内存,如果超过总量的四分之三就会尝试释放内存
        BinderInternal.addGcWatcher(new Runnable() {
            @Override public void run() {
                if (!mSomeActivitiesChanged) {
                    return;
                }
                Runtime runtime = Runtime.getRuntime();
                long dalvikMax = runtime.maxMemory();
                long dalvikUsed = runtime.totalMemory() - runtime.freeMemory();
                if (dalvikUsed > ((3*dalvikMax)/4)) {
                    if (DEBUG_MEMORY_TRIM) Slog.d(TAG, "Dalvik max=" + (dalvikMax/1024)
                            + " total=" + (runtime.totalMemory()/1024)
                            + " used=" + (dalvikUsed/1024));
                    mSomeActivitiesChanged = false;
                    try {
                        mgr.releaseSomeActivities(mAppThread);
                    } catch (RemoteException e) {
                        throw e.rethrowFromSystemServer();
                    }
                }
            }
        });
    } else {
        ... ...
    }
    ... ...
    // 为根 View 添加 config 回调接收 config 变化相关的信息
    ViewRootImpl.addConfigCallback(configChangedCallback);
}

4.2.1 ActivityManagerService.attachApplication

// frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

@Override
public final void attachApplication(IApplicationThread thread, long startSeq) {
    synchronized (this) {
        int callingPid = Binder.getCallingPid();
        final int callingUid = Binder.getCallingUid();
        final long origId = Binder.clearCallingIdentity();
        attachApplicationLocked(thread, callingPid, callingUid, startSeq);
        Binder.restoreCallingIdentity(origId);
    }
}

4.2.2 ActivityManagerService.attachApplicationLocked

// frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

private final boolean attachApplicationLocked(IApplicationThread thread,
        int pid, int callingUid, long startSeq) {
    ... ... 
    // See if the top visible activity is waiting to run in this process...
    if (normalMode) {
        try {
            if (mStackSupervisor.attachApplicationLocked(app)) {
                didSomething = true;
            }
        } catch (Exception e) {
            Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
            badApp = true;
        }
    }
    ... ...
    return true;
}

4.3 ActivityStackSupervisor.attachApplicationLocked

// frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java

boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
    final String processName = app.processName;
    boolean didSomething = false;
    for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
        final ActivityDisplay display = mActivityDisplays.valueAt(displayNdx);
        for (int stackNdx = display.getChildCount() - 1; stackNdx >= 0; --stackNdx) {
            final ActivityStack stack = display.getChildAt(stackNdx);
            if (!isFocusedStack(stack)) {
                continue;
            }
            stack.getAllRunningVisibleActivitiesLocked(mTmpActivityList);
            final ActivityRecord top = stack.topRunningActivityLocked();
            final int size = mTmpActivityList.size();
            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 {
                        // 执行 realStartActivityLocked 方法
                        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;
}

4.4 ActivityStackSupervisor.realStartActivityLocked

realStartActivityLocked 就是应用进程已经启动的情况下去启动 Activity 所调用的方法。

// frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java

final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
        boolean andResume, boolean checkConfig) throws RemoteException {

    try {
        ... ...
        try {
            ... ...
            final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread,
                    r.appToken);
            // 为 ClientTransaction 对象添加 LaunchActivityItem 的 callback
            clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
                    System.identityHashCode(r), r.info,
                    mergedConfiguration.getGlobalConfiguration(),
                    mergedConfiguration.getOverrideConfiguration(), r.compat,
                    r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,
                    r.persistentState, results, newIntents, mService.isNextTransitionForward(),
                    profilerInfo));

            final ActivityLifecycleItem lifecycleItem;
            // 设置当前的生命周期状态
            if (andResume) {
                lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward());
            } else {
                lifecycleItem = PauseActivityItem.obtain();
            }
            clientTransaction.setLifecycleStateRequest(lifecycleItem);

            // 调用 ClientLifecycleManager.scheduleTransaction 方法
            mService.getLifecycleManager().scheduleTransaction(clientTransaction);
    ... ...
}

调用 ClientLifecycleManager.scheduleTransaction 方法之后具体是如何执行的前面已经分析过了,这里就不再分析了。

我们这里看一下执行 callback 后跳转到 LaunchActivityItem.execute方法。

4.5 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);
    // 调用 ActivityThread.handleLaunchActivity 方法
    client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
    Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}

4.6 ActivityThread.handleLaunchActivity

// frameworks/base/core/java/android/app/ActivityThread.java

public Activity handleLaunchActivity(ActivityClientRecord r,
        PendingTransactionActions pendingActions, Intent customIntent) {
    ... ...
    final Activity a = performLaunchActivity(r, customIntent);
    ... ...
}

4.7 ActivityThread.performLaunchActivity

// frameworks/base/core/java/android/app/ActivityThread.java

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    ActivityInfo aInfo = r.activityInfo;
    if (r.packageInfo == null) {
        r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
                Context.CONTEXT_INCLUDE_CODE);
    }

    // 初始化 ComponentName
    ComponentName component = r.intent.getComponent();
    if (component == null) {
        component = r.intent.resolveActivity(
            mInitialApplication.getPackageManager());
        r.intent.setComponent(component);
    }

    if (r.activityInfo.targetActivity != null) {
        component = new ComponentName(r.activityInfo.packageName,
                r.activityInfo.targetActivity);
    }

    // 初始化 ContextImpl 和 Activity
    ContextImpl appContext = createBaseContextForActivity(r);
    Activity activity = null;
    try {
        java.lang.ClassLoader cl = appContext.getClassLoader();
        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) {
        ... ...
    }

    try {
        // 初始化Application
        Application app = r.packageInfo.makeApplication(false, mInstrumentation);

        if (activity != null) {
            CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
            Configuration config = new Configuration(mCompatConfiguration);
            if (r.overrideConfig != null) {
                config.updateFrom(r.overrideConfig);
            }
            Window window = null;
            if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
                window = r.mPendingRemoveWindow;
                r.mPendingRemoveWindow = null;
                r.mPendingRemoveWindowManager = null;
            }
            appContext.setOuterContext(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);

            if (customIntent != null) {
                activity.mIntent = customIntent;
            }
            r.lastNonConfigurationInstances = null;
            checkAndBlockForNetworkAccess();
            activity.mStartedActivity = false;
            // 设置 Activity 的 Theme
            int theme = r.activityInfo.getThemeResource();
            if (theme != 0) {
                activity.setTheme(theme);
            }

            activity.mCalled = false;
            // 调用 Instrumentation.callActivityOnCreate 方法
            if (r.isPersistable()) {
                mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
            } else {
                mInstrumentation.callActivityOnCreate(activity, r.state);
            }
            if (!activity.mCalled) {
            ... ...
            r.activity = activity;
        }
        r.setState(ON_CREATE);

        mActivities.put(r.token, r);

    } catch (SuperNotCalledException e) {
        ... ...
    }

    return activity;
}


mWDKMt.png


4.8 Instrumentation.callActivityOnCreate

// frameworks/base/core/java/android/app/Instrumentation.java

public void callActivityOnCreate(Activity activity, Bundle icicle,
        PersistableBundle persistentState) {
    prePerformCreate(activity);
    activity.performCreate(icicle, persistentState);  // 执行此方法
    postPerformCreate(activity);
}

4.9 Activity.performCreate

// frameworks/base/core/java/android/app/Activity.java

final void performCreate(Bundle icicle, PersistableBundle persistentState) {
    ... ...
    if (persistentState != null) {
        onCreate(icicle, persistentState);
    } else {
        onCreate(icicle);
    }
    ... ...
}

至此 executeCallbacks() 执行完毕,开始执行 executeLifecycleState 方法,会先执行 cycleToPath 方法。

4.10 TransactionExecutor.cycleToPath

// frameworks/base/core/java/android/app/servertransaction/TransactionExecutor.java

private void cycleToPath(ActivityClientRecord r, int finish,
            boolean excludeLastState) {
    final int start = r.getLifecycleState();
    log("Cycle from: " + start + " to: " + finish + " excludeLastState:" + excludeLastState);
    final IntArray path = mHelper.getLifecyclePath(start, finish, excludeLastState);
    performLifecycleSequence(r, path);
}

4.11 TransactionExecutor.performLifecycleSequence

// frameworks/base/core/java/android/app/servertransaction/TransactionExecutor.java

private void performLifecycleSequence(ActivityClientRecord r, IntArray path) {
        final int size = path.size();
    for (int i = 0, state; i < size; i++) {
        state = path.get(i);
        log("Transitioning to state: " + state);
        // 生命周期状态是从 ON_CREATE 状态到 ON_RESUME 状态,中间有一个 ON_START 状态,
        // 所以会执行 ActivityThread.handleStartActivity 方法。
        switch (state) {
            case ON_CREATE:
                mTransactionHandler.handleLaunchActivity(r, mPendingActions,
                        null /* customIntent */);
                break;
            case ON_START:
                mTransactionHandler.handleStartActivity(r, mPendingActions);
                break;
            case ON_RESUME:
                mTransactionHandler.handleResumeActivity(r.token, false /* finalStateRequest */,
                        r.isForward, "LIFECYCLER_RESUME_ACTIVITY");
                break;
            case ON_PAUSE:
                mTransactionHandler.handlePauseActivity(r.token, false /* finished */,
                        false /* userLeaving */, 0 /* configChanges */, mPendingActions,
                        "LIFECYCLER_PAUSE_ACTIVITY");
                break;
            case ON_STOP:
                mTransactionHandler.handleStopActivity(r.token, false /* show */,
                        0 /* configChanges */, mPendingActions, false /* finalStateRequest */,
                        "LIFECYCLER_STOP_ACTIVITY");
                break;
            case ON_DESTROY:
                mTransactionHandler.handleDestroyActivity(r.token, false /* finishing */,
                        0 /* configChanges */, false /* getNonConfigInstance */,
                        "performLifecycleSequence. cycling to:" + path.get(size - 1));
                break;
            case ON_RESTART:
                mTransactionHandler.performRestartActivity(r.token, false /* start */);
                break;
            default:
                throw new IllegalArgumentException("Unexpected lifecycle state: " + state);
        }
    }
}

4.12 ActivityThread.handleStartActivity

// frameworks/base/core/java/android/app/ActivityThread.java

public void handleStartActivity(ActivityClientRecord r,
        PendingTransactionActions pendingActions) {
    ... ...
    // Start
    activity.performStart("handleStartActivity");
    r.setState(ON_START);
    ... ...
}

4.13 Activity.performStart

// frameworks/base/core/java/android/app/Activity.java

final void performStart(String reason) {
    ... ...
    mInstrumentation.callActivityOnStart(this);
    ... ...
}

4.14 Instrumentation.callActivityOnStart

// frameworks/base/core/java/android/app/Instrumentation.java

public void callActivityOnStart(Activity activity) {
    // 经过多次跳转最后会调用 Activity.onStart 方法
    activity.onStart();
}

执行完毕 cycleToPath,开始执行 ResumeActivityItem.execute 方法。

4.15 ResumeActivityItem.execute

// frameworks/base/core/java/android/app/servertransaction/ResumeActivityItem.java

public void execute(ClientTransactionHandler client, IBinder token,
        PendingTransactionActions pendingActions) {
    Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityResume");
    client.handleResumeActivity(token, true /* finalStateRequest */, mIsForward,
            "RESUME_ACTIVITY");
    Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}

4.16 ActivityThread.handleResumeActivity

// frameworks/base/core/java/android/app/ActivityThread.java

public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
        String reason) {
    ... ...
    // TODO Push resumeArgs into the activity for consideration
    final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
    if (r == null) {
        // We didn't actually resume the activity, so skipping any follow-up actions.
        return;
    }
    ... ...
    if (localLOGV) Slog.v(TAG, "Scheduling idle handler for " + r);

    // 这边的方法我们在最后会说明,其中涉及到 onStop() 方法
    Looper.myQueue().addIdleHandler(new Idler());
}

4.17 ActivityThread.performResumeActivity

// frameworks/base/core/java/android/app/ActivityThread.java

public ActivityClientRecord performResumeActivity(IBinder token, boolean finalStateRequest,
        String reason) {
    ... ...
    try {
        r.activity.onStateNotSaved();
        r.activity.mFragments.noteStateNotSaved();
        checkAndBlockForNetworkAccess();
        if (r.pendingIntents != null) {
            deliverNewIntents(r, r.pendingIntents);
            r.pendingIntents = null;
        }
        if (r.pendingResults != null) {
            deliverResults(r, r.pendingResults, reason);
            r.pendingResults = null;
        }
        // 执行 performResume 方法
        r.activity.performResume(r.startsNotResumed, reason);

        r.state = null;
        r.persistentState = null;
        r.setState(ON_RESUME);
    } catch (Exception e) {
        if (!mInstrumentation.onException(r.activity, e)) {
            throw new RuntimeException("Unable to resume activity "
                    + r.intent.getComponent().toShortString() + ": " + e.toString(), e);
        }
    }
    return r;
}

4.18 Activity.performResume

// frameworks/base/core/java/android/app/Activity.java

final void performResume(boolean followedByPause, String reason) {
    performRestart(true /* start */, reason);
    ... ...
    // mResumed is set by the instrumentation
    mInstrumentation.callActivityOnResume(this);
    ... ...
}

4.19 Instrumentation.callActivityOnResume

// frameworks/base/core/java/android/app/Instrumentation.java

public void callActivityOnResume(Activity activity) {
    activity.mResumed = true;
    // 最终调用到 Activity.onResume 方法
    activity.onResume();
    ... ...
}

至此,Activity 启动完毕。


mWR9HI.png


五、栈顶活动 onStop

我们在讨论 ActivityThread.handleResumeActivity 源码的时候,最后一行代码还未讨论。

// frameworks/base/core/java/android/app/ActivityThread.java

public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
        String reason) {
    ... ...
    final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
    ... ...
    // 当 MessageQueue 空闲的时候就会执行这个 Handler,即执行完当前 Activity 的 onResume() 方法后执行
    Looper.myQueue().addIdleHandler(new Idler());
}

为什么要单独讨论这行代码,因为上面分析了栈顶 ActivityonPause()新 ActivityonCreate()、onStart()、onResume(),但缺失一个栈顶 ActivityonStop() 生命周期,此方法就是在这行代码中处理的。

5.1 Idler

// frameworks/base/core/java/android/app/ActivityThread.java

private class Idler implements MessageQueue.IdleHandler {
    @Override
    public final boolean queueIdle() {
        ... ...
        if (a != null) {
            mNewActivities = null;
            IActivityManager am = ActivityManager.getService();
            ActivityClientRecord prev;
            do {
                if (a.activity != null && !a.activity.mFinished) {
                    try {
                        // 调用 ActivityManagerService.activityIdle 方法
                        am.activityIdle(a.token, a.createdConfig, stopProfiling);
                        a.createdConfig = null;
                    } catch (RemoteException ex) {
                        throw ex.rethrowFromSystemServer();
                    }
                }
                prev = a;
                a = a.nextIdle;
                prev.nextIdle = null;
            } while (a != null);
        }
        ... ...
        return false;
    }
}

5.2 ActivityManagerService.activityIdle

// frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
    final long origId = Binder.clearCallingIdentity();
    synchronized (this) {
        ActivityStack stack = ActivityRecord.getStackLocked(token);
        if (stack != null) {
            // 调用 ActivityStackSupervisor.activityIdleInternalLocked 方法
            ActivityRecord r =
                    mStackSupervisor.activityIdleInternalLocked(token, false /* fromTimeout */,
                            false /* processPausingActivities */, config);
            if (stopProfiling) {
                if ((mProfileProc == r.app) && mProfilerInfo != null) {
                    clearProfilerLocked();
                }
            }
        }
    }
    Binder.restoreCallingIdentity(origId);
}

5.3 ActivityStackSupervisor.activityIdleInternalLocked

// frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java

final ActivityRecord activityIdleInternalLocked(final IBinder token, boolean fromTimeout,
        boolean processPausingActivities, Configuration config) {

    for (int i = 0; i < NS; i++) {
        r = stops.get(i);
        final ActivityStack stack = r.getStack();
        if (stack != null) {
            if (r.finishing) {
                stack.finishCurrentActivityLocked(r, ActivityStack.FINISH_IMMEDIATELY, false,
                        "activityIdleInternalLocked");
            } else {
                stack.stopActivityLocked(r);
            }
        }
    }
    ... ...
    return r;
}

5.4 ActivityStack.stopActivityLocked

// frameworks/base/services/core/java/com/android/server/am/ActivityStack.java

final void stopActivityLocked(ActivityRecord r) {
    ... ...
    if (r.app != null && r.app.thread != null) {
        adjustFocusedActivityStack(r, "stopActivity");
        r.resumeKeyDispatchingLocked();
        try {
            ... ...
            mService.getLifecycleManager().scheduleTransaction(r.app.thread, r.appToken,
                    StopActivityItem.obtain(r.visible, r.configChangeFlags));
            if (shouldSleepOrShutDownActivities()) {
                r.setSleeping(true);
            }
            Message msg = mHandler.obtainMessage(STOP_TIMEOUT_MSG, r);
            mHandler.sendMessageDelayed(msg, STOP_TIMEOUT);
        } catch (Exception e) {
            ... ...
        }
    }
}

又见到了 ClientLifecycleManager.scheduleTransaction 方法,前面已经分析过多次,会去执行 StopActivityItem.execute 方法,然后经过多次跳转,最终执行了 Activity.onStop 方法。


mWh5Px.png


5.5 StopActivityItem.execute

// frameworks/base/core/java/android/app/servertransaction/StopActivityItem.java

@Override
public void execute(ClientTransactionHandler client, IBinder token,
        PendingTransactionActions pendingActions) {
    Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityStop");
    client.handleStopActivity(token, mShowWindow, mConfigChanges, pendingActions,
            true /* finalStateRequest */, "STOP_ACTIVITY_ITEM");
    Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}

5.6 ActivityThread.handleStopActivity

// frameworks/base/core/java/android/app/ActivityThread.java

@Override
public void handleStopActivity(IBinder token, boolean show, int configChanges,
        PendingTransactionActions pendingActions, boolean finalStateRequest, String reason) {
    ... ...
    performStopActivityInner(r, stopInfo, show, true /* saveState */, finalStateRequest,
                reason);
    ... ...
}

5.7 ActivityThread.performStopActivityInner

// frameworks/base/core/java/android/app/ActivityThread.java

private void performStopActivityInner(ActivityClientRecord r, StopInfo info, boolean keepShown,
        boolean saveState, boolean finalStateRequest, String reason) {
    if (r != null) {
        ... ...
        if (!keepShown) {
            callActivityOnStop(r, saveState, reason);
        }
    }
}

5.8 ActivityThread.callActivityOnStop

// frameworks/base/core/java/android/app/ActivityThread.java

private void callActivityOnStop(ActivityClientRecord r, boolean saveState, String reason) {
    ... ...
    try {
        r.activity.performStop(false /*preserveWindow*/, reason);
    } catch (SuperNotCalledException e) {
        throw e;
    } catch (Exception e) {
        ... ...
    }
    ... ...
}

5.9 Activity.performStop

// frameworks/base/core/java/android/app/Activity.java

final void performStop(boolean preserveWindow, String reason) {
    ... ...
    if (!mStopped) {
        ... ...
        mInstrumentation.callActivityOnStop(this);
    }
}

5.10 Instrumentation.callActivityOnStop

// frameworks/base/core/java/android/app/Instrumentation.java

public void callActivityOnStop(Activity activity) {
    activity.onStop();
}


mW7oRI.png