大家都知道一个应用开始的地方为ActivityThread的main方法,main方法中有以下代码:
- ActivityThread thread = new ActivityThread();
- thread.attach(false);
下面我们看attanch方法
- private void attach(boolean system) {
- sCurrentActivityThread = this;
- mSystemThread = system;
- if (!system) {
- ViewRootImpl.addFirstDrawHandler(new Runnable() {
- @Override
- public void run() {
- ensureJitEnabled();
- }
- });
- android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",
- UserHandle.myUserId());
- RuntimeInit.setApplicationObject(mAppThread.asBinder());
- final IActivityManager mgr = ActivityManagerNative.getDefault();
- try {
- mgr.attachApplication(mAppThread);
- } catch (RemoteException ex) {
- // Ignore
- }
- } else {
- // Don't set application object here -- if the system crashes,
- // we can't display an alert, we just want to die die die.
- android.ddm.DdmHandleAppName.setAppName("system_process",
- UserHandle.myUserId());
- try {
- mInstrumentation = new Instrumentation();
- ContextImpl context = ContextImpl.createAppContext(
- this, getSystemContext().mPackageInfo);
- mInitialApplication = context.mPackageInfo.makeApplication(true, null);
- mInitialApplication.onCreate();
- } catch (Exception e) {
- throw new RuntimeException(
- "Unable to instantiate Application():" + e.toString(), e);
- }
- }
- // 省略部分代码
- }
在非system应用中,获取了一个ActivityManagerService,并将当前的app thread绑定到ActivityMangerService
在ActivityManagerNative中可以看到getDefault return gDefault.get(); gDefault定义如下:
- private static final Singleton<IActivityManager> gDefault = new Singleton<IActivityManager>() {
- protected IActivityManager create() {
- IBinder b = ServiceManager.getService("activity");
- if (false) {
- Log.v("ActivityManager", "default service binder = " + b);
- }
- IActivityManager am = asInterface(b);
- if (false) {
- Log.v("ActivityManager", "default service = " + am);
- }
- return am;
- }
- };
通过ServiceManager.getService返回一个ActivityManagerService对象,并用ActivityManagerProxy对其包装。
ServiceManager管理了常用的service,如AudioService ActivityManagerService AlarmService等(具体可参见ContextImpl中的registerService代码)。
因此这里我们查看ActivityManagerService的attachApplication方法。
- public final void attachApplication(IApplicationThread thread) {
- synchronized (this) {
- int callingPid = Binder.getCallingPid();
- final long origId = Binder.clearCallingIdentity();
- attachApplicationLocked(thread, callingPid);
- Binder.restoreCallingIdentity(origId);
- }
- }
主要还是调用了 attachApplicationLocked,attachApplicationLocked代码大约有240行,因此这里我们只摘取重要的部分,如下:
- thread.bindApplication(processName, appInfo, providers, app.instrumentationClass,
- profilerInfo, app.instrumentationArguments, app.instrumentationWatcher,
- app.instrumentationUiAutomationConnection, testMode, enableOpenGlTrace,
- enableTrackAllocation, isRestrictedBackupMode || !normalMode, app.persistent,
- new Configuration(mConfiguration), app.compat,
- getCommonServicesLocked(app.isolated),
- mCoreSettingsObserver.getCoreSettingsLocked());
- // 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;
- }
- }
bindApplication为绑定application对象,暂且不提,我们看下下面的那部分代码,通过注释也可以看出是将最顶部activity显示,而显示最重要的部门为mStackSupervisor.attachApplicationLocked,这里用到了一个全新的类ActivityStackSupervisor。通过命名就可以清楚这是一个activity stack管理类,然后我们进入看它的attachApplicationLocked方法。
- boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
- final String processName = app.processName;
- boolean didSomething = false;
- for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
- ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
- for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
- final ActivityStack stack = stacks.get(stackNdx);
- if (!isFrontStack(stack)) {
- continue;
- }
- ActivityRecord hr = stack.topRunningActivityLocked(null);
- if (hr != null) {
- if (hr.app == null && app.uid == hr.info.applicationInfo.uid
- && processName.equals(hr.processName)) {
- try {
- if (realStartActivityLocked(hr, app, true, true)) {
- didSomething = true;
- }
- } catch (RemoteException e) {
- Slog.w(TAG, "Exception in new application when starting activity "
- + hr.intent.getComponent().flattenToShortString(), e);
- throw e;
- }
- }
- }
- }
- }
- if (!didSomething) {
- ensureActivitiesVisibleLocked(null, 0);
- }
- return didSomething;
- }
经过一系列逻辑判断后最终调用到了realStartActivityLocked方法,realStartActivityLocked方法代码量大约200行,其中包括对activity task的一些逻辑操作,配置相关信息等,我们这里只关注activity启动过程,因此找到下面的代码
- app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
- System.identityHashCode(r), r.info, new Configuration(mService.mConfiguration),
- new Configuration(stack.mOverrideConfig), r.compat, r.launchedFromPackage,
- task.voiceInteractor, app.repProcState, r.icicle, r.persistentState, results,
- newIntents, !andResume, mService.isNextTransitionForward(), profilerInfo);
这里我们知道最终走到了ApplicationThread的scheduleLaunchActivity方法。ApplicationThread为ActivityThread的一个私有内部类.其cheduleLaunchActivity代码如下
- 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) {
- updateProcessState(procState, false);
- ActivityClientRecord r = new ActivityClientRecord();
- r.token = token;
- r.ident = ident;
- r.intent = intent;
- r.referrer = referrer;
- r.voiceInteractor = voiceInteractor;
- r.activityInfo = info;
- r.compatInfo = compatInfo;
- r.state = state;
- r.persistentState = persistentState;
- r.pendingResults = pendingResults;
- r.pendingIntents = pendingNewIntents;
- r.startsNotResumed = notResumed;
- r.isForward = isForward;
- r.profilerInfo = profilerInfo;
- r.overrideConfig = overrideConfig;
- updatePendingConfiguration(curConfig);
- sendMessage(H.LAUNCH_ACTIVITY, r);
- }
终于我们看到了一丝曙光,在该方法的最后一句send了一个LAUNCH_ACTIVITY的message。到这里activity启动过程讲了一半了,第二部分给大家讲ActivityThread如何接收找个message并进行activity启动的相关操作,这里我们总结一下:
Activity启动流程,为首先系统走main方法,在main中通过attach方法,开启了一系列调用,
ActivityManagerService.attachApplication -> attachApplicationLocked -> ActivityStackSupervisor.attachApplicationLocked -> realStartActivityLocked -> ApplicationThread.scheduleLaunchActivity -> sendMessage