Activity的启动过程

时间:2020-11-30 04:33:57

Android系统启动流程简述

Android系统启动的时候,会创建一个init进程,在init进程中会创建出zygote进程。zygote进程启动的时候会创建DVM(Dalvik虚拟机)、SystemServer进程,同时还会创建一个服务端socket,用来等待ActivityManagerService发送的申请zygote进程创建应用程序进程的请求(由此可知,应用程序进程也是通过zygote创建的)。
在SystemServer的run方法中,会先创建出SystemServiceManager(它会对系统服务进行创建、启动、生命周期管理)。然后通过SystemServiceManager启动AMS、PMS、WMS等服务。
Android中涉及的系统服务大概有80多个,这些系统服务又分为引导服务、核心服务、其他服务3类。其中AMS、PMS、WMS这三个是我们常见的服务,AMS、PMS它们两个属于引导服务,WMS属于其他服务,这三个系统服务的作用是:

  • AMS(ActivityManagerService):负责对四大组件的管理,主要是启动、切换、调度等。
  • PMS(PackageManagerService):负责对apk的管理,主要是apk的安装、解析、卸载、提供包信息等。
  • WMS(WindowManagerService):负责对窗体的管理,主要是对窗体上的View的添加、修改、删除等。

在SystemServer的run方法中,调用startOtherServices方法时,会调用AMS的systemReady方法,在systemReady方法中会启动Lanucher,Lanucher是一个应用程序,Lanucher启动的时候会通过PMS获取系统中安装的所有应用的信息,并将这些应用以快捷图标的形式展示出来(我们在桌面上看到的应用图标),可以通过点击快捷图标来打开一个具体的应用程序。
应用程序的进程是由AMS发起请求,zygote创建的(fork zygote进程自身的方式创建),应用程序进程创建后,会从ActivityThread的main方法作为应用程序的入口进行执行。

Activity的启动过程(基于8.0系统)

Activity的启动分为根Activity的启动和普通Activity的启动,当我们点击桌面上的应用图标的时候,Lanucher应用会请求AMS启动应用程序进程,并调用Lanucher的startActivitySafely方法启动对应应用程序的根Activity,最终会调用到startActivityForResult方法。启动普通Activity的方法最终也是调用到startActivityForResult方法,所以启动过程的分析就从Activity的startActivityForResult这个方法开始,startActivityForResult方法源码:

public void startActivityForResult(
        ................

        //关键代码
        Instrumentation.ActivityResult ar =
            mInstrumentation.execStartActivity(
                this, mMainThread.getApplicationThread(), mToken, who,
                intent, requestCode, options);

         ................
    }

在startActivityForResult方法中,调用了Instrumentation的execStartActivity方法,execStartActivity方法源码:

public ActivityResult execStartActivity(
            Context who, IBinder contextThread, IBinder token, Activity target,
            Intent intent, int requestCode, Bundle options) {
        IApplicationThread whoThread = (IApplicationThread) contextThread;

       ................

        //关键代码
        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;
    }

在execStartActivity的方法中调用了ActivityManager.getService()的startActivity方法,那么ActivityManager.getService()是什么呢?看下相关源码:

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

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

                    //关键代码1
                    final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);

                    //关键代码2
                    final IActivityManager am = IActivityManager.Stub.asInterface(b);

                    return am;
                }
            };

从上面的代码中可以看到getService的返回值是IActivityManager 类型的,由关键代码1可知b是AMS的一个Binder引用,在看关键代码2生成了b的一个本地代理对象am,这个am就是getService方法返回的IActivityManager 的具体实现,也就是说getService方法返回的是AMS远程服务在本地的一个代理,本地可以通过这个代理和远程的AMS进行通信。那么,启动过程就交给AMS的startActivity方法去执行了。下面看下AMS的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) {

        //调用了startActivityAsUser方法
        return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
                resultWho, requestCode, startFlags, profilerInfo, bOptions,
                UserHandle.getCallingUserId());
    }


    @Override
    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) {
        enforceNotIsolatedCaller("startActivity");
        userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
                userId, false, ALLOW_FULL_ONLY, "startActivity", null);
        // TODO: Switch to user app stacks here.
        //关键代码
        return mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent,
                resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
                profilerInfo, null, null, bOptions, false, userId, null, null,
                "startActivityAsUser");
    }

从上面的代码可知,AMS的startActivity方法又调用了AMS的startActivityAsUser方法,startActivityAsUser方法里面调用了ActivityStarter类的startActivityMayWait,下面看下在ActivityStarter中的调用链:

   final 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, Bundle bOptions, boolean ignoreTargetSecurity, int userId,
            IActivityContainer iContainer, TaskRecord inTask, String reason) {

            ................ 

            //关键代码
            int res = startActivityLocked(caller, intent, ephemeralIntent, resolvedType,
                    aInfo, rInfo, voiceSession, voiceInteractor,
                    resultTo, resultWho, requestCode, callingPid,
                    callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
                    options, ignoreTargetSecurity, componentSpecified, outRecord, container,
                    inTask, reason);

            ................

            return res;
        }
    }



int startActivityLocked(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,
            ActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,
            ActivityRecord[] outActivity, ActivityStackSupervisor.ActivityContainer container,
            TaskRecord inTask, String reason) {

        ................

        //关键代码
        mLastStartActivityResult = startActivity(caller, intent, ephemeralIntent, resolvedType,
                aInfo, rInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode,
                callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
                options, ignoreTargetSecurity, componentSpecified, mLastStartActivityRecord,
                container, inTask);

        ................

        return mLastStartActivityResult;
    }



 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,
            ActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,
            ActivityRecord[] outActivity, ActivityStackSupervisor.ActivityContainer container,
            TaskRecord inTask) {

        ................

        //关键代码,调用重载的startActivity方法
        return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags, true,
                options, inTask, outActivity);
    }



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

            ................

            //关键代码
            result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
                    startFlags, doResume, options, inTask, outActivity);

        ................

        return result;
    }


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

            ................ 

        //关键代码 
        mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity,
                        mOptions);

        ................ 

        return START_SUCCESS;
    }

在ActivityStarter这个类中经过一系列的调用,最终调用到了ActivityStackSupervisor类的resumeFocusedStackTopActivityLocked方法:

  boolean resumeFocusedStackTopActivityLocked(
            ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
        if (targetStack != null && isFocusedStack(targetStack)) {
            return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
        }
        final ActivityRecord r = mFocusedStack.topRunningActivityLocked();
        if (r == null || r.state != RESUMED) {

            //关键代码,调用了ActivityStack的resumeTopActivityUncheckedLocked方法
            mFocusedStack.resumeTopActivityUncheckedLocked(null, null);

        } else if (r.state == RESUMED) {
            // Kick off any lingering app transitions form the MoveTaskToFront operation.
            mFocusedStack.executeAppTransition(targetOptions);
        }
        return false;
    }

由上面的代码可知,在resumeFocusedStackTopActivityLocked方法中调用了ActivityStack的resumeTopActivityUncheckedLocked方法:

  boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {

        ................ 

        //关键代码
        result = resumeTopActivityInnerLocked(prev, options);

       ................ 

        return result;
    }



private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {

     ................ 

     //关键代码
     mStackSupervisor.startSpecificActivityLocked(next, true, false);

     ................ 

     return true;
  }

在ActivityStack中执行结束,又调用到了ActivityStackSupervisor类中的startSpecificActivityLocked方法:

 void startSpecificActivityLocked(ActivityRecord r,
            boolean andResume, boolean checkConfig) {

            ................ 

            //关键代码
            realStartActivityLocked(r, app, andResume, checkConfig);

            ................ 

    }



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

            ................ 

        return true;
    }


//关键代码,app.thread就是ApplicationThread 
private class ApplicationThread extends IApplicationThread.Stub {
        ................
}

app.thread是IApplicationThread类型的,它的具体实现是ApplicationThread,这个类是ActivityThread的一个内部类,从源码中可以看到ApplicationThread继承了 IApplicationThread.Stub ,所以ApplicationThread也是一个本地Binder代理类,AMS执行完客户端的请求后会回调给ApplicationThread,AMS是一个独立的进程,ApplicationThread属于应用程序客户端进程,所以AMS和ApplicationThread的通信是一个进程间通信的过程。那么此时,调用流程转到了ApplicationThread的scheduleLaunchActivity方法中:

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

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

            //发送一个Handler消息
            sendMessage(H.LAUNCH_ACTIVITY, r);
        }

ApplicationThread中方法的执行是在Binder线程池中执行的,所以要将执行流程切换到主线程中去,从上面的源码可知,最终发送了一个Handler消息,这个Handler就是ActivityThread的一个继承了Handler的内部类,H的源码如下:

 private class H extends Handler {
        public static final int LAUNCH_ACTIVITY         = 100;

         ................ 

         public void handleMessage(Message msg) {
            if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
            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, "LAUNCH_ACTIVITY");

                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                } break;

         ................ 

从上面的消息处理来看,调用到了ActivityThread的handleLaunchActivity方法,这样就切换到ActivityThread所在线程(主线程)去启动Activity了,在handleLaunchActivity方法中又调用了performLaunchActivity方法:

    private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");

        ActivityInfo aInfo = r.activityInfo;
        if (r.packageInfo == null) {
            r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
                    Context.CONTEXT_INCLUDE_CODE);
        }

        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 appContext = createBaseContextForActivity(r);

        //关键代码1,创建Activity
        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) {
            if (!mInstrumentation.onException(activity, e)) {
                throw new RuntimeException(
                    "Unable to instantiate activity " + component
                    + ": " + e.toString(), e);
            }
        }

        //关键代码2,创建Application
        try {
            Application app = r.packageInfo.makeApplication(false, mInstrumentation);

            if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
            if (localLOGV) Slog.v(
                    TAG, r + ": app=" + app
                    + ", appName=" + app.getPackageName()
                    + ", pkg=" + r.packageInfo.getPackageName()
                    + ", comp=" + r.intent.getComponent().toShortString()
                    + ", dir=" + r.packageInfo.getAppDir());


            if (activity != null) {
                CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
                Configuration config = new Configuration(mCompatConfiguration);
                if (r.overrideConfig != null) {
                    config.updateFrom(r.overrideConfig);
                }
                if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
                        + r.activityInfo.name + " with config " + config);
                Window window = null;
                if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
                    window = r.mPendingRemoveWindow;
                    r.mPendingRemoveWindow = null;
                    r.mPendingRemoveWindowManager = null;
                }
                appContext.setOuterContext(activity);

                //关键代码3,初始化一些和Activity相关的数据
                activity.attach(appContext, this, getInstrumentation(), r.token,
                        r.ident, app, r.intent, r.activityInfo, title, r.parent,
                        r.embeddedID, r.lastNonConfigurationInstances, config,
                        r.referrer, r.voiceInteractor, window, r.configCallback);


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

                activity.mCalled = false;

                //关键代码4,调用Activity的onCreate方法
                if (r.isPersistable()) {
                    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.stopped = true;
                if (!r.activity.mFinished) {
                    activity.performStart();
                    r.stopped = false;
                }
                if (!r.activity.mFinished) {
                    if (r.isPersistable()) {
                        if (r.state != null || r.persistentState != null) {
                            mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
                                    r.persistentState);
                        }
                    } else if (r.state != null) {
                        mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
                    }
                }
                if (!r.activity.mFinished) {
                    activity.mCalled = false;
                    if (r.isPersistable()) {
                        mInstrumentation.callActivityOnPostCreate(activity, r.state,
                                r.persistentState);
                    } else {
                        mInstrumentation.callActivityOnPostCreate(activity, r.state);
                    }
                    if (!activity.mCalled) {
                        throw new SuperNotCalledException(
                            "Activity " + r.intent.getComponent().toShortString() +
                            " did not call through to super.onPostCreate()");
                    }
                }
            }
            r.paused = true;

            mActivities.put(r.token, r);

        } catch (SuperNotCalledException e) {
            throw e;

        } catch (Exception e) {
            if (!mInstrumentation.onException(activity, e)) {
                throw new RuntimeException(
                    "Unable to start activity " + component
                    + ": " + e.toString(), e);
            }
        }

        return activity;
    }

在关键代码1处,可以看出是通过类加载器创建了Activity。在关键代码2处,可以看出通过makeApplication创建Application,Application全局只有一个,如果Application已经被创建过了就不会在创建了,如果没有创建过(开启根Activity)就会创建一个。在关键代码3处,可以看出调用了activity的attach方法,在这个方法会初始化一些Activity需要的数据,window(PhoneWindow)就是在这个方法中创建的。从关键代码4处可以看出,调用了Activity的onCreate方法,说明Activity已经启动起来了。为了整个调用流程看起来更直观一些,下面给出了相关类的调用时序图:
Activity的启动过程