一、Activity 起始

1、开始 startActivity

#Activity
![](https://user-gold-cdn.xitu.io/2019/1/23/1687a36f94c7d771?w=915&h=502&f=png&s=7087)
@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);
    }
}
复制代码
#Activity
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);
        if (ar != null) {
            mMainThread.sendActivityResult(
                mToken, mEmbeddedID, requestCode, ar.getResultCode(),
                ar.getResultData());
        }
        ......
    }
}
复制代码

Instrumentation 是 android 系统中启动 Activity 的一个实际操作类

2、Instrumentation

#Instrumentation
public ActivityResult execStartActivity(
        Context who, IBinder contextThread, IBinder token, Activity target,
        Intent intent, int requestCode, Bundle options) {
    ......
    try {
        intent.migrateExtraStreamToClipData();
        intent.prepareToLeaveProcess(who);
        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 获取 ActivityManagerService 的代理对象,通过 Binder 实现跟 AMS 的进程通信

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

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

复制代码

最终实际调用的是 AMS 的 startActivity 方法,实现了应用进程和 SystemServer 进程的通信

二、ActivityManagerService

#ActivityManagerService
final int startActivity(Intent intent, ActivityStackSupervisor.ActivityContainer container) {
    enforceNotIsolatedCaller("ActivityContainer.startActivity");
    final int userId = mUserController.handleIncomingUser(Binder.getCallingPid(),
            Binder.getCallingUid(), mStackSupervisor.mCurrentUser, false,
            ActivityManagerService.ALLOW_FULL_ONLY, "ActivityContainer", null);
    ......
    return mActivityStarter.startActivityMayWait(null, -1, null, intent, mimeType, null, null,
            null, null, 0, 0, null, null, null, null, false, userId, container, null,
            "startActivity");
}
复制代码

调用了 ActivityStarter 的 startActivityMayWait 方法 -->
调用了 ActivityStarter 的 startActivityLocked 方法 -->
调用了 ActivityStarter 的 startActivity 方法 -->
调用了 ActivityStarter 的 startActivityUnchecked 方法 -->
调用了 ActivityStackSupervisor 的 resumeFocusedStackTopActivityLocked 方法 -->
调用了 ActivityStack 的 resumeTopActivityUncheckedLocked 方法 -->
调用了 ActivityStack 的 resumeTopActivityInnerLocked 方法 -->
调用了 ActivityStackSupervisor 的 startSpecificActivityLocked 方法 -->

#ActivityStackSupervisor
void startSpecificActivityLocked(ActivityRecord r,
        boolean andResume, boolean checkConfig) {
    // Is this activity's application already running?
    ProcessRecord app = mService.getProcessRecordLocked(r.processName,
            r.info.applicationInfo.uid, true);
r.getStack().setLaunchTime(r);

if (app != null &amp;&amp; app.thread != null) {
    try {
        ......
        (1)
        realStartActivityLocked(r, app, 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.
}
(2)
mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
        "activity", r.intent.getComponent(), false, false, true);

}

复制代码

(1)当 application 不为空的时候执行 realStartActivityLocked 方法
(2)通过调用 AMS 的 startProcessLocked 向 Zygote 进程发送创建进程请求,最终执行了 ActivityThread 的 main 方法

#ActivityStackSupervisor
final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
        boolean andResume, boolean checkConfig) throws RemoteException {
    ......
    app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
            System.identityHashCode(r), r.info,
            // TODO: Have this take the merged configuration instead of separate global and
            // override configs.
            mergedConfiguration.getGlobalConfiguration(),
            mergedConfiguration.getOverrideConfiguration(), r.compat,
            r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,
            r.persistentState, results, newIntents, !andResume,
            mService.isNextTransitionForward(), profilerInfo);

    ......

<span class="hljs-built_in">return</span> <span class="hljs-literal">true</span>;

}

复制代码
  • app.thread 指的是 IApplicationThread,IApplicationThread 是一个 Binder 接口。
  • 它的实现是 ActivityThread 的内部类 ApplicationThread。最终调用的是 ApplicationThread 的 scheduleLaunchActivity 方法。
  • 最终通过 Binder 进行通信,实现了从 AMS 所在的 SystemServer 进程,传递到了应用所在进程。

三、ActivityThread

1、调用到 ActivityThread

#ActivityThread.ApplicationThread
@Override
public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
        ActivityInfo info, Configuration curConfig, Configuration overrideConfig,
        CompatibilityInfo compatInfo, String referrer, IVoiceInteractor voiceInteractor,
        int procState, Bundle state, PersistableBundle persistentState,
        List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents,
        boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) {
......

sendMessage(H.LAUNCH_ACTIVITY, r);

}

复制代码

通过 Handler 跟 ActivityThread 进行通信

#ActivityThread
public void handleMessage(Message msg) {
    switch (msg.what) {
        case LAUNCH_ACTIVITY: {
            Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
            final ActivityClientRecord r = (ActivityClientRecord) msg.obj;
        r.packageInfo = getPackageInfoNoCheck(
                r.activityInfo.applicationInfo, r.compatInfo);
        handleLaunchActivity(r, null, <span class="hljs-string">"LAUNCH_ACTIVITY"</span>);
    ......
}

}

复制代码

ActivityThread 接收到消息后,调用了 handleLaunchActivity 方法

#ActivityThread
private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
    ......
    //创建Activity对象
    Activity a = performLaunchActivity(r, customIntent);
<span class="hljs-keyword">if</span> (a != null) {
    r.createdConfig = new Configuration(mConfiguration);
    reportSizeConfigurations(r);
    Bundle oldState = r.state;
    handleResumeActivity(r.token, <span class="hljs-literal">false</span>, r.isForward,
            !r.activity.mFinished &amp;&amp; !r.startsNotResumed, r.lastProcessedSeq, reason);
    ......
}

}

复制代码

2、通过 performLaunchActivity 创建了 Activity 对象

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");
    ......
    //创建ContextImpl
    ContextImpl appContext = createBaseContextForActivity(r);
    Activity activity = null;
    try {
        java.lang.ClassLoader cl = appContext.getClassLoader();
        //(1)通过Instrumentation创建Activity对象
        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) {
        if (!mInstrumentation.onException(activity, e)) {
            throw new RuntimeException(
                "Unable to instantiate activity" + component
                + ":" + e.toString(), e);
        }
    }
try {
    //(2)创建Application对象
    Application app = r.packageInfo.makeApplication(<span class="hljs-literal">false</span>, mInstrumentation);

    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">local</span>LOGV) Slog.v(TAG, <span class="hljs-string">"Performing launch of "</span> + r);
    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">local</span>LOGV) Slog.v(
            TAG, r + <span class="hljs-string">": app="</span> + app
            + <span class="hljs-string">", appName="</span> + app.getPackageName()
            + <span class="hljs-string">", pkg="</span> + r.packageInfo.getPackageName()
            + <span class="hljs-string">", comp="</span> + r.intent.getComponent().toShortString()
            + <span class="hljs-string">", dir="</span> + r.packageInfo.getAppDir());

    <span class="hljs-keyword">if</span> (activity != null) {
        CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
        Configuration config = new Configuration(mCompatConfiguration);
        <span class="hljs-keyword">if</span> (r.overrideConfig != null) {
            config.updateFrom(r.overrideConfig);
        }
        <span class="hljs-keyword">if</span> (DEBUG_CONFIGURATION) Slog.v(TAG, <span class="hljs-string">"Launching activity "</span>
                + r.activityInfo.name + <span class="hljs-string">" with config "</span> + config);
        Window window = null;
        <span class="hljs-keyword">if</span> (r.mPendingRemoveWindow != null &amp;&amp; r.mPreserveWindow) {
            window = r.mPendingRemoveWindow;
            r.mPendingRemoveWindow = null;
            r.mPendingRemoveWindowManager = null;
        }
        appContext.setOuterContext(activity);
        //(3)创建PhoneWindow对象跟Activity关联,将Context与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);

        ......
        //(4)调用了Instrumentation方法
        <span class="hljs-keyword">if</span> (r.isPersistable()) {
            mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
        } <span class="hljs-keyword">else</span> {
            mInstrumentation.callActivityOnCreate(activity, r.state);
        }
        ......
    }

<span class="hljs-built_in">return</span> activity;

}

复制代码

(1)通过反射实现 Activity 创建

#Instrumentation
public Activity newActivity(ClassLoader cl, String className,
        Intent intent)
        throws InstantiationException, IllegalAccessException,
        ClassNotFoundException {
    return (Activity)cl.loadClass(className).newInstance();
}
复制代码

(2)通过反射实现了 Application 创建

static public Application newApplication(Class<?> clazz, Context context)
        throws InstantiationException, IllegalAccessException, 
        ClassNotFoundException {
    Application app = (Application)clazz.newInstance();
    app.attach(context);
    return app;
}
复制代码

(3)实现了 PhoneWindow 的创建

final void attach(Context context, ActivityThread aThread,
        Instrumentation instr, IBinder token, int ident,
        Application application, Intent intent, ActivityInfo info,
        CharSequence title, Activity parent, String id,
        NonConfigurationInstances lastNonConfigurationInstances,
        Configuration config, String referrer, IVoiceInteractor voiceInteractor,
        Window window, ActivityConfigCallback activityConfigCallback) {
    attachBaseContext(context);
mFragments.attachHost(null /*parent*/);

mWindow = new PhoneWindow(this, window, activityConfigCallback);
mWindow.setWindowControllerCallback(this);
mWindow.setCallback(this);
mWindow.setOnWindowDismissedCallback(this);
......

}

复制代码

(4)调用了 Instrumentation 的 callActivityOnCreate 方法

四、回到 Activity

#Instrumentation
public void callActivityOnCreate(Activity activity, Bundle icicle) {
    prePerformCreate(activity);
    activity.performCreate(icicle);
    postPerformCreate(activity);
}
复制代码
#Activity
final void performCreate(Bundle icicle) {
    restoreHasCurrentPermissionRequest(icicle);
    onCreate(icicle);
    mActivityTransitionState.readState(icicle);
    performCreateCommon();
}
复制代码

调用了 Activity 的 onCreate 方法

五、流程总结:

1、请求 AMS

2、AMS 到 ApplicationThread

3、ActivityThread 到 Activity

4、进程间通信

参考文章:
Android8.0 根 Activity 启动过程 1
Android8.0 根 Activity 启动过程 2

  • Android

    开放手机联盟(一个由 30 多家科技公司和手机公司组成的团体)已开发出 Android,Android 是第一个完整、开放、免费的手机平台。

    293 引用
感谢    赞同    分享    收藏    关注    反对    举报    ...