Activity 启动过程分析

09 Jan 2018

概述

启动 Activity 是日常开发的高频操作,本文将基于 android-9.0.0_r1 源码学习启动过程,加深对 Android Framework 层的理解。

启动流程

startActivity 方法是我们日常打开新 Activity 的入口,从该方法开始:

@Override
public void startActivity(Intent intent) {
    this.startActivity(intent, null);
}

@Override
public void startActivity(Intent intent, @Nullable Bundle options) {
    if (options != null) {
        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);
    }
}

Bundle 用来携带需要传递的参数。这两个分支最终都会调用到 startActivityForResult 方法:

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

只保留关键操作,即 android.app.InstrumentationexecStartActivity 方法:

public ActivityResult execStartActivity(
        Context who, IBinder contextThread, IBinder token, Activity target,
        Intent intent, int requestCode, Bundle options) {
    ...
    try {
        int result = ActivityManager.getService()
            .startActivity(whoThread, who.getBasePackageName(), intent,
                    intent.resolveTypeIfNeeded(who.getContentResolver()),
                    token, target != null ? target.mEmbeddedID : null,
                    requestCode, 0, null, options);
        checkStartActivityResult(result, intent);
    } catch (RemoteException e) {
        throw new RuntimeException("Failure from system", e);
    }
    return null;
}

该方法有很多参数,它们的意义如下:

ActivityManager.getService() 定义如下:

public static IActivityManager getService() {
    return IActivityManagerSingleton.get();
}

private static final Singleton<IActivityManager> IActivityManagerSingleton =
        new Singleton<IActivityManager>() {
            @Override
            protected IActivityManager create() {
                ...
            }
        };

Singleton 是一个抽象工具类,可以按照懒加载的方式提供单例对象:

public abstract class Singleton<T> {
    private T mInstance;

    protected abstract T create();

    public final T get() {
        synchronized (this) {
            if (mInstance == null) {
                mInstance = create();
            }
            return mInstance;
        }
    }
}

所以回到 IActivityManagerSingleton 实现的 create 方法:

protected IActivityManager create() {
    final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
    final IActivityManager am = IActivityManager.Stub.asInterface(b);
    return am;
}           

ServiceManager.getService 定义如下:

public static IBinder getService(String name) {
    try {
        IBinder service = sCache.get(name);
        if (service != null) {
            return service;
        } else {
            return Binder.allowBlocking(rawGetService(name));
        }
    } catch (RemoteException e) {
        Log.e(TAG, "error in getService", e);
    }
    return null;
}

private static IBinder rawGetService(String name) throws RemoteException {
    ...
    final IBinder binder = getIServiceManager().getService(name);
    ...
    return binder;
}

@UnsupportedAppUsage
private static IServiceManager getIServiceManager() {
    ...
    // Find the service manager
    sServiceManager = ServiceManagerNative.asInterface(Binder.allowBlocking(BinderInternal.getContextObject()));
    return sServiceManager;
}

name 参数的值为 Context.ACTIVITY_SERVICE = activityBinderInternal.getContextObject() 是一个 jni 调用,返回的是 native 层 ServiceManager 服务的 Binder 代理对象。然后通过 ServiceManagerNative 最终返回 ServiceManagerProxy 对象,即用它来代理和 native 层 ServiceManager 服务的通信。

ServiceManagerProxy 的声明如下:

class ServiceManagerProxy implements IServiceManager {
    public ServiceManagerProxy(IBinder remote) {
        mRemote = remote;
    }

    public IBinder asBinder() {
        return mRemote;
    }
}

ServiceManagerNative 是 java 层对 native 层 ServiceManager 服务的映射,它也是一个 Binder 对象并实现了 IServiceManager 接口,即它是 Java 层对 native 层 ServiceManager 服务请求的映射。ServiceManager 服务是 Binder 通信机制的管家服务,所有其他服务启动后都要注册到 ServiceManager 服务。Context.ACTIVITY_SERVICE 这个名称代表的是 ActivityManagerService 服务,简称 AMS 。通过 ServiceManagerProxy 代理的 ServiceManager 服务通过服务名称 activity 获取到能与 AMS 服务进程远程通信的 Binder 代理对象。该 Binder 对象的实例对象为 IActivityManager.Stub.Proxy 对象,其 startActivity 方法声明如下:

@Override 
public int startActivity(
    android.app.IApplicationThread caller, 
    java.lang.String callingPackage, 
    android.content.Intent intent, 
    java.lang.String resolvedType, 
    android.os.IBinder resultTo, 
    java.lang.String resultWho, 
    int requestCode, 
    int flags, 
    android.app.ProfilerInfo profilerInfo, 
    android.os.Bundle options) throws android.os.RemoteException {   
    android.os.Parcel _data = android.os.Parcel.obtain();
        android.os.Parcel _reply = android.os.Parcel.obtain();
        int _result;
        try {
          ...
          boolean _status = mRemote.transact(Stub.TRANSACTION_startActivity, _data, _reply, 0);
          if (!_status && getDefaultImpl() != null) {
            return getDefaultImpl().startActivity(caller, callingPackage, intent, resolvedType, resultTo, resultWho, requestCode, flags, profilerInfo, options);
          }
          _reply.readException();
          _result = _reply.readInt();
        }
        finally {
          _reply.recycle();
          _data.recycle();
        }
        return _result;
}

这里又有一长串的参数:

这部分代码在分析 Binder 原理的时候已经非常熟悉了,远过程调用数据的传输通过 Parcel 数据包,然后利用 mRemote 这个 Binder 对象的 transact 方法开始 Binder 通信过程。响应 transact 的是服务方代理的 onTransact 。这个远程代理由 java 层的 AMS 实现,其定义如下:

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

继承自 IActivityManager.Stub 类,所以前面 transact 方法最终由 IActivityManager.Stub#onTransactonTransact 响应:

@Override public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException {
    java.lang.String descriptor = DESCRIPTOR;
    switch (code) {
        case TRANSACTION_startActivity:
        {
        	...
          	int _result = this.startActivity(_arg0, _arg1, _arg2, _arg3, _arg4, _arg5, _arg6, _arg7, _arg8, _arg9);
          	...
          	return true;
        }
    }
}

实现 startActivity 接口的是 ActivityManagerService#startActivity 方法:

@Override
public final int startActivity(IApplicationThread caller, String callingPackage,
        Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
        int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
    return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
            resultWho, requestCode, startFlags, profilerInfo, bOptions,
            UserHandle.getCallingUserId());
}

经过几次直接方法调用后到:

public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
        Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
        int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
        boolean validateIncomingUser) {
    ...
    return mActivityStartController.obtainStarter(intent, "startActivityAsUser")
            .setCaller(caller)
            .setCallingPackage(callingPackage)
            .setResolvedType(resolvedType)
            .setResultTo(resultTo)
            .setResultWho(resultWho)
            .setRequestCode(requestCode)
            .setStartFlags(startFlags)
            .setProfilerInfo(profilerInfo)
            .setActivityOptions(bOptions)
            .setMayWait(userId)
            .execute();

}

这里先介绍几个类:

上面的 mActivityStartController 就是 ActivityStartController 对象。其 obtainStarter 定义如下:

ActivityStarter obtainStarter(Intent intent, String reason) {
    return mFactory.obtain().setIntent(intent).setReason(reason);
}

mFactory 就是 ActivityStarter.Factory 对象,其默认实现 ActivityStarter.DefaultFactoryobtain 方法实现如下:

@Override
public ActivityStarter obtain() {
    ActivityStarter starter = mStarterPool.acquire();

    if (starter == null) {
        starter = new ActivityStarter(mController, mService, mSupervisor, mInterceptor);
    }

    return starter;
}

mStarterPool 缓存池大小为 3 ,如果没有缓存的 starter ,就实例化一个新的。所以接下来会调用 ActivityStartersetIntentsetReason 方法:

ActivityStarter setIntent(Intent intent) {
    mRequest.intent = intent;
    return this;
}

// reason 的值为前面传的 startActivityAsUser
ActivityStarter setReason(String reason) {
    mRequest.reason = reason;
    return this;
}

mRequestRequest 的实例,它是 ActivityStarter 的一个私有静态内部类,用来记录请求 Activity 启动的各类参数以及工具类,并且在起初始化的时候就创建好了。

回到上面的 startActivityAsUser 方法,从 setCallersetMayWait 都是填充 mRequest 对象。然后看看 execute 方法:

int execute() {
    try {
        // TODO(b/64750076): Look into passing request directly to these methods to allow
        // for transactional diffs and preprocessing.
        if (mRequest.mayWait) {
            return startActivityMayWait(mRequest.caller, mRequest.callingUid,
                    mRequest.callingPackage, mRequest.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);
        } else {
            ...
        }
    } finally {
        onExecutionComplete();
    }
}

startActivityMayWait 方法很长很复杂,只保留关键部分:

private int startActivityMayWait(IApplicationThread caller, int callingUid,
            String callingPackage, Intent intent, String resolvedType,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            IBinder resultTo, String resultWho, int requestCode, int startFlags,
            ProfilerInfo profilerInfo, WaitResult outResult,
            Configuration globalConfig, SafeActivityOptions options, boolean ignoreTargetSecurity,
            int userId, TaskRecord inTask, String reason,
            boolean allowPendingRemoteAnimationRegistryLookup) {
    ...
    boolean componentSpecified = intent.getComponent() != null;
    ...
    // 第一部分
    ResolveInfo rInfo = mSupervisor.resolveIntent(intent, resolvedType, userId,
                0 /* matchFlags */,
                        computeResolveFilterUid(
                                callingUid, realCallingUid, mRequest.filterCallingUid));
    ...
    // Collect information about the target of the Intent.
    ActivityInfo aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags, profilerInfo);

    synchronized (mService) {
        ...
        // 第二部分
        final ActivityRecord[] outRecord = new ActivityRecord[1];
        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);
        ...
        return res;
    }
}

这里只看其中最重要的两个部分。

第一部分

ResolveInfo rInfo = mSupervisor.resolveIntent(intent, resolvedType, userId, 0, computeResolveFilterUid(callingUid, realCallingUid, mRequest.filterCallingUid));

ResolveInfo 对象保存从 AndroidManifest.xml 里面解析的 <intent> 标签的信息,比如我们常说的四大组件。

ResolveInfo resolveIntent(Intent intent, String resolvedType, int userId, int flags, int filterCallingUid) {
    ...
    synchronized (mService) {
        return mService.getPackageManagerInternalLocked().resolveIntent(intent, resolvedType, modifiedFlags, userId, true, filterCallingUid);
    }
}

mService.getPackageManagerInternalLocked() 获取的是 PackageManagerService.PackageManagerInternalImpl 对象,该对象是在 PackageManagerService 被创建的时候添加到 LocalServices 这个对象里。继续跟踪代码,可以找到最重要的一些操作:

private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType, int flags, int userId, boolean resolveForStart, int filterCallingUid) {
    try {
        ...
        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
        ...
        final ResolveInfo bestChoice =
                    chooseBestActivity(intent, resolvedType, flags, query, userId);
        return bestChoice;
    } finally {
        ...
    }
}

先是通过 PackageManagerService 读取到 intent 里面对应 component 的 Activity 的信息保存到 ResolveInfo 里面。然后通过 chooseBestActivity 选择最终要启动的那个 Activity 的信息,一般只有一个 Activity ,在有多个的时候,会弹出选择框让用户选择。

第二部分

又是一个巨漫长巨复杂的过程,先是进行权限检查,通过之后,创建新的 ActivityRecord 对象,该对象是 Activity 在任务栈中的描述。然后检查是要创建新的任务栈还是共用当然获得焦点的任务栈、是需要启动新的 Activity 还是仅仅将之前某个任务栈带到前台、按照设置的启动模式来启动 Activity 等等这些操作都是在这一步完成。重点来看 ActivityStackSupervisorstartSpecificActivityLocked 方法:

void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) {
    // Is this activity's application already running?
    ...
    mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
            "activity", r.intent.getComponent(), false, false, true);
}

会先判断目标进程是否已经存在,但这里分析的是一开始的启动流程,所以忽略这部分逻。在 AMS 的 startProcessLocked 方法中,先通过 newProcessRecordLocked 创建新的 ProcessRecord 对象,然后调用另外一个重载的 startProcessLocked 方法,最终调用到 startProcess 方法:

private ProcessStartResult startProcess(String hostingType, String entryPoint,
        ProcessRecord app, int uid, int[] gids, int runtimeFlags, int mountExternal,
        String seInfo, String requiredAbi, String instructionSet, String invokeWith,
        long startTime) {
    try {
        final ProcessStartResult startResult;
        if (hostingType.equals("webview_service")) {
            ...
        } else {
            startResult = Process.start(entryPoint,
                    app.processName, uid, uid, gids, runtimeFlags, mountExternal,
                    app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
                    app.info.dataDir, invokeWith,
                    new String[] {PROC_START_SEQ_IDENT + app.startSeq});
        }
        checkTime(startTime, "startProcess: returned from zygote!");
        return startResult;
    } finally {
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
    }
}

启动进程的具体操作交给 android.os.Process 对象,其 start 方法只是把启动操作委托给它的 zygoteProcess 对象,该对象的声明如下:

public static final ZygoteProcess zygoteProcess = new ZygoteProcess(ZYGOTE_SOCKET, SECONDARY_ZYGOTE_SOCKET);

ZygoteProcess 实现了与 Zygote 进程的通信,Zygote 是 Java 进程的始祖,所有应用进程都是从它 fork 出来的。了解下它的注释:

/**
 * Maintains communication state with the zygote processes. This class is responsible
 * for the sockets opened to the zygotes and for starting processes on behalf of the
 * {@link android.os.Process} class.
 *
 * {@hide}
 */

它会通过 Socket 的方式与 Zygote 进程通信,通知 Zygote 创建指定的进程。新的进程创建完毕后,将 ActivityThread 加载到新的进程,然后调用其 main 方法:

public static void main(String[] args) {
    ...
    Process.setArgV0("<pre-initialized>");
    Looper.prepareMainLooper();
    ...
    ActivityThread thread = new ActivityThread();
    thread.attach(false, startSeq);

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

    if (false) {
        Looper.myLooper().setMessageLogging(new
                LogPrinter(Log.DEBUG, "ActivityThread"));
    }
    Looper.loop();
    throw new RuntimeException("Main thread loop unexpectedly exited");
}

终于我们看到了我们熟悉的 main looper 的 的启动过程,ActivityThread 代表了应用的主线程,在它实例化的时候,创建了最前面说的 ApplicationThread 对象,Main Looper 对象以及 Handler 对象。然后来看看 attach

private void attach(boolean system, long startSeq) {
    sCurrentActivityThread = this;
    mSystemThread = system;
    if (!system) {
        ...
        final IActivityManager mgr = ActivityManager.getService();
        try {
            mgr.attachApplication(mAppThread, startSeq);
        } catch (RemoteException ex) {
            throw ex.rethrowFromSystemServer();
        }
        ...
    } else {
        ...
    }
    ...
}

这里主要分析非系统 AT 过程,所以重点需要关注的是通过 Binder 通信,调用 AMS 的 attachApplication 方法,该方法会调用到 attachApplicationLocked 方法:

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

该方法做了很多事情,我们重点来看 mStackSupervisor.attachApplicationLocked 操作:

boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
    final String processName = app.processName;
    boolean didSomething = false;
    for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
        final ActivityDisplay display = mActivityDisplays.valueAt(displayNdx);
        for (int stackNdx = display.getChildCount() - 1; stackNdx >= 0; --stackNdx) {
            final ActivityStack stack = display.getChildAt(stackNdx);
            if (!isFocusedStack(stack)) {
                continue;
            }
            stack.getAllRunningVisibleActivitiesLocked(mTmpActivityList);
            // 获取栈顶正在运行的 Activity
            final ActivityRecord top = stack.topRunningActivityLocked();
            final int size = mTmpActivityList.size();
            for (int i = 0; i < size; i++) {
                final ActivityRecord activity = mTmpActivityList.get(i);
                if (activity.app == null && app.uid == activity.info.applicationInfo.uid
                        && processName.equals(activity.processName)) {
                    try {
                        // 开始真正的启动流程
                        if (realStartActivityLocked(activity, app,
                                top == activity /* andResume */, true /* checkConfig */)) {
                            didSomething = true;
                        }
                    } catch (RemoteException e) {
                        Slog.w(TAG, "Exception in new application when starting activity "
                                + top.intent.getComponent().flattenToShortString(), e);
                        throw e;
                    }
                }
            }
        }
    }
    if (!didSomething) {
        ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
    }
    return didSomething;
}

如注释所示,我们直接看 realStartActivityLocked,这部分又很长,还是一点一点去看:

if (!allPausedActivitiesComplete()) {
    // While there are activities pausing we skipping starting any new activities until
    // pauses are complete. NOTE: that we also do this for activities that are starting in
    // the paused state because they will first be resumed then paused on the client side.
    ...
    return false;
}

新的 Activity 在启动的过程中,会先 pause 掉当前栈顶的 Activity ,在实际启动新的 Activity 之前,会检查是否还有 Activity 的 pause 过程没有执行完成,如果有的话,会等到执行完成之后再来执行新 Activity 的启动过程。

final TaskRecord task = r.getTask();
final ActivityStack stack = task.getStack();
beginDeferResume();

获取当前 ActivityRecord 所属的任务,即 TaskRecord 对象,以及当前任务所属的任务栈,即 ActivityStack 对象。beginDeferResume 方法用来标记本次延迟的 resume 过程,ActivityStackSupervisor 中使用 mDeferResumeCount 变量标记当前是否可以进行 resume 操作,只有当这个变量值为 0 的时候才会允许,这是为了防止重复进行 resume 操作。

int idx = app.activities.indexOf(r);
if (idx < 0) {
    app.activities.add(r);
}

app.activities 保存的是当前进程中 Activity 列表,这里新启动的 Activity 要么是当前进程的栈顶 Activity ,要么是新的 Activity ,如过是新的,则将对应的 ActivityRecord 信息添加到列表末尾。

app.hasShownUi = true;
app.pendingUiClean = true;
app.forceProcessStateUpTo(mService.mTopProcessState);

将该进程设置为前台进程。

clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
    System.identityHashCode(r), r.info,
    mergedConfiguration.getGlobalConfiguration(),
    mergedConfiguration.getOverrideConfiguration(), r.compat,
    r.launchedFromPackage, task.voiceInteractor, proc.getReportedProcState(),
    r.icicle, r.persistentState, results, newIntents,
    dc.isNextTransitionForward(), proc.createProfilerInfoIfNeeded(),
    r.assistToken));
final ActivityLifecycleItem lifecycleItem;
if (andResume) {
    lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward());
} else {
    lifecycleItem = PauseActivityItem.obtain();
}
clientTransaction.setLifecycleStateRequest(lifecycleItem);
mService.getLifecycleManager().scheduleTransaction(clientTransaction);

clientTransaction.addCallback 经过一系列调用之后,会回调 ClientTransactionHandlerhandleLaunchActivityclientTransaction.setLifecycleStateRequest(lifecycleItem); 参数中的 lifecycleItemResumeActivityItem ,最终会回调 ClientTransactionHandlerhandleResumeActivity 方法。ClientTransactionHandler 的实现类是 ActivityThread 。先看 handleLaunchActivity 方法:

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

先初始化 WindowManagerService ,然后调用 performLaunchActivity 执行具体的启动过程:

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    ...
    ContextImpl appContext = createBaseContextForActivity(r);
    Activity activity = null;
    try {
        java.lang.ClassLoader cl = appContext.getClassLoader();
        activity = mInstrumentation.newActivity(
                cl, component.getClassName(), r.intent);
        StrictMode.incrementExpectedActivityCount(activity.getClass());
        r.intent.setExtrasClassLoader(cl);
        r.intent.prepareToEnterProcess();
        if (r.state != null) {
            r.state.setClassLoader(cl);
        }
    } catch (Exception e) {
        ...
    }
    try {
        Application app = r.packageInfo.makeApplication(false, mInstrumentation);
        if (activity != null) {
            ...
            appContext.setOuterContext(activity);
            activity.attach(appContext, this, getInstrumentation(), r.token,
                    r.ident, app, r.intent, r.activityInfo, title, r.parent,
                    r.embeddedID, r.lastNonConfigurationInstances, config,
                    r.referrer, r.voiceInteractor, window, r.configCallback);
            ...
            if (r.isPersistable()) {
                mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
            } else {
                mInstrumentation.callActivityOnCreate(activity, r.state);
            }
            ...
            r.activity = activity;
        }
        r.setState(ON_CREATE);

        mActivities.put(r.token, r);

    } catch (SuperNotCalledException e) {
        throw e;

    } catch (Exception e) {
        ...
    }
    return activity;
}

主要执行了以下步骤:

  1. 创建 ContextImpl 对象。
  2. 创建 Activity 对象。
  3. 创建 Application 对象。
  4. 回调 attach 方法。
  5. 回调 onCreate 声明周期。

这些操作完整之后,会继续回调到 handleResumeActivity 方法,继续执行 onResume 生命周期。

总结

整个 Activity 启动的过程可以概括为以下几步:

  1. 从启动 Activity 的进程会通过 Binder IPC 通信,将请求发送到 AMS 。
  2. AMS 服务通过 Socket 通信向 Zygote 进程请求创建进程。
  3. 新进程启动动,调用新应用的 ActivityThread 的 main 方法,启动主线程。
  4. ActivityThread 通过 Binder IPC 发起 attach application 请求到 AMS 。
  5. 最后回到 ActivityThread 执行 Activity 启动的生命周期。

参考

https://cs.android.com/android/platform/superproject/+/android-9.0.0_r1:frameworks

http://gityuan.com/2016/03/12/start-activity/