2

前言

由于源码分析的代码量比较大,大部分博客网站的内容显示页面都比较窄,显示出来的效果都异常丑陋,所以您也可以直接查看 《 Thinking in Android 》 来阅读这边文章,希望这篇文章能帮你梳理清楚应用的启动流程。

核心源码

Source Path
BaseDraggingActivity.java packages/apps/Launcher3//src/com/android/launcher3/BaseDraggingActivity.java
ItemClickHandler.java packages/apps/Launcher3/src/com/android/launcher3/touch/ItemClickHandler.java
Launcher.java packages/apps/Launcher3/src/com/android/launcher3/Launcher.java
Activity.java frameworks/base/core/java/android/app/Activity.java
ActivityManager.java frameworks/base/core/java/android/app/ActivityManager.java
ActivityTaskManager.java frameworks/base/core/java/android/app/ActivityTaskManager.java
ActivityThread.java frameworks/base/core/java/android/app/ActivityThread.java
ClientTransaction.java frameworks/base/core/java/android/app/servertransaction/ClientTransaction.java
ClientTransactionHandler.java frameworks/base/core/java/android/app/ClientTransactionHandler.java
ActivityManagerInternal.java frameworks/base/core/java/android/app/ActivityManagerInternal.java
Instrumentation.java frameworks/base/core/java/android/app/Instrumentation.java
LaunchActivityItem.java frameworks/base/core/java/android/app/servertransaction/LaunchActivityItem.java
PauseActivityItem.java frameworks/base/core/java/android/app/servertransaction/PauseActivityItem.java
Process.java frameworks/base/core/java/android/os/Process.java
TransactionExecutor.java frameworks/base/core/java/android/app/servertransaction/TransactionExecutor.java
ActivityManagerService.java frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
ActivityTaskManagerService.java frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
RootActivityContainer.java frameworks/base/services/core/java/com/android/server/wm/RootActivityContainer.java
ActivityStack.java frameworks/base/services/core/java/com/android/server/wm/ActivityStack.java
ActivityStarter.java frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java
ActivityStartController.java frameworks/base/services/core/java/com/android/server/wm/ActivityStartController.java
ActivityStackSupervisor.java frameworks/base/services/core/java/com/android/server/wm/ActivityStackSupervisor.java
ClientLifecycleManager.java frameworks/base/services/core/java/com/android/server/wm/ClientLifecycleManager.java
ProcessList.java frameworks/base/services/core/java/com/android/server/am/ProcessList.java
ActivityTaskManagerInternal.java frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerInternal.java


前言

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

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

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


一、Launcher 的 onPause 流程

我们既然要启动新的 APK 置于前台,那么当前活动必然要被切换到后台,所以首先涉及到的就是 Launcher 的 onPause 流程。

1.1 ItemClickHandler.onClick()

当点击应用程序 Launcher 的某个图标时,会触发回调接口 ItemClickHandler

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

public class Launcher extends BaseDraggingActivity implements LauncherExterns,
        Callbacks, LauncherProviderChangeListener, UserEventDelegate,
        InvariantDeviceProfile.OnIDPChangeListener {

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

}

1.2 ItemClickHandler.startAppShortcutOrInfoActivity()

回调接口 ItemClickHandler 会执行 onClick() 方法中的 startAppShortcutOrInfoActivity()

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

public class ItemClickHandler {

    public static final OnClickListener INSTANCE = getInstance(null);

    public static final OnClickListener getInstance(String sourceContainer) {
        return v -> onClick(v, sourceContainer);
    }

    private static void onClick(View v, String sourceContainer) {
        ... ...

        Object tag = v.getTag();
        if (tag instanceof WorkspaceItemInfo) {
            onClickAppShortcut(v, (WorkspaceItemInfo) tag, launcher, sourceContainer);
        } else if (tag instanceof FolderInfo) {
            if (v instanceof FolderIcon) {
                onClickFolderIcon(v);
            }
        } else if (tag instanceof AppInfo) {
            // 调用 startAppShortcutOrInfoActivity() 方法
            startAppShortcutOrInfoActivity(v, (AppInfo) tag, launcher,
                    sourceContainer == null ? CONTAINER_ALL_APPS: sourceContainer);
        } else if (tag instanceof LauncherAppWidgetInfo) {
            if (v instanceof PendingAppWidgetHostView) {
                onClickPendingWidget((PendingAppWidgetHostView) v, launcher);
            }
        }        
    }

    private static void startAppShortcutOrInfoActivity(View v, ItemInfo item, Launcher launcher,
            @Nullable String sourceContainer) {
        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 WorkspaceItemInfo) {
            WorkspaceItemInfo si = (WorkspaceItemInfo) item;
            if (si.hasStatusFlag(WorkspaceItemInfo.FLAG_SUPPORTS_WEB_UI)
                    && Intent.ACTION_VIEW.equals(intent.getAction())) {
                intent = new Intent(intent);
                intent.setPackage(null);
            }
        }
        if (v != null && launcher.getAppTransitionManager().supportsAdaptiveIconAnimation()) {
            FloatingIconView.fetchIcon(launcher, v, item, true /* isOpening */);
        }
        // 调用 startActivitySafely() 方法
        launcher.startActivitySafely(v, intent, item, sourceContainer);
    }

}

1.3 Launcher.startActivitySafely()

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

public class Launcher extends BaseDraggingActivity implements LauncherExterns,
        Callbacks, LauncherProviderChangeListener, UserEventDelegate,
        InvariantDeviceProfile.OnIDPChangeListener {

    public boolean startActivitySafely(View v, Intent intent, ItemInfo item,
            @Nullable String sourceContainer) {
        if (!hasBeenResumed()) {
            addOnResumeCallback(() -> startActivitySafely(v, intent, item, sourceContainer));
            UiFactory.clearSwipeSharedState(true /* finishAnimation */);
            return true;
        }

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

}

1.4 BaseDraggingActivity.startActivitySafely()

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

public abstract class BaseDraggingActivity extends BaseActivity
        implements WallpaperColorInfo.OnChangeListener {

    public boolean startActivitySafely(View v, Intent intent, @Nullable ItemInfo item,
            @Nullable String sourceContainer) {
        ... ...

        // 添加标志,表示要在一个新的 Task 中启动这个 Activity
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (v != null) {
            intent.setSourceBounds(getViewBounds(v));
        }
        try {
            boolean isShortcut = (item instanceof WorkspaceItemInfo)
                    && (item.itemType == Favorites.ITEM_TYPE_SHORTCUT
                    || item.itemType == Favorites.ITEM_TYPE_DEEP_SHORTCUT)
                    && !((WorkspaceItemInfo) item).isPromise();
            if (isShortcut) {
                // Shortcuts need some special checks due to legacy reasons.
                startShortcutIntentSafely(intent, optsBundle, item, sourceContainer);
            } else if (user == null || user.equals(Process.myUserHandle())) {
                // 调用 Activity.startActivity() 方法
                startActivity(intent, optsBundle);
                AppLaunchTracker.INSTANCE.get(this).onStartApp(intent.getComponent(),
                        Process.myUserHandle(), sourceContainer);
            } else {
                LauncherAppsCompat.getInstance(this).startActivityForProfile(
                        intent.getComponent(), user, intent.getSourceBounds(), optsBundle);
                AppLaunchTracker.INSTANCE.get(this).onStartApp(intent.getComponent(), user,
                        sourceContainer);
            }
            getUserEventDispatcher().logAppLaunch(v, intent);
            getStatsLogManager().logAppLaunch(v, intent);
            return true;
        } catch (NullPointerException|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;
    }

}

1.5 Activity.startActivity()

// framework/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, ContentCaptureManager.ContentCaptureClient {
        
    @Override
    public void startActivity(Intent intent, @Nullable Bundle options) {
        if (options != null) {
            // options 表示 Launcher 启动 Activity 时的动画效果
            startActivityForResult(intent, -1, options);
        } else {
            // Note we want to go through this call for compatibility with
            // applications that may have overridden the method.
            startActivityForResult(intent, -1);
        }
    }

}

1.6 Activity.startActivityForResult()

// framework/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, ContentCaptureManager.ContentCaptureClient {

    private Instrumentation mInstrumentation;

    /*package*/ ActivityThread mMainThread;

    public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
            @Nullable Bundle options) {
        // mParent 代表目前 Launcher Activity 的状态,第一次启动 Activity,走此条分支
        if (mParent == null) {
            options = transferSpringboardActivityOptions(options);
            Instrumentation.ActivityResult ar =
                // 执行 mInstrumentation.execStartActivity() 方法
                mInstrumentation.execStartActivity(
                    this, mMainThread.getApplicationThread(), mToken, this,
                    intent, requestCode, options);
            if (ar != null) {
                mMainThread.sendActivityResult(
                    mToken, mEmbeddedID, requestCode, ar.getResultCode(),
                    ar.getResultData());
            }
            if (requestCode >= 0) {
                mStartedActivity = true;
            }

            cancelInputsAndStartExitTransition(options);
        } else {
            if (options != null) {
                // 最终也会调用 mInstrumentation.execStartActivity() 方法
                mParent.startActivityFromChild(this, intent, requestCode, options);
            } else {
                mParent.startActivityFromChild(this, intent, requestCode);
            }
        }
    }

}

mInstrumentation.execStartActivity() 方法中有一个 mMainThread.getApplicationThread() 参数,mMainThreadActivity 类的 成员变量,它的类型是 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() 获得的是 ActivityThread 内部成员变量 ApplicationThread,它是一个 Binder 对象。这个对象是干嘛用的,我们后面会讲解到。

1.7 Instrumentation.execStartActivity()

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

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

public class Instrumentation {

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

        try {
            intent.migrateExtraStreamToClipData();
            intent.prepareToLeaveProcess(who);
            // 调用 ActivityTaskManager.getService().startActivity() 方法
            int result = ActivityTaskManager.getService()
                .startActivity(whoThread, who.getBasePackageName(), intent,
                        intent.resolveTypeIfNeeded(who.getContentResolver()),
                        token, target, requestCode, 0, null, options);
            checkStartActivityResult(result, intent);
        } catch (RemoteException e) {
            throw new RuntimeException("Failure from system", e);
        }
        return null;
    }

}

看下 ActivityTaskManager.getService() 方法:

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

public class ActivityTaskManager {

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

    private static final Singleton<IActivityTaskManager> IActivityTaskManagerSingleton =
            new Singleton<IActivityTaskManager>() {
                @Override
                protected IActivityTaskManager create() {
                    final IBinder b = ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE);
                    return IActivityTaskManager.Stub.asInterface(b);
                }
            };

}

// frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java

public class ActivityTaskManagerService extends IActivityTaskManager.Stub {}

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

ActivityTaskManager.getService().startActivity() 方法实际上调用到了 ActivityTaskManagerServicestartActivity() 方法。

1.8 ActivityTaskManagerService.startActivity()

下面看看 ActivityManagerServicestartActivity 方法:

// frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java

public class ActivityTaskManagerService extends IActivityTaskManager.Stub {

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

}

1.9 ActivityTaskManagerService.startActivityAsUser()

// frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java

public class ActivityTaskManagerService extends IActivityTaskManager.Stub {

    ActivityStartController getActivityStartController() {
        return mActivityStartController;
    }

    @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");

        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)    // 设置了 mRequest.mayWait = true,后面会用到
                .execute();

    }

}

1.10 ActivityStartController.obtainStarter()

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

import com.android.server.am.ActivityStarter.Factory;

public class ActivityStartController {

    private final Factory mFactory;

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

}

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

mFactory.obtain() - -> DefaultFactory.obtain()
// frameworks/base/services/core/java/com/android/server/am/ActivityStarter.java

class ActivityStarter {

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

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

            return starter;
        }

    }

}
mFactory.obtain().setIntent() - -> ActivityStarter.setIntent()
// frameworks/base/services/core/java/com/android/server/am/ActivityStarter.java

class ActivityStarter {

    private Request mRequest = new Request();

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

}
mFactory.obtain().setIntent(intent).setReason() - ->ActivityStarter.setReason()
// frameworks/base/services/core/java/com/android/server/am/ActivityStarter.java

class ActivityStarter {

    private Request mRequest = new Request();

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

}

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

1.11 ActivityStarter.execute()

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

class ActivityStarter {

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

    /**
     * Starts an activity based on the request parameters provided earlier.
     * @return The starter result.
     */
    int execute() {
        try {
            if (mRequest.mayWait) {    // setMayWait() 方法中置为 true
                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.12 流程小结

由于代码追踪起来比较绕,我们分段通过流程图回顾下方法调用逻辑。

YBhwlV.png

1.13 ActivityStarter.startActivityMayWait()

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

class ActivityStarter {

    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) {
        ... ...

        // 解析 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.mGlobalLock) {
            ... ...

            // 用于记录 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,
                    allowBackgroundActivityStart);

            Binder.restoreCallingIdentity(origId);
            ... ...

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

}

1.14 ActivityStarter.startActivity() - - 01

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

class ActivityStarter {

    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) {
        ... ...

        // 调用 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,
                allowBackgroundActivityStart);
        ... ...

        return getExternalResult(mLastStartActivityResult);
    }

}

1.15 ActivityStarter.startActivity() - - 02

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

class ActivityStarter {

    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) {
        ... ...

        final int res = startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
                true /* doResume */, checkedOptions, inTask, outActivity, restrictedBgActivity);
        ... ...

    }

}

1.16 ActivityStarter.startActivity() - - 03

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

class ActivityStarter {

    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();
            // 调用 startActivityUnchecked() 方法
            result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
                    startFlags, doResume, options, inTask, outActivity, restrictedBgActivity);
        } finally {
            final ActivityStack currentStack = r.getActivityStack();
            startedActivityStack = currentStack != null ? currentStack : mTargetStack;

            if (ActivityManager.isStartResultSuccessful(result)) {
                if (startedActivityStack != null) {
                    final ActivityRecord currentTop =
                            startedActivityStack.topRunningActivityLocked();
                    if (currentTop != null && currentTop.shouldUpdateConfigForDisplayChanged()) {
                        mRootActivityContainer.ensureVisibilityAndConfig(
                                currentTop, currentTop.getDisplayId(),
                                true /* markFrozenIfConfigChanged */, false /* deferResume */);
                    }
                }
            } else {
                final ActivityStack stack = mStartActivity.getActivityStack();
                if (stack != null) {
                    stack.finishActivityLocked(mStartActivity, RESULT_CANCELED,
                            null /* intentResultData */, "startActivity", true /* oomAdj */);
                }

                if (startedActivityStack != null && startedActivityStack.isAttached()
                        && startedActivityStack.numActivities() == 0
                        && !startedActivityStack.isActivityTypeHome()) {
                    startedActivityStack.remove();
                }
            }
            // 继续布局
            mService.mWindowManager.continueSurfaceLayout();
        }

        postStartActivityProcessing(r, result, startedActivityStack);

        return result;
    }

}

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

1.17 ActivityStarter.startActivityUnchecked()

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

class ActivityStarter {

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

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

        final int preferredWindowingMode = mLaunchParams.mWindowingMode;

        // 计算出启动的 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.getTaskRecord().topRunningActivityLocked();
            if (!mTargetStack.isFocusable()
                    || (topTaskActivity != null && topTaskActivity.mTaskOverlay
                    && mStartActivity != topTaskActivity)) {
                mTargetStack.ensureActivitiesVisibleLocked(mStartActivity, 0, !PRESERVE_WINDOWS);
                mTargetStack.getDisplay().mDisplayContent.executeAppTransition();
            } else {
                if (mTargetStack.isFocusable()
                        && !mRootActivityContainer.isTopDisplayFocusedStack(mTargetStack)) {
                    mTargetStack.moveToFront("startActivityUnchecked");
                }
                // 调用 resumeFocusedStacksTopActivities() 方法
                mRootActivityContainer.resumeFocusedStacksTopActivities(
                        mTargetStack, mStartActivity, mOptions);
            }
        } else if (mStartActivity != null) {
            mSupervisor.mRecentTasks.add(mStartActivity.getTaskRecord());
        }
        mRootActivityContainer.updateUserStack(mStartActivity.mUserId, mTargetStack);

        mSupervisor.handleNonResizableTaskIfNeeded(mStartActivity.getTaskRecord(),
                preferredWindowingMode, mPreferredDisplayId, mTargetStack);

        return START_SUCCESS;
    }

}

1.18 RootActivityContainer.resumeFocusedStacksTopActivities()

// frameworks/base/services/core/java/com/android/server/wm/RootActivityContainer.java

class RootActivityContainer extends ConfigurationContainer
        implements DisplayManager.DisplayListener {

    boolean resumeFocusedStacksTopActivities(
            ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
        ... ...

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

        return result;
    }

}

1.19 ActivityStack.resumeTopActivityUncheckedLocked()

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

class ActivityStack extends ConfigurationContainer {

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

        boolean result = false;

        try {
            mInResumeTopActivity = true;
            // 调用 resumeTopActivityInnerLocked() 方法
            result = resumeTopActivityInnerLocked(prev, options);

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

        return result;
    }

}

1.20 ActivityStack.resumeTopActivityInnerLocked()

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

class ActivityStack extends ConfigurationContainer {

    private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
        if (!mService.isBooting() && !mService.isBooted()) {
            // Not ready yet!
            return false;
        }
        ... ...

        boolean pausing = display.pauseBackStacks(userLeaving, next, false);
        if (mResumedActivity != null) {
            if (DEBUG_STATES) Slog.d(TAG_STATES,
                    "resumeTopActivityLocked: Pausing " + mResumedActivity);
            // 先执行 startPausingLocked() 方法
            pausing |= startPausingLocked(userLeaving, false, next, false);
        }
        ... ...

        if (next.attachedToProcess()) {
            ... ...

            try {
                ... ...

            } catch (Exception e) {
                // Whoops, need to restart this activity!
                if (DEBUG_STATES) Slog.v(TAG_STATES, "Resume failed; resetting state to "
                        + lastState + ": " + next);
                next.setState(lastState, "resumeTopActivityInnerLocked");

                // lastResumedActivity being non-null implies there is a lastStack present.
                if (lastResumedActivity != null) {
                    lastResumedActivity.setState(RESUMED, "resumeTopActivityInnerLocked");
                }

                Slog.i(TAG, "Restarting because process died: " + next);
                if (!next.hasBeenLaunched) {
                    next.hasBeenLaunched = true;
                } else  if (SHOW_APP_STARTING_PREVIEW && lastFocusedStack != null
                        && lastFocusedStack.isTopStackOnDisplay()) {
                    next.showStartingWindow(null /* prev */, false /* newTask */,
                            false /* taskSwitch */);
                }
                // 执行 startSpecificActivityLocked() 方法
                mStackSupervisor.startSpecificActivityLocked(next, true, false);
                return true;
            }
            try {
                next.completeResumeLocked();
            } catch (Exception e) {
                // If any exception gets thrown, toss away this
                // activity and try the next one.
                Slog.w(TAG, "Exception thrown during resume of " + next, e);
                requestFinishActivityLocked(next.appToken, Activity.RESULT_CANCELED, null,
                        "resume-exception", true);
                return true;
            }
        } else {
            // Whoops, need to restart this activity!
            if (!next.hasBeenLaunched) {
                next.hasBeenLaunched = true;
            } else {
                if (SHOW_APP_STARTING_PREVIEW) {
                    next.showStartingWindow(null /* prev */, false /* newTask */,
                            false /* taskSwich */);
                }
                if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "Restarting: " + next);
            }
            if (DEBUG_STATES) Slog.d(TAG_STATES, "resumeTopActivityLocked: Restarting " + next);
            // 执行 startSpecificActivityLocked() 方法
            mStackSupervisor.startSpecificActivityLocked(next, true, true);
        }

        return true;
    }

}

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

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

1.21 ActivityStack.startPausingLocked()

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

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

class ActivityStack extends ConfigurationContainer {

    final ActivityTaskManagerService mService;

    // 栈顶 Activity 执行 onPause() 方法退出
    final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping,
            ActivityRecord resuming, boolean pauseImmediately) {
        ... ...

        ActivityRecord prev = mResumedActivity;
        ... ...

        // 把 prev 赋值给 mPausingActivity,这个值在 Activity 启动过程中会用到,
        // 这边其实就是将 mResumedActivity 赋值给 mPausingActivity,就是我们的 Launcher。
        mPausingActivity = prev;
        mLastPausedActivity = prev;
        mLastNoHistoryActivity = (prev.intent.getFlags() & Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
                || (prev.info.flags & ActivityInfo.FLAG_NO_HISTORY) != 0 ? prev : null;
        prev.setState(PAUSING, "startPausingLocked");
        prev.getTaskRecord().touchActiveTime();
        clearLaunchTime(prev);
        
        mService.updateCpuStats();
        ... ...

        if (prev.attachedToProcess()) {
            if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Enqueueing pending pause: " + prev);
            try {
                EventLogTags.writeAmPauseActivity(prev.mUserId, System.identityHashCode(prev),
                        prev.shortComponentName, "userLeaving=" + userLeaving);
                /*
                 * 从 Android P 开始,引入了 ClientLifecycleManager 和 ClientTransactionHandler 来辅助
                 * 管理 Activity 生命周期,它会发送 EXECUTE_TRANSACTION 消息到 ActivityThread.H 里面继续处理。
             
                 * 通过 ClientLifecycleManager 的 scheduleTransaction() 方法把 PauseActivityItem
                 * 事件加入到执行计划中,开始栈顶的 pausing 过程。
                 *
                 *    ClientLifecycleManager getLifecycleManager() {
                 *        return mLifecycleManager;
                 *    }
                 */
                mService.getLifecycleManager().scheduleTransaction(prev.app.getThread(),
                        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;
        }
        ... ...

    }

}

1.22 ClientLifecycleManager.scheduleTransaction()

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

class ClientLifecycleManager {

    void scheduleTransaction(@NonNull IApplicationThread client, @NonNull IBinder activityToken,
            @NonNull ActivityLifecycleItem stateRequest) throws RemoteException {
        final ClientTransaction clientTransaction = transactionWithState(client, activityToken,
                stateRequest);
        scheduleTransaction(clientTransaction);
    }

    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 IApplicationThread getClient() {
        return mClient;
    }

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

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

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

    }
}

1.24 流程小结

YrmlQJ.png

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

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

}

1.26 ActivityThread.sendMessage()

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

public final class ActivityThread extends ClientTransactionHandler {

    // An executor that performs multi-step transactions.
    private final TransactionExecutor mTransactionExecutor = new TransactionExecutor(this);

    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;

            }
        }

    }

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

}

1.27 TransactionExecutor.execute()

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

public class TransactionExecutor {

    public void execute(ClientTransaction transaction) {
        if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "Start resolving transaction");
        final IBinder token = transaction.getActivityToken();
        ... ...

        executeCallbacks(transaction);         // 重要方法 1
        executeLifecycleState(transaction);    // 重要方法 2
        
        mPendingActions.clear();
        if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "End resolving transaction");
    }

    // 重要方法 1
    /** Cycle through all states requested by callbacks and execute them at proper times. */
    public void executeCallbacks(ClientTransaction transaction) {
        final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
        ... ...

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

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

前面讲解到:在 ActivityStack.startPausingLocked() 方法里面 scheduleTransaction() 传递的是 PauseActivityItem() 对象,所以 executeLifecycleState() 方法里调用的 lifecycleItem.execute() 方法其实就是 PauseActivityItem.execute()方法。

1.28 PauseActivityItem.execute()

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

/**
 * Request to move an activity to paused state.
 * @hide
 */
public class PauseActivityItem extends ActivityLifecycleItem {

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

}

1.29 ActivityThread.handlePauseActivity()

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

public final class ActivityThread extends ClientTransactionHandler {

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

            r.activity.mConfigChangeFlags |= configChanges;
            // 调用 performPauseActivity() 方法
            performPauseActivity(r, finished, reason, pendingActions);

            // Make sure any pending writes are now committed.
            if (r.isPreHoneycomb()) {
                QueuedWork.waitToFinish();
            }
            mSomeActivitiesChanged = true;
        }
    }

}

1.30 ActivityThread.performPauseActivity()

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


public final class ActivityThread extends ClientTransactionHandler {

    /**
     * Pause the activity.
     * @return Saved instance state for pre-Honeycomb apps if it was saved, {@code null} otherwise.
     */
    private Bundle performPauseActivity(ActivityClientRecord r, boolean finished, String reason,
            PendingTransactionActions pendingActions) {
        ... ...
        
        performPauseActivityIfNeeded(r, reason);
        ... ...

    }

}

1.31 ActivityThread.performPauseActivityIfNeeded()

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

public final class ActivityThread extends ClientTransactionHandler {

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

        reportTopResumedActivityChanged(r, false /* onTop */, "pausing");

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

}

1.32 Instrumentation.callActivityOnPause()

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

public class Instrumentation {

    /**
     * Perform calling of an activity's {@link Activity#onPause} method.  The
     * default implementation simply calls through to that method.
     * 
     * @param activity The activity being paused.
     */
    public void callActivityOnPause(Activity activity) {
        activity.performPause();    // 直接调用 Activity.performPause 方法
    }

}

1.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, ContentCaptureManager.ContentCaptureClient {

    final void performPause() {
        dispatchActivityPrePaused();
        mDoReportFullyDrawn = false;
        mFragments.dispatchPause();
        mCalled = false;
        onPause();    // 执行暂停方法
        writeEventLog(LOG_AM_ON_PAUSE_CALLED, "performPause");
        mResumed = false;
        if (!mCalled && getApplicationInfo().targetSdkVersion
                >= android.os.Build.VERSION_CODES.GINGERBREAD) {
            throw new SuperNotCalledException(
                    "Activity " + mComponent.toShortString() +
                    " did not call through to super.onPause()");
        }
        dispatchActivityPostPaused();
    }

}

1.34 流程小结

YrByFK.png

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


二、启动应用进程

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

2.1 ActivityStackSupervisor.startSpecificActivityLocked()

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

public class ActivityStackSupervisor implements RecentTasks.Callbacks {

    final ActivityTaskManagerService mService;

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

        boolean knownToBeDead = false;
        // 如果 app 存在,并且已经启动
        if (wpc != null && wpc.hasThread()) {
            try {
                // app 存在并且已经启动,调用 realStartActivityLocked() 方法
                realStartActivityLocked(r, wpc, andResume, checkConfig);
                return;
            } catch (RemoteException e) {
                Slog.w(TAG, "Exception when starting activity "
                        + r.intent.getComponent().flattenToShortString(), e);
            }

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

        if (getKeyguardController().isKeyguardLocked()) {
            r.notifyUnknownVisibilityLaunched();
        }

        final boolean isTop = andResume && r.isTopRunningActivity();
        // 调用 startProcessAsync() 方法启动新的进程
        mService.startProcessAsync(r, knownToBeDead, isTop, isTop ? "top-activity" : "activity");
    }

}

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

如果没有启动,则会调用 ActivityTaskManagerService.startProcessAsync() 方法创建新的进程,我们重点看下新应用进程的创建流程。

2.2 ActivityTaskManagerService.startProcessAsync()

// frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java

public class ActivityTaskManagerService extends IActivityTaskManager.Stub {

    void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
            String hostingType) {
        try {
            if (Trace.isTagEnabled(TRACE_TAG_ACTIVITY_MANAGER)) {
                Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "dispatchingStartProcess:"
                        + activity.processName);
            }
            // Post message to start process to avoid possible deadlock of calling into AMS with the
            // ATMS lock held.
            // Message 包含一个 ActivityManagerInternal::startProcess 方法
            final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
                    mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
                    isTop, hostingType, activity.intent.getComponent());
            mH.sendMessage(m);
        } finally {
            Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
        }
    }

}

2.3 ActivityManagerInternal.startProcess()

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

public abstract class ActivityManagerInternal {

    // 抽象方法,由 ActivityManagerService 内部类 LocalService 实现
    public abstract void startProcess(String processName, ApplicationInfo info,
            boolean knownToBeDead, boolean isTop, String hostingType, ComponentName hostingName);

}

2.4 ActivityManagerService.LocalService.startProcess()

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

public class ActivityManagerService extends IActivityManager.Stub
        implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
        
    @VisibleForTesting
    public final class LocalService extends ActivityManagerInternal {
    
        @Override
        public void startProcess(String processName, ApplicationInfo info, boolean knownToBeDead,
                boolean isTop, String hostingType, ComponentName hostingName) {
            try {
                if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
                    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "startProcess:"
                            + processName);
                }
                synchronized (ActivityManagerService.this) {
                    // 调用 startProcessLocked() 方法
                    startProcessLocked(processName, info, knownToBeDead, 0 /* intentFlags */,
                            new HostingRecord(hostingType, hostingName, isTop),
                            ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE, false /* allowWhileBooting */,
                            false /* isolated */, true /* keepIfLarge */);
                }
            } finally {
                Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
            }
        }    
    
    }

}

2.5 ActivityManagerService.startProcessLocked()

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

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

    /**
     * Process management.
     */
    final ProcessList mProcessList = new ProcessList();

    @GuardedBy("this")
    final ProcessRecord startProcessLocked(String processName,
            ApplicationInfo info, boolean knownToBeDead, int intentFlags,
            HostingRecord hostingRecord, int zygotePolicyFlags, boolean allowWhileBooting,
            boolean isolated, boolean keepIfLarge) {
        return mProcessList.startProcessLocked(processName, info, knownToBeDead, intentFlags,
                hostingRecord, zygotePolicyFlags, allowWhileBooting, isolated, 0 /* isolatedUid */,
                keepIfLarge, null /* ABI override */, null /* entryPoint */,
                null /* entryPointArgs */, null /* crashHandler */);
    }
        
}

2.6 ProcessList.startProcessLocked() - - 01

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

/**
 * Activity manager code dealing with processes.
 */
public final class ProcessList {

    @GuardedBy("mService")
    final ProcessRecord startProcessLocked(String processName, ApplicationInfo info,
            boolean knownToBeDead, int intentFlags, HostingRecord hostingRecord,
            int zygotePolicyFlags, boolean allowWhileBooting, boolean isolated, int isolatedUid,
            boolean keepIfLarge, String abiOverride, String entryPoint, String[] entryPointArgs,
            Runnable crashHandler) {

        // 调用 startProcessLocked() 方法
        final boolean success =
                startProcessLocked(app, hostingRecord, zygotePolicyFlags, abiOverride);    
            
    }

}

2.7 ProcessList.startProcessLocked() - - 02

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

/**
 * Activity manager code dealing with processes.
 */
public final class ProcessList {

    @GuardedBy("mService")
    final boolean startProcessLocked(ProcessRecord app, HostingRecord hostingRecord,
            int zygotePolicyFlags, String abiOverride) {
        // 调用 startProcessLocked() 方法
        return startProcessLocked(app, hostingRecord, zygotePolicyFlags,
                false /* disableHiddenApiChecks */, false /* disableTestApiChecks */,
                false /* mountExtStorageFull */, abiOverride);
    }

}

2.8 ProcessList.startProcessLocked() - - 03

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

/**
 * Activity manager code dealing with processes.
 */
public final class ProcessList {

    @GuardedBy("mService")
    boolean startProcessLocked(ProcessRecord app, HostingRecord hostingRecord,
            int zygotePolicyFlags, boolean disableHiddenApiChecks, boolean disableTestApiChecks,
            boolean mountExtStorageFull, String abiOverride) {
        ... ...

        try {
            ... ...

            // 调用 startProcessLocked() 方法
            return startProcessLocked(hostingRecord, entryPoint, app, uid, gids,
                    runtimeFlags, zygotePolicyFlags, mountExternal, seInfo, requiredAbi,
                    instructionSet, invokeWith, startTime);            
        } catch (RuntimeException e) {
            Slog.e(ActivityManagerService.TAG, "Failure starting process " + app.processName, e);
            mService.forceStopPackageLocked(app.info.packageName, UserHandle.getAppId(app.uid),
                    false, false, true, false, false, app.userId, "start failure");
            return false;
        }
    }

}

2.9 ProcessList.startProcessLocked() - - 04

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

/**
 * Activity manager code dealing with processes.
 */
public final class ProcessList {

    @GuardedBy("mService")
    boolean startProcessLocked(HostingRecord hostingRecord, String entryPoint, ProcessRecord app,
            int uid, int[] gids, int runtimeFlags, int zygotePolicyFlags, int mountExternal,
            String seInfo, String requiredAbi, String instructionSet, String invokeWith,
            long startTime) {

        if (mService.mConstants.FLAG_PROCESS_START_ASYNC) {
            if (DEBUG_PROCESSES) Slog.i(TAG_PROCESSES,
                    "Posting procStart msg for " + app.toShortString());
            mService.mProcStartHandler.post(() -> {
                ... ...

            });
            return true;
        } else {
            try {
                // 调用 startProcess() 方法
                final Process.ProcessStartResult startResult = startProcess(hostingRecord,
                        entryPoint, app,
                        uid, gids, runtimeFlags, zygotePolicyFlags, mountExternal, seInfo,
                        requiredAbi, instructionSet, invokeWith, startTime);
                handleProcessStartedLocked(app, startResult.pid, startResult.usingWrapper,
                        startSeq, false);
            } catch (RuntimeException e) {
                Slog.e(ActivityManagerService.TAG, "Failure starting process "
                        + app.processName, e);
                app.pendingStart = false;
                mService.forceStopPackageLocked(app.info.packageName, UserHandle.getAppId(app.uid),
                        false, false, true, false, false, app.userId, "start failure");
            }
            return app.pid > 0;
        }

    }

}

2.10 ProcessList.startProcess()

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

/**
 * Activity manager code dealing with processes.
 */
public final class ProcessList {

    private Process.ProcessStartResult startProcess(HostingRecord hostingRecord, String entryPoint,
            ProcessRecord app, int uid, int[] gids, int runtimeFlags, int zygotePolicyFlags,
            int mountExternal, String seInfo, String requiredAbi, String instructionSet,
            String invokeWith, long startTime) {
        try {
            Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "Start proc: " +
                    app.processName);
            checkSlow(startTime, "startProcess: asking zygote to start proc");
            final boolean isTopApp = hostingRecord.isTopApp();
            if (isTopApp) {
                app.setHasForegroundActivities(true);
            }

            final Process.ProcessStartResult startResult;
            if (hostingRecord.usesWebviewZygote()) {
                startResult = startWebView(entryPoint,
                        app.processName, uid, uid, gids, runtimeFlags, mountExternal,
                        app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
                        app.info.dataDir, null, app.info.packageName, app.mDisabledCompatChanges,
                        new String[]{PROC_START_SEQ_IDENT + app.startSeq});
            } else if (hostingRecord.usesAppZygote()) {
                final AppZygote appZygote = createAppZygoteForProcessIfNeeded(app);

                startResult = appZygote.getProcess().start(entryPoint,
                        app.processName, uid, uid, gids, runtimeFlags, mountExternal,
                        app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
                        app.info.dataDir, null, app.info.packageName,
                        /*zygotePolicyFlags=*/ ZYGOTE_POLICY_FLAG_EMPTY, isTopApp,
                        app.mDisabledCompatChanges,
                        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, app.info.packageName, zygotePolicyFlags,
                        isTopApp, app.mDisabledCompatChanges,
                        new String[]{PROC_START_SEQ_IDENT + app.startSeq});
            }
            checkSlow(startTime, "startProcess: returned from zygote!");
            return startResult;
        } finally {
            Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        }
    }

}

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

YrvAit.png

进程的创建流程和源码分析,这边就不再讨论了!在《 【 Android 10 进程线程 】系列 -- 关于 "进程" -> "创建" 的原理】》一文中,我作了详细的分析!


三、Activity 进程

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

3.1 ActivityThread.main()

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

public final class ActivityThread extends ClientTransactionHandler {

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

        // Install selective syscall interception
        AndroidOs.install();

        CloseGuard.setEnabled(false);

        Environment.initForCurrentUser();

        // Make sure TrustedCertificateStore looks in the right place for CA certificates
        final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
        TrustedCertificateStore.setDefaultUserDirectory(configDir);

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

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

        // Find the value for {@link #PROC_START_SEQ_IDENT} if provided on the command line.
        // It will be in the format "seq=114"
        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
        ActivityThread thread = new ActivityThread();

        // attach 到系统进程
        thread.attach(false, startSeq);

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

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

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

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

}

3.2 ActivityThread.attach()

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

public final class ActivityThread extends ClientTransactionHandler {

    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 {
                            ActivityTaskManager.getService().releaseSomeActivities(mAppThread);
                        } catch (RemoteException e) {
                            throw e.rethrowFromSystemServer();
                        }
                    }
                }
            });
        } else {
            ... ...

        }
        ... ...
    
        // 为根 View 添加 config 回调接收 config 变化相关的信息
        ViewRootImpl.addConfigCallback(configChangedCallback);
    }

}

3.3 ActivityManagerService.attachApplication()

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

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

    @Override
    public final void attachApplication(IApplicationThread thread, long startSeq) {
        if (thread == null) {
            throw new SecurityException("Invalid application interface");
        }
        synchronized (this) {
            int callingPid = Binder.getCallingPid();
            final int callingUid = Binder.getCallingUid();
            final long origId = Binder.clearCallingIdentity();
            // 调用 attachApplicationLocked() 方法
            attachApplicationLocked(thread, callingPid, callingUid, startSeq);
            Binder.restoreCallingIdentity(origId);
        }
    }

}

3.4 ActivityManagerService.attachApplicationLocked()

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

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

    public ActivityTaskManagerInternal mAtmInternal;

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

        return true;
    }

}

3.5 ActivityTaskManagerInternal.attachApplication()

// frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerInternal.java

public abstract class ActivityTaskManagerInternal {

    // 抽象方法,由 ActivityTaskManagerService 内部类 LocalService 实现
    public abstract boolean attachApplication(WindowProcessController wpc) throws RemoteException;

}

3.6 ActivityTaskManagerService.attachApplication()

// frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java

public class ActivityTaskManagerService extends IActivityTaskManager.Stub {

    final class LocalService extends ActivityTaskManagerInternal {

        @Override
        public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
            synchronized (mGlobalLockWithoutBoost) {
            // 调用 RootActivityContainer.attachApplication() 方法
                return mRootActivityContainer.attachApplication(wpc);
            }
        }

    }
}

3.7 RootActivityContainer.attachApplication()

// frameworks/base/services/core/java/com/android/server/wm/RootActivityContainer.java

class RootActivityContainer extends ConfigurationContainer
        implements DisplayManager.DisplayListener {

    boolean attachApplication(WindowProcessController app) throws RemoteException {
        final String processName = app.mName;
        boolean didSomething = false;
        for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
            final ActivityDisplay display = mActivityDisplays.get(displayNdx);
            final ActivityStack stack = display.getFocusedStack();
            if (stack != null) {
                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.mUid == activity.info.applicationInfo.uid
                            && processName.equals(activity.processName)) {
                        try {
                            // 调用 ActivityStackSupervisor.realStartActivityLocked() 方法
                            if (mStackSupervisor.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) {
            ensureActivitiesVisible(null, 0, false /* preserve_windows */);
        }
        return didSomething;
    }

}

3.8 ActivityStackSupervisor.realStartActivityLocked()

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

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

public class ActivityStackSupervisor implements RecentTasks.Callbacks {

    boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
            boolean andResume, boolean checkConfig) throws RemoteException {
        ... ...
        
        final TaskRecord task = r.getTaskRecord();
        final ActivityStack stack = task.getStack();

        beginDeferResume();

        try {

            try {
                ... ...
                
                // Create activity launch transaction.
                final ClientTransaction clientTransaction = ClientTransaction.obtain(
                        proc.getThread(), r.appToken);
                        
                final DisplayContent dc = r.getDisplay().mDisplayContent;
                // 为 ClientTransaction 对象添加 LaunchActivityItem 的 callback
                clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
                        System.identityHashCode(r), r.info,
                        // TODO: Have this take the merged configuration instead of separate global
                        // and override configs.
                        mergedConfiguration.getGlobalConfiguration(),
                        mergedConfiguration.getOverrideConfiguration(), r.compat,
                        r.launchedFromPackage, task.voiceInteractor, proc.getReportedProcState(),
                        r.icicle, r.persistentState, results, newIntents,
                        dc.isNextTransitionForward(), proc.createProfilerInfoIfNeeded(),
                                r.assistToken));

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

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

            } catch (RemoteException e) {
            }
        } finally {
            endDeferResume();
        }
        ... ...

        return true;
    }

}

调用 ClientLifecycleManager.scheduleTransaction() 方法之后具体是如何执行的前面已经分析过了,这里就不再分析了。我们这里跟踪执行 callback 后跳转到 LaunchActivityItem.execute()方法。

3.9 LaunchActivityItem.execute()

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

/**
 * Request to launch an activity.
 * @hide
 */
public class LaunchActivityItem extends ClientTransactionItem {

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

}

3.10 ActivityThread.handleLaunchActivity()

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

public final class ActivityThread extends ClientTransactionHandler {

    @Override
    public Activity handleLaunchActivity(ActivityClientRecord r,
            PendingTransactionActions pendingActions, Intent customIntent) {

        // 调用 performLaunchActivity() 方法
        final Activity a = performLaunchActivity(r, customIntent);

    }

}

3.11 ActivityThread.performLaunchActivity()

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

public final class ActivityThread extends ClientTransactionHandler {

    /**  Core implementation of activity launch. */
    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 {
            ... ...

        } catch (Exception e) {
        }

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

            if (activity != null) {
                CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
                ... ...

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

                activity.mCalled = false;
                if (r.isPersistable()) {
                    // 调用 Instrumentation.callActivityOnCreate() 方法
                    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
                } else {
                    mInstrumentation.callActivityOnCreate(activity, r.state);
                }
                if (!activity.mCalled) {
                    throw new SuperNotCalledException(
                        "Activity " + r.intent.getComponent().toShortString() +
                        " did not call through to super.onCreate()");
                }
                r.activity = activity;
            }
            r.setState(ON_CREATE);

            synchronized (mResourcesManager) {
                mActivities.put(r.token, r);
            }

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

        return activity;

    }

}

3.12 流程小结

YsKuCV.png

3.13 Instrumentation.callActivityOnCreate()

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

public class Instrumentation {

    public void callActivityOnCreate(Activity activity, Bundle icicle) {
        prePerformCreate(activity);
        // 调用 performCreate() 方法
        activity.performCreate(icicle);
        postPerformCreate(activity);
    }

}

3.14 Activity.performCreate()

// 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, ContentCaptureManager.ContentCaptureClient {

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

至此 executeCallbacks() 执行完毕,开始执行 executeLifecycleState() 方法,会先执行 cycleToPath() 方法(这边如果觉得乱的话,可以回去看下之前的分析)。

3.15 TransactionExecutor.cycleToPath()

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

public class TransactionExecutor {

    private void cycleToPath(ActivityClientRecord r, int finish, boolean excludeLastState,
            ClientTransaction transaction) {

        final int start = r.getLifecycleState();
        if (DEBUG_RESOLVER) {
            Slog.d(TAG, tId(transaction) + "Cycle activity: "
                    + getShortActivityName(r.token, mTransactionHandler)
                    + " from: " + getStateName(start) + " to: " + getStateName(finish)
                    + " excludeLastState: " + excludeLastState);
        }
        final IntArray path = mHelper.getLifecyclePath(start, finish, excludeLastState);
        // 调用 performLifecycleSequence() 方法
        performLifecycleSequence(r, path, transaction);
    }

}

3.16 TransactionExecutor.performLifecycleSequence()

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

public class TransactionExecutor {

    private ClientTransactionHandler mTransactionHandler;

    /** Transition the client through previously initialized state sequence. */
    private void performLifecycleSequence(ActivityClientRecord r, IntArray path,
            ClientTransaction transaction) {
        final int size = path.size();
        for (int i = 0, state; i < size; i++) {
            state = path.get(i);
            if (DEBUG_RESOLVER) {
                Slog.d(TAG, tId(transaction) + "Transitioning activity: "
                        + getShortActivityName(r.token, mTransactionHandler)
                        + " to state: " + getStateName(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);
            }
        }
    }

}

3.17 ActivityThread.handleStartActivity()

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

public final class ActivityThread extends ClientTransactionHandler {

    @Override
    public void handleStartActivity(ActivityClientRecord r,
            PendingTransactionActions pendingActions) {
        final Activity activity = r.activity;
        ... ...

        // Start
        activity.performStart("handleStartActivity");
        r.setState(ON_START);
        ... ...

    }

}

3.18 Activity.performStart()

// 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, ContentCaptureManager.ContentCaptureClient {

    final void performStart(String reason) {
        ... ...

        mInstrumentation.callActivityOnStart(this);
        ... ...

    }

}

3.19 Instrumentation.callActivityOnStart()

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

public class Instrumentation {

    public void callActivityOnStart(Activity activity) {
        // 最终调用了 Activity.onStart() 方法
        activity.onStart();
    }

}

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

3.20 ResumeActivityItem.execute()

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

/**
 * Request to move an activity to resumed state.
 * @hide
 */
public class ResumeActivityItem extends ActivityLifecycleItem {

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

}

3.21 ActivityThread.handleResumeActivity()

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

public final class ActivityThread extends ClientTransactionHandler {

    @Override
    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;
        }
        ... ...

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

}

3.22 ActivityThread.performResumeActivity()

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

public final class ActivityThread extends ClientTransactionHandler {

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

            reportTopResumedActivityChanged(r, r.isTopResumedActivity, "topWhenResuming");
        } 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;
    }

}

3.23 Activity.performResume()

// 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, ContentCaptureManager.ContentCaptureClient {

    final void performResume(boolean followedByPause, String reason) {
        dispatchActivityPreResumed();
        performRestart(true /* start */, reason);
        ... ...

        mInstrumentation.callActivityOnResume(this);
        ... ...

        dispatchActivityPostResumed();
    }

}

3.24 Instrumentation.callActivityOnResume()

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

public class Instrumentation {

    public void callActivityOnResume(Activity activity) {
        activity.mResumed = true;
        // 调用了 Activity.onResume() 方法
        activity.onResume();
        
        if (mActivityMonitors != null) {
            synchronized (mSync) {
                final int N = mActivityMonitors.size();
                for (int i=0; i<N; i++) {
                    final ActivityMonitor am = mActivityMonitors.get(i);
                    am.match(activity, activity, activity.getIntent());
                }
            }
        }
    }
    
}

至此,Activity 启动完毕。

3.25 流程小结

YssngS.png


四、栈顶活动 onStop

我们在讨论 ActivityThread.handleResumeActivity() 源码的时候,最后一行代码比较特殊,还未进行讨论。

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

public final class ActivityThread extends ClientTransactionHandler {

    @Override
    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;
        }
        ... ...

        // 当 MessageQueue 空闲的时候就会执行这个 Handler,即执行完当前 Activity 的 onResume() 方法后执行
        Looper.myQueue().addIdleHandler(new Idler());
        
    }

}

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

4.1 new Idler()

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

public final class ActivityThread extends ClientTransactionHandler {

    private class Idler implements MessageQueue.IdleHandler {
        @Override
        public final boolean queueIdle() {
            ActivityClientRecord a = mNewActivities;
            boolean stopProfiling = false;
            if (mBoundApplication != null && mProfiler.profileFd != null
                    && mProfiler.autoStopProfiler) {
                stopProfiling = true;
            }
            if (a != null) {
                mNewActivities = null;
                IActivityTaskManager am = ActivityTaskManager.getService();
                ActivityClientRecord prev;
                do {
                    if (localLOGV) Slog.v(
                        TAG, "Reporting idle of " + a +
                        " finished=" +
                        (a.activity != null && a.activity.mFinished));
                    if (a.activity != null && !a.activity.mFinished) {
                        try {
                            // 调用 ActivityTaskManagerService.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);
            }
            if (stopProfiling) {
                mProfiler.stopProfiling();
            }
            applyPendingProcessState();
            return false;
        }
    }

}

4.2 ActivityTaskManagerService.activityIdle()

// frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java

public class ActivityTaskManagerService extends IActivityTaskManager.Stub {

    ActivityStackSupervisor mStackSupervisor;

    @Override
    public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
        final long origId = Binder.clearCallingIdentity();
        try {
            WindowProcessController proc = null;
            synchronized (mGlobalLock) {
                ActivityStack stack = ActivityRecord.getStackLocked(token);
                if (stack == null) {
                    return;
                }
                // 调用 ActivityStackSupervisor.activityIdleInternalLocked 方法
                final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
                        false /* fromTimeout */, false /* processPausingActivities */, config);
                if (r != null) {
                    proc = r.app;
                }
                if (stopProfiling && proc != null) {
                    proc.clearProfilerIfNeeded();
                }
            }
        } finally {
            Binder.restoreCallingIdentity(origId);
        }
    }

}

4.3 ActivityStackSupervisor.activityIdleInternalLocked()

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

public class ActivityStackSupervisor implements RecentTasks.Callbacks {

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

        ... ...

        // Stop any activities that are scheduled to do so but have been
        // waiting for the next one to start.
        for (int i = 0; i < NS; i++) {
            r = stops.get(i);
            final ActivityStack stack = r.getActivityStack();
            if (stack != null) {
                if (r.finishing) {
                    stack.finishCurrentActivityLocked(r, ActivityStack.FINISH_IMMEDIATELY, false,
                            "activityIdleInternalLocked");
                } else {
                    // 调用 ActivityStack.stopActivityLocked() 方法
                    stack.stopActivityLocked(r);
                }
            }
        }
        ... ...

        return r;
    }

}

4.4 ActivityStack.stopActivityLocked()

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

    final void stopActivityLocked(ActivityRecord r) {
        ... ...

        if (r.attachedToProcess()) {
            adjustFocusedActivityStack(r, "stopActivity");
            r.resumeKeyDispatchingLocked();
            try {
                ... ...

                EventLogTags.writeAmStopActivity(
                        r.mUserId, System.identityHashCode(r), r.shortComponentName);
                // 又见面了
                mService.getLifecycleManager().scheduleTransaction(r.app.getThread(), 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) {
                Slog.w(TAG, "Exception thrown during pause", e);
                // Just in case, assume it to be stopped.
                r.stopped = true;
                if (DEBUG_STATES) Slog.v(TAG_STATES, "Stop failed; moving to STOPPED: " + r);
                r.setState(STOPPED, "stopActivityLocked");
                if (r.deferRelaunchUntilPaused) {
                    destroyActivityLocked(r, true, "stop-except");
                }
            }
        }
    }
    
}

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

4.5 StopActivityItem.execute()

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

/**
 * Request to move an activity to stopped state.
 * @hide
 */
public class StopActivityItem extends ActivityLifecycleItem {

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

}

4.6 ActivityThread.handleStopActivity()

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

public final class ActivityThread extends ClientTransactionHandler {

    @Override
    public void handleStopActivity(IBinder token, boolean show, int configChanges,
            PendingTransactionActions pendingActions, boolean finalStateRequest, String reason) {
        ... ...

        performStopActivityInner(r, stopInfo, show, true /* saveState */, finalStateRequest,
                reason);
        ... ...

    }

}

4.7 ActivityThread.performStopActivityInner()

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

public final class ActivityThread extends ClientTransactionHandler {

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

            if (!keepShown) {
                callActivityOnStop(r, saveState, reason);
            }
        }
    }

}

4.8 ActivityThread.callActivityOnStop()

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

public final class ActivityThread extends ClientTransactionHandler {

    private void callActivityOnStop(ActivityClientRecord r, boolean saveState, String reason) {
        final boolean shouldSaveState = saveState && !r.activity.mFinished && r.state == null
                && !r.isPreHoneycomb();
        final boolean isPreP = r.isPreP();
        if (shouldSaveState && isPreP) {
            callActivityOnSaveInstanceState(r);
        }

        try {
            // 调用 Activity.performStop() 方法
            r.activity.performStop(r.mPreserveWindow, reason);
        } catch (SuperNotCalledException e) {
            throw e;
        } catch (Exception e) {
            if (!mInstrumentation.onException(r.activity, e)) {
                throw new RuntimeException(
                        "Unable to stop activity "
                                + r.intent.getComponent().toShortString()
                                + ": " + e.toString(), e);
            }
        }
        r.setState(ON_STOP);

        if (shouldSaveState && !isPreP) {
            callActivityOnSaveInstanceState(r);
        }
    }

}

4.9 Activity.performStop()

// 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, ContentCaptureManager.ContentCaptureClient {

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

            mStopped = true;
            dispatchActivityPostStopped();
        }
        mResumed = false;
    }

}

4.10 Instrumentation.callActivityOnStop()

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

public class Instrumentation {

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

YsfltJ.png



DeepCoder
569 声望3.2k 粉丝

One blog for recorded and shared, Android system development.