美文网首页
Android14 AMS源码解析

Android14 AMS源码解析

作者: 墨客MOKE | 来源:发表于2024-06-25 23:26 被阅读0次

    前言

    Android 14 (U) 版本里,延续了从Android 10开始的改版,将原先的AMS拆分成ActivityTaskManagerService(ATMS)ActivityManagerService(AMS)这两个Service,ATMS主要是管理Activity Task相关的。

    AMS初始化

    ActivityTaskManagerService(ATMS)ActivityManagerService(AMS)这两个Service都是在SystemServer进程启动时初始化的。

    SystemServer.java
    public final class SystemServer implement Dumpanle {
        ...
        private void run {
            ...
            startBootstrapServices(t);
        }
        
        private void startBootstrapServices(TimingsTraceAndSlog t) {
            ...
            ActivityTaskManagerService atm = mSystemServiceManager.startService(
                ActivityTaskManangerService.Lifecycle.class).getService();
            mActivityManagerService = ActivityManagerService.Lifecycle.startService(
                mSystemServiceManager, atm);
            ...
        }
    }
    

    疑问: 为什么这些系统服务是先反射实例化内部类Lifecycle对象来获取实际Service对象的? 而且这个Lifecycle对象后面再也没用到过,有啥必要?

    首先是ATMS的初始化,在startService里通过反射实例化一个ActivityTaskManagerService.Lifecycle对象,真正的ATMS对象实际是在这个Lifecycle类的构造方法里创建的:

    public static final class Lifecycle extends SystemService {
        private final ActivityTaskManagerService mService;
        public Lifecycle(Context context) {
            super(context);
            mService = new ActivityTaskManagerService(context);
        }
    
        @Override
        public void onStart() {
            publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
            mService.start();
        }
    
        public ActivityTaskManagerService getService() {
            return mService;
        }
    }
    

    startService方法最后会调用到LifecycleonStart方法,如上,首先会在publishBinderService方法里将创建好的service对象通过Binder保存到在一个Service Manager进程里,方便后续跨进程取用。

    根据官方的解释,ActivityTaskManagerService即ATMS是用来管理Activity和Activity的容器(任务,显示, 。。。)的系统服务。
    ActivityTaskManagerService构造方法如下

    public ActivityTaskManagerService(Context context) {
        ...
        //将多个客户端生命周期转换请求或回调结合起来,作为一个事务执行。
        mLifecycleManager = new ClientLifecycleManager();
        //用于快速查询所有拥有可见活动的进程,同时也能追踪有前台活动的进程的CPU占用情况
        mVisibleActivityProcessTracker = new VisibleActivityProcessTracker(this);
        //创建一个内部类,继承自ActivityTaskManagerInternal抽象类,并在后续LocalServices.addService(ActivityTaskManagerInternal.class, mInternal)缓存到当前进程的静态Map里,
        //方便为systemserver进程内部快速使用
        mInternal = new LocalService();
        ...
        //组织、管理windows的接口在服务端的实现。
        mWindowOrganizerController = new WindowOrganizerController(this);
        ...
        //在服务端处理与返回手势相关的操作。
        mBackNavigationController = new BackNavigationController();
    }
    

    AMS对象也是类似的流程。

    public static final class Lifecycle extends SystemService {
        private final ActivityManagerService mService;
        private static ActivityTaskManagerService sAtm;
        public Lifecycle(Context context) {
            super(context);
            mService = new ActivityManagerService(context, sAtm);
        }
        public static ActivityManagerService startService(
                SystemServiceManager ssm, ActivityTaskManagerService atm) {
            sAtm = atm;
            return ssm.startService(ActivityManagerService.Lifecycle.class).getService();
        }
        @Override
        public void onStart() {
            mService.start();
        }
        public ActivityManagerService getService() {
            return mService;
        }
    }
    

    ActivityManagerService的构造函数如下,通过AMS的构造函数将ATMS对象传给AMS,其只被AMS对象持有、调用。因此,我们可以在梳理分析AMS的过程中看看ATMS负责做了哪些工作。

    public ActivityManagerService(Context systemContext, ActivityTaskManagerService atm) {
        ...
        //追踪正在运行进程的的活跃uids
        final ActiveUids activityUids = new ActiveUids(this, true);
        mPlatformCompat = (PlatformCompat)ServiceManager.getService(
            Context.PLATFORM_COMPAT_SERVICE);
        //负责处理进程相关的代码,如启动、杀死进程等操作
        mProcessList = mInjector.getProcessList(this);
        mProcessList.init(this, activityUids, mPlatformCompat);
        //app性能剖析器,追踪app的内存,CPU占用等性能表现
        mAppProfiler = new AppProfiler(this, BackgroundThread.getHandler().getLooper(), new LowMemDetector(this));
        //处理幻影进程相关的代码,主要是用来管理子进程
        mPhantomProcessList = new PhantomProcessList(this);
        //用来计算处理进程的状态与oom_adj值,oom_adj这个值就是在内存不够时系统判断优先释放哪些进程内存时使用的,越高代表越容易被杀
        mOomAdjuster = new OomAdjuster(this, mProcessList, activeUids)
        ...
        //负责Broadcast的管理,为每个进程都存储一个广播队列
        mBroadcastQueues = new BroadcastQueue[1];
        mBroadcastQueues[0] = new BroadcastQueueModernImpl(this, mHandler,
                foreConstants, backConstants);
        //负责Service的管理
        mServices = new ActiveServices(this);
        //负责ContentProvider的管理
        mCpHelper = new ContentProviderHelper(this, true);
        ...
        //创建AppOpsService, 用于权限检查
        mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops_accesses.xml"),
                    new File(systemDir, "appops.xml"), mHandler);
        ...
        //Intent防火墙,用于检查拦截Intent,FWK开发可以自定义规则
        mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);
        //ATMS进行一些初始化工作,下面会讲到
        mActivityTaskManager.initialize(mIntentFirewall, mPendingIntentController,
                    DisplayThread.get().getLooper());
        ...
        //创建内部类LocalService,继承自抽象类ActivityManangerInternal
        mInternal = new LocalService();
        ...
    }
    

    AMS初始工作基本完成了,接下来就让我们通过Activity的启动走进ATMS和AMS的内部世界一探究竟。

    Activity启动

    启动一个Activity的起点首先是Activity类的startActivity方法。

    Activity.java
    public void startActivity(Intent intent, @Nullable Bundle options) {
        ...
        if (options != null) {
            startActivityForResult(intent, -1, options);
        } else {
            startActivityForResult(intent, -1);
        }
    }
    
    public void startActivityForResult(@RequiresPermission Intent intent, int requestCode, @Nullable Bundle options) {
        if (mParent == null) {
            ...
            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());
            }
            ...
        } else {
            if (options != null) {
                mParent.startActivityFromChild(this, intent, requestCode, options);
            } else {
                mParent.startActivityFromChild(this, intent, requestCode);
            }
        }
    }
    

    如上,启动Activity离不开一个类Instrumentation,app进程就是依靠这个类与与处于系统进程的AMS进行通信:

    Instrumentation.java
    public ActivityResult execStartActivity(Context who, IBinder contextThread, IBinder token, Activity target,
            Intent intent, int requestCode, Bundle options) {
        IApplicationThread whoThread = (IApplicationThread) contextThread;
        ...
        try {
            ...
            //通过单例模式获取ATMS实例,并调用ATMS的startActivity方法
            int result = ActivityTaskManager.getService().startActivity(whoThread,
                    who.getOpPackageName(), who.getAttributionTag(), intent,
                    intent.resolveTypeIfNeeded(who.getContentResolver()), token,
                    target != null ? target.mEmbeddedID : null, requestCode, 0, null, options);
            ...
        } catch (RemoteException e) {
            throw new RuntimeException("Failure from system", e);
        }
        return null;
    }
    

    由于ATMS的实例是缓存在service manager进程里的,systemServer进程是怎么跨进程获取到这个IBinder对象的呢?
    那就先看下ActivityTaskManagergetService方法里是怎么做的:

    ActivityTaskManager.java
    public static IActivityTaskManager getService() {
        return IActivityTaskManagerSingleton.get();
    }
    //Singleton类使用了加了锁的懒汉式单例模式,最终是从ServiceManager的静态方法getService中获取
    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);
            }
        };
    
    ServiceManager.java
    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);
        ...
    }
    private static IServiceManager getIServiceManager() {
        ...
        //通过Binder获取到ServerManager引用
        sServiceManager = ServiceManagerNative
                .asInterface(Binder.allowBlocking(BinderInternal.getContextObject()));
        return sServiceManager;
    }
    

    BinderInternal.getContextObject()这个native方法获取到的就是IServiceManager的实现类IBinder对象, 其保存了已完成注册的服务名称和对应IBinder实体(系统服务基本都是继承自Binder以支持跨进程调用)。
    然后在ServiceManagerNativeasInterface里将IBinder转成IServiceMananger对象,之后调用getService就可以通过传进去的服务名称获取到对应服务的Ibinder对象了。
    所以本质上还是通过Binder机制来完成IPC以获取对应的Service对象的。

    ServiceManagerNative.java
    public static IServiceManager asInterface(IBinder obj) {
        ...
        return new ServiceManagerProxy(obj);
    }
    
    class ServiceManagerProxy implements IServiceManager {
        public ServiceManagerProxy(IBinder remote) {
            mRemote = remote;
            mServiceManager = IServiceManager.Stub.asInterface(remote);
        }
        public IBinder getService(String name) throws RemoteException {
            return mServiceManager.checkService(name);
        }
    }
    

    接着,我们拿到ATMS对象后调用startActivity方法,最后走到了:

    ActivityTaskManagerService.java
    private int startActivityAsUser(IApplicationThread caller, String callingPackage,
            @Nullable String callingFeatureId, Intent intent, String resolvedType,
            IBinder resultTo, String resultWho, int requestCode, int startFlags,
            ProfilerInfo profilerInfo, Bundle bOptions, int userId, boolean validateIncomingUser) {
    
        ...
        return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
                .setCaller(caller)
                .setCallingPackage(callingPackage)
                .setCallingFeatureId(callingFeatureId)
                .setResolvedType(resolvedType)
                .setResultTo(resultTo)
                .setResultWho(resultWho)
                .setRequestCode(requestCode)
                .setStartFlags(startFlags)
                .setProfilerInfo(profilerInfo)
                .setActivityOptions(opts)
                .setUserId(userId)
                .execute();
    
    }
    
    

    明显ATMS将启动Activity交给了内部成员ActivityStartController去操作,ActivityStartController每次启动Activity时都会在obtainStarter方法里从对象池中获取或new一个ActivityStarter对象,使用建造者模式的方式将需要的参数传给starter,最后调用execute方法。

    ActivityStarter.java
    int execute() {
        ...
        try {
            res = executeRequest(mRequest);
        } finally {
           ...
        }
    }
    
    private int executeRequest(Request request) {
        ...
        //intent没有指定组件名
        if (err == ActivityManager.START_SUCCESS && intent.getComponent() == null) {
            err = ActivityManager.START_INTENT_NOT_RESOLVED;
        }
        //目标Actiivty不存在
        if (err == ActivityManager.START_SUCCESS && aInfo == null) {
            err = ActivityManager.START_CLASS_NOT_FOUND;
        }
        ...
        //检查启动方是否有权限启动目标Activity,你可以在AndroidManifest里为Activity等组件设置permission属性来限制访问
        boolean abort;
        try {
            abort = !mSupervisor.checkStartAnyActivityPermission(intent, aInfo, resultWho,
                    requestCode, callingPid, callingUid, callingPackage, callingFeatureId,
                    request.ignoreTargetSecurity, inTask != null, callerApp, resultRecord,
                    resultRootTask);
        } catch (SecurityException e) {
        ...
        }
        //使用IntentFirewall过滤Intent
        abort |= !mService.mIntentFirewall.checkStartActivity(intent, callingUid,
            callingPid, resolvedType, aInfo.applicationInfo);
        //
        //检查action
        abort |= !mService.getPermissionPolicyInternal().checkStartActivity(intent, callingUid,
            callingPackage);
        //下面一系列都是对activity的启动进行检查的操作
        ...
        //创建一个ActivityRecord对象
        final ActivityRecord r = new ActivityRecord.Builder(mService)
                    .setCaller(callerApp)
                    .setLaunchedFromPid(callingPid)
                    .setLaunchedFromUid(callingUid)
                    .setLaunchedFromPackage(callingPackage)
                    .setLaunchedFromFeature(callingFeatureId)
                    .setIntent(intent)
                    .setResolvedType(resolvedType)
                    .setActivityInfo(aInfo)
                    .setConfiguration(mService.getGlobalConfiguration())
                    .setResultTo(resultRecord)
                    .setResultWho(resultWho)
                    .setRequestCode(requestCode)
                    .setComponentSpecified(request.componentSpecified)
                    .setRootVoiceInteraction(voiceSession != null)
                    .setActivityOptions(checkedOptions)
                    .setSourceRecord(sourceRecord)
                    .build();
        ...
        mLastStartActivityResult = startActivityUnchecked(r, sourceRecord, voiceSession,
                    request.voiceInteractor, startFlags, checkedOptions,
                    inTask, inTaskFragment, balCode, intentGrants, realCallingUid);
        ...
    }
    

    如上,ATMS每次启动一个Activity时都会创建一个ActivityRecord,包含了这个Activity的基本信息。

    ActivityStarter.java
    private int startActivityUnchecked(...) {
        ...
        try {
            result = startActivityInner(r, sourceRecord, voiceSession, voiceInteractor,
                startFlags, options, inTask, inTaskFragment, balCode,
                intentGrants, realCallingUid);
        } finally {
            startedActivityRootTask = handleStartResult(r, options, result, newTransition,
                    remoteTransition);
        }
    }
    
    int startActivityInner(...) {
        ...
        
        final Task reusedTask = getReusableTask();
        ...
        //计算并获取存放ActivityRecord的目标Task
        final Task targetTask = reusedTask != null ? reusedTask : computeTargetTask();
        final boolean newTask = targetTask == null;
        ...
        //获取或创建根task
        if (mTargetRootTask == null) {
            mTargetRootTask = getOrCreateRootTask(mStartActivity, mLaunchFlags, targetTask, mOptions);
        }
        //如果目标Task不存在则创建新的Task并add进上一步获取到的根task,或者添加到现有的Task
        if (newTask) {
            final Task taskToAffiliate = (mLaunchTaskBehind && mSourceRecord != null)
                    ? mSourceRecord.getTask() : null;
            setNewTask(taskToAffiliate);
        } else if (mAddingToTask) {
            addOrReparentStartingActivity(targetTask, "adding to task");
        }
        ...
        //调整目标task在根task里的顺序
        mTargetRootTask.startActivityLocked(mStartActivity, topRootTask, newTask, isTaskSwitch,
                    mOptions, sourceRecord);
        if (mDoResume) {
            ...
            if() {
                
            } else {
                mRootWindowContainer.resumeFocusedTasksTopActivities(
                    mTargetRootTask, mStartActivity, mOptions, mTransientLaunch);
            }
        }
        ...
        //将目标task添加到最近任务列表里
        mSupervisor.mRecentTasks.add(startedTask);
    }
    

    如上,还会复用或创建Task对象,这是一个容器,保管了一组满足一些共同条件的ActivityRecord,比如同一个TaskAffinity的ActivityRecord就会被归为一组,具现化来说,最近列表页即手机底部上滑出来的界面,里面每一个窗口就是一个Task,每个Task以栈的形式(使用ArrayList实现的栈效果)保存一个或复数个代表Activity的ActiivtyRecord对象。

    RootWindowContainer.java
    boolean resumeFocusedTasksTopActivities(...) {
        ...
        if (...) {
            result = targetRootTask.resumeTopActivityUncheckedLocked(target, targetOptions,
                deferPause);
        }
        ...
    }
    
    //Task.java
    boolean resumeTopActivityUncheckedLocked(...) {
        ...
        if (isLeafTask()) {
            if (isFocusableAndVisible()) {
                someActivityResumed = resumeTopActivityInnerLocked(prev, options, deferPause);
            }
        }
        ...
    }
    private boolean resumeTopActivityInnerLocked(...) {
        ...
        final boolean[] resumed = new boolean[1];
        final TaskFragment topFragment = topActivity.getTaskFragment();
        resumed[0] = topFragment.resumeTopActivity(prev, options, deferPause);
        ...
    }
    
    //TaskFragment.java
    final boolean resumeTopActivity(ActivityRecord prev, ActivityOptions options,
            boolean deferPause) {
        ActivityRecord next = topRunningActivity(true /* focusableOnly */);
        ...
        //如果当前Task中存在resume状态的Activity,则先pause该Activity
        if (mResumedActivity != null) {
            pausing |= startPausing(mTaskSupervisor.mUserLeaving, false /* uiSleeping */,
                next, "resumeTopActivity");
        }
        ...
        if (next.attachedToProcess()) {
        } else {
            ...
            mTaskSupervisor.startSpecificActivity(next, true, true);
        }
        return true;
    }
    

    如上,启动Activity走到了一个RootWindowContainer类里,这个对象代表设备窗口层级的根容器,管理Display的窗口状态和其他相关内容,其在WMS初始化时创建,并在systemServer初始化时传给ATMS。最后走到了ActivityTaskSupervisor里的startSpecificActivity方法里,如果目标进程正在运行,则继续启动Activity,如果不存在则先创建目标进程:

    ActivityTaskSupervisor.java
    void startSpecificActivity(ActivityRecord r, boolean andResume, boolean checkConfig) {
        final WindowProcessController wpc =
                    mService.getProcessController(r.processName, r.info.applicationInfo.uid);
        if (wpc != null && wpc.hasThread()) {
            try {
                //如果目标Activity的进程已经处于运行状态,则直接启动Activity
                realStartActivityLocked(r, wpc, andResume, checkConfig);
                return;
            } catch (RemoteException e) {
                Slog.w(TAG, "Exception when starting activity "
                        + r.intent.getComponent().flattenToShortString(), e);
            }
        } 
        ...
        //目标进程不在,则先异步启动进程
        mService.startProcessAsync(r, knownToBeDead, isTop,
                    isTop ? HostingRecord.HOSTING_TYPE_TOP_ACTIVITY
                            : HostingRecord.HOSTING_TYPE_ACTIVITY);
    }
    
    ActivityTaskManagerService.java
    void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
            String hostingType) {
        try {
            if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
                Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
                        + activity.processName);
            }
            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_WINDOW_MANAGER);
        }
    }
    

    通过Handler/Message的消息机制进行异步操作,mH是ATMS内部类H(继承自Handler)的实例,mAmInternal是通过LocalService.getService(ActivityManagerInternal.class)获取到的,这个是在AMS初始化时注册的内部类LocalService,这个对象持有AMS引用,封装了AMS对外提供的能力:

    ActivityManagerService.java
    public class ActivityManagerService extends ... {
        ...
        public final class LocalService extends ActivityManagerInternal implements ActivityManagerLocal {
            @Override
            public void startProcess(String processName, ApplicationInfo info, boolean knownToBeDead,
                    boolean isTop, String hostingType, ComponentName hostingName) {
                ...
                synchronized (ActivityManagerService.this) {
                    startProcessLocked(processName, info, knownToBeDead, 0 /* intentFlags */,
                            new HostingRecord(hostingType, hostingName, isTop),
                            ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE, false /* allowWhileBooting */,
                            false /* isolated */);
                }
            }
        }
        
        final ProcessRecord startProcessLocked(String processName, ApplicationInfo info, boolean knownToBeDead, int intentFlags,
                HostingRecord hostingRecord, int zygotePolicyFlags, boolean allowWhileBooting, boolean isolated) {
            return mProcessList.startProcessLocked(processName, info, knownToBeDead, intentFlags,
                    hostingRecord, zygotePolicyFlags, allowWhileBooting, isolated, 0 /* isolatedUid */,
                    false /* isSdkSandbox */, 0 /* sdkSandboxClientAppUid */,
                    null /* sdkSandboxClientAppPackage */,
                    null /* ABI override */, null /* entryPoint */,
                    null /* entryPointArgs */, null /* crashHandler */);
        }
    

    AMS将进程的管理工作交给了ProcessList类,包括了进程的启动和杀死,

    ProcessList.java
    ProcessRecord startProcessLocked(String processName, ApplicationInfo info,
                boolean knownToBeDead, int intentFlags, HostingRecord hostingRecord,
                int zygotePolicyFlags, boolean allowWhileBooting, boolean isolated, int isolatedUid,
                boolean isSdkSandbox, int sdkSandboxUid, String sdkSandboxClientAppPackage,
                String abiOverride, String entryPoint, String[] entryPointArgs, Runnable crashHandler) {
        ProcessRecord app;
        if (!isolated) {
            获取本地缓存的ProcessRecord对象
            app = getProcessRecordLocked(processName, info.uid);
            ...
        } else {
            app = null;
        }
        ...
        if (app == null) {
            //如果本地没有ProcessRecord,则创建一个
            app = newProcessRecordLocked(info, processName, isolated, isolatedUid, isSdkSandbox,
                    sdkSandboxUid, sdkSandboxClientAppPackage, hostingRecord);
            ...
        }
        ...
        final boolean success =
            startProcessLocked(app, hostingRecord, zygotePolicyFlags, abiOverride);
        return success ? app : null;
    }
    
    //经过一系列同名方法,走到这里
    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 startUptime, long startElapsedTime) {
        ...
        //如果配置为异步启动进程
        if (mService.mConstants.FLAG_PROCESS_START_ASYNC) {
            mService.mProcStartHandler.post(() -> handleProcessStart(
                    app, entryPoint, gids, runtimeFlags, zygotePolicyFlags, mountExternal,
                    requiredAbi, instructionSet, invokeWith, startSeq));
            return true;
        }
    }
    
    private void handleProcessStart(final ProcessRecord app, final String entryPoint,
            final int[] gids, final int runtimeFlags, int zygotePolicyFlags,
            final int mountExternal, final String requiredAbi, final String instructionSet,
            final String invokeWith, final long startSeq) {
        final Runnable startRunnable = () -> {
            try {
                final Process.ProcessStartResult startResult = startProcess(app.getHostingRecord(),
                        entryPoint, app, app.getStartUid(), gids, runtimeFlags, zygotePolicyFlags,
                        mountExternal, app.getSeInfo(), requiredAbi, instructionSet, invokeWith,
                        app.getStartTime());
    
                ...
            } catch (RuntimeException e) {
                ...
            }
        };
        ...
        startRunnable.run();
    }
    
    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) {
        ...
        if (hostingRecord.usesWebviewZygote()) {
            ...
        } else if (hostingRecord.usesAppZygote()) {
            ...
        } else {
            regularZygote = true;
            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.getDisabledCompatChanges(), pkgDataInfoMap,
                    allowlistedAppDataInfoMap, bindMountAppsData, bindMountAppStorageDirs,
                    new String[]{PROC_START_SEQ_IDENT + app.getStartSeq()});
            app.mProcessGroupCreated = true;
        }
        ...
        return startResult;
    }
    

    正如每个Activity都有对应的一个ActivityRecord实例一样,每个进程也对应一个ProcessRecordProcessList类内部用一个键值对形式的Map数据结构来保存ProcessRecord们,设计逻辑上将进程名和uid作为key。
    Process.start方法里会进行app进程的孵化,system_server进程通过socket的方式与zygote进程进行通信,zygote进程fork出一个子进程,并返回子进程的pid。

    //ZygoteProcess.java
    private Process.ProcessStartResult attemptZygoteSendArgsAndGetResult(
                ZygoteState zygoteState, String msgStr) throws ZygoteStartFailedEx {
        try {
            final BufferedWriter zygoteWriter = zygoteState.mZygoteOutputWriter;
            final DataInputStream zygoteInputStream = zygoteState.mZygoteInputStream;
    
            zygoteWriter.write(msgStr);
            zygoteWriter.flush();
    
            Process.ProcessStartResult result = new Process.ProcessStartResult();
            result.pid = zygoteInputStream.readInt();
            result.usingWrapper = zygoteInputStream.readBoolean();
    
            if (result.pid < 0) {
                throw new ZygoteStartFailedEx("fork() failed");
            }
    
            return result;
        } catch (IOException ex) {
            zygoteState.close();
            Log.e(LOG_TAG, "IO Exception while communicating with Zygote - "
                    + ex.toString());
            throw new ZygoteStartFailedEx(ex);
        }
    }
    

    zygote创建子进程在native层的细节就先不讲了,我们需要知道的是,当app进程创建好后,通过反射进入我们上面注释提到过的ActivityThread.main方法,接下来就走进应用进程的初始化工作:

    ActivityThread.java
    public static void main(String[] args) {
        ...
        //创建主线程的looper
        Looper.prepareMainLooper();
        ...
        //创建ActivityThread对象
        ActivityThread thread = new ActivityThread();
        thread.attach(false, startSeq);
        //获取ActivityThread的内部类H对象,继承自Handler
        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }
        ...
        //无限循环等待、处理主线程MessageQueue里面的消息
        Lopper.loop()
    }
    

    main方法里主要是创建了应用进程的主线程Looper对象,并开始循环等待处理Message。同时为当前进程创建了一个ActivityThread对象,ActivityThread是应用进程用来请求与AMS相关API的类,并调用了attach方法。

    ActivityThread.java
    private void attach(boolean system, long startSeq) {
        if (!system) {//非systemserver进程
            //获取AMS对象,是个IBinder
            final IActivityManager mgr = ActivityManager.getService();
            try {
                mgr.attachApplication(mAppThread, startSeq);
            } catch (RemoteException ex) {
                throw ex.rethrowFromSystemServer();
            }
        }
    }
    

    如上,应用进程与AMS所在的SystemServer进程通信的方式就是Binder,通过Binder驱动获取到AMS对象,并调用attachApplication方法,并将ApplicationThread传进去,这是ActivityThread的内部类。而ApplicationThread是app进程本地生成并传给AMS的IBinder对象,用来让AMS与APP进程通信的。接着就从应用进程回到了systemserver进程。

    ActivityManagerService.java
    public final void attachApplication(IApplicationThread thread, long startSeq) {
        ...
        synchronized (this) {
            int callingPid = Binder.getCallingPid();
            final int callingUid = Binder.getCallingUid();
            final long origId = Binder.clearCallingIdentity();
            attachApplicationLocked(thread, callingPid, callingUid, startSeq);
            Binder.restoreCallingIdentity(origId);
        }
    }
    
    private void attachApplicationLocked(@NonNull IApplicationThread thread,
                int pid, int callingUid, long startSeq) {
        ...
        //找到本地之前创建进程时缓存下来的ProcessRecord对象,startSeq就是个AMS计算已启动进程数量的计数而已,无特别实际含义
        if (app == null && startSeq > 0) {
            final ProcessRecord pending = mProcessList.mPendingStarts.get(startSeq);
            if (pending != null && pending.getStartUid() == callingUid
                    && pending.getStartSeq() == startSeq
                    && mProcessList.handleProcessStartedLocked(pending, pid,
                        pending.isUsingWrapper(), startSeq, true)) {
                app = pending;
            }
        }
        ...
        //使用AppDeathRecipient监听IApplicationThread这个代表app进程的IBinder死亡状态
         try {
            AppDeathRecipient adr = new AppDeathRecipient(
                    app, pid, thread);
            thread.asBinder().linkToDeath(adr, 0);
            app.setDeathRecipient(adr);
        } catch (RemoteException e) {
            app.resetPackageList(mProcessStats);
            mProcessList.startProcessLocked(app,
                    new HostingRecord(HostingRecord.HOSTING_TYPE_LINK_FAIL, processName),
                    ZYGOTE_POLICY_FLAG_EMPTY);
            return;
        }
        ...
        //创建app的ContentProviderRecord对象
        List<ProviderInfo> providers = normalMode
            ? mCpHelper.generateApplicationProvidersLocked(app)
            : null;
        ...
        thread.bindApplication(processName, appInfo,
                            app.sdkSandboxClientAppVolumeUuid, app.sdkSandboxClientAppPackage,
                            providerList, null, profilerInfo, null, null, null, testMode,
                            mBinderTransactionTrackingEnabled, enableTrackAllocation,
                            isRestrictedBackupMode || !normalMode, app.isPersistent(),
                            new Configuration(app.getWindowProcessController().getConfiguration()),
                            app.getCompat(), getCommonServicesLocked(app.isolated),
                            mCoreSettingsObserver.getCoreSettingsLocked(),
                            buildSerial, autofillOptions, contentCaptureOptions,
                            app.getDisabledCompatChanges(), serializedSystemFontMap,
                            app.getStartElapsedTime(), app.getStartUptime());
        ...
    }
    

    AMS接着又调用ApplicationThreadbindApplication方法回到app进程。

    ActivityThread.java
    private class ApplicationThread extends IApplicationThread.Stub {
        @Override
        public final void bindApplication(String processName, ApplicationInfo appInfo,
                String sdkSandboxClientAppVolumeUuid, String sdkSandboxClientAppPackage,
                ProviderInfoList providerList, ComponentName instrumentationName,
                ProfilerInfo profilerInfo, Bundle instrumentationArgs,
                IInstrumentationWatcher instrumentationWatcher,
                IUiAutomationConnection instrumentationUiConnection, int debugMode,
                boolean enableBinderTracking, boolean trackAllocation,
                boolean isRestrictedBackupMode, boolean persistent, Configuration config,
                CompatibilityInfo compatInfo, Map services, Bundle coreSettings,
                String buildSerial, AutofillOptions autofillOptions,
                ContentCaptureOptions contentCaptureOptions, long[] disabledCompatChanges,
                SharedMemory serializedSystemFontMap,
                long startRequestedElapsedTime, long startRequestedUptime) {
            ...
            //创建AppBindData对象, 缓存一些app信息,比如provider信息,是否persistent,Configuration等等
            AppBindData data = new AppBindData();
            ...
            //采用Message方式进行下一步
            sendMessage(H.BIND_APPLICATION, data);
        }
    }
    

    为了保证进程一些操作的线程安全性,采用了Handler/Message处理操作,完成线程切换,保证都是在主线程里面处理消息。内部类H接收到H.BIND_APPLICATION消息时,调用了handleBindApplication(data)方法。

    ActivityThread.java
    private void handleBindApplication(AppBindData data) {
        ...
        创建Instrumentation,用来监听应用进程与系统进程之间的所有通信、交互操作
        if (ii != null) {
            ...
        } else {
            mInstrumentation = new Instrumentation();
            mInstrumentation.basicInit(this);
        }
        ...
        //创建Application对象
        Application app;
        app = data.info.makeApplicationInner(data.restrictedBackupMode, null);
        ...
        //根据ContentProviderRecord创建app的ContentProvider
        if (!data.restrictedBackupMode) {
            if (!ArrayUtils.isEmpty(data.providers)) {
                installContentProviders(app, data.providers);
            }
        }
        ...
        try {
            //调用Application的onCreate方法
            mInstrumentation.callApplicationOnCreate(app);
        } catch (Exception e) {
            if (!mInstrumentation.onException(app, e)) {
                throw new RuntimeException(
                  "Unable to create application " + app.getClass().getName()
                  + ": " + e.toString(), e);
            }
        }
        ...
        try {
            //mgr是AMS对象,通知AMS完成attachApplication操作
            mgr.finishAttachApplication(mStartSeq);
        } catch (RemoteException ex) {
            throw ex.rethrowFromSystemServer();
        }
    }
    

    如上,ActivityThread的handleBindApplication方法里创建了应用的InstrumentationApplication对象并调用了相应的初始化方法,此外创建了应用的ContentProvider对象并完成初始化。

    ActivityManagerService
    @Override
    public final void finishAttachApplication(long startSeq) {
        ...
        final long origId = Binder.clearCallingIdentity();
        try {
            finishAttachApplicationInner(startSeq, uid, pid);
        } finally {
            Binder.restoreCallingIdentity(origId);
        }
    }
    
    private void finishAttachApplicationInner(long startSeq, int uid, int pid) {
        ...
        //检查是否存在等待启动的Activity
        if (normalMode) {
            try {
                didSomething = mAtmInternal.attachApplication(app.getWindowProcessController());
            } catch (Exception e) {
                Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
                badApp = true;
            }
        }
    
        //检查是否存在等待启动的Service
        if (!badApp) {
            try {
                didSomething |= mServices.attachApplicationLocked(app, processName);
                checkTime(startTime, "finishAttachApplicationInner: "
                        + "after mServices.attachApplicationLocked");
            } catch (Exception e) {
                Slog.wtf(TAG, "Exception thrown starting services in " + app, e);
                badApp = true;
            }
        }
        
        //检查是否存在等待启动的Broadcast
        if (!badApp) {
            try {
                for (BroadcastQueue queue : mBroadcastQueues) {
                    didSomething |= queue.onApplicationAttachedLocked(app);
                }
                checkTime(startTime, "finishAttachApplicationInner: "
                        + "after dispatching broadcasts");
            } catch (BroadcastDeliveryFailedException e) {
                // If the app died trying to launch the receiver we declare it 'bad'
                Slog.wtf(TAG, "Exception thrown dispatching broadcasts in " + app, e);
                badApp = true;
            }
        }
        ...
    }
    

    如上,在AMS内完成进程启动步骤的最后,会检查是否存在等待启动的Activity、Service、Broadcast,如果有的话,就会依次开始启动相应的组件。

    ActivityTaskManagerService.java
    final class LocalService extends ActivityTaskManagerInternal {
        @Override
        public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
            synchronized (mGlobalLockWithoutBoost) {
                ...
                return mRootWindowContainer.attachApplication(wpc);
            }
        }
    }
    
    RootWindowContainer.java
    boolean attachApplication(WindowProcessController app) throws RemoteException {
        try {
            return mAttachApplicationHelper.process(app);
        } finally {
            mAttachApplicationHelper.reset();
        }
    }
    
    private class AttachApplicationHelper implements Consumer<Task>, Predicate<ActivityRecord> {
        boolean process(WindowProcessController app) throws RemoteException {
            mApp = app;
            for (int displayNdx = getChildCount() - 1; displayNdx >= 0; --displayNdx) {
                getChildAt(displayNdx).forAllRootTasks(this);
                if (mRemoteException != null) {
                    throw mRemoteException;
                }
            }
            if (!mHasActivityStarted) {
                ensureActivitiesVisible(null /* starting */, 0 /* configChanges */,
                        false /* preserveWindows */);
            }
            return mHasActivityStarted;
        }
    }
    
    WindowContainer.java
    void forAllRootTasks(Consumer<Task> callback) {
        forAllRootTasks(callback, true /* traverseTopToBottom */);
    }
    
    void forAllRootTasks(Consumer<Task> callback, boolean traverseTopToBottom) {
        int count = mChildren.size();
        if (traverseTopToBottom) {
            for (int i = count - 1; i >= 0; --i) {
                mChildren.get(i).forAllRootTasks(callback, traverseTopToBottom);
            }
        } else {
            ...
        }
    }
    

    为什么forAllRootTasks这个方法最终会调到了TaskforAllRootTasks方法,从全局所有看只有Task重写了这个方法,但RootWindowContainer这个容器管理的子类明明是DisplayContentDisplayContentTask都是WindowContainer的子类,但为什么会走到Task里面呢?暂时没想通,但全局只有Task这个子类重写了,只能先往这里分析了,有大佬明白的麻烦指教一下。

    Task.java
    @Override
    void forAllRootTasks(Consumer<Task> callback, boolean traverseTopToBottom) {
        if (isRootTask()) {
            callback.accept(this);
        }
    }
    

    这个callback就是RootWindowContainer内部类AttachApplicationHelper,因为之前调用了forAllRootTasksthis传了进去。

    RootWindowContainer.java
    private class AttachApplicationHelper implements Consumer<Task>, Predicate<ActivityRecord> {
        @Override
        public void accept(Task rootTask) {
            ...
            rootTask.forAllActivities(this);
        }
    }
    
    

    Task没有重写forAllActivities,还是只能往父类WindowContainer里找,

    WindowContainer.java
    boolean forAllActivities(Predicate<ActivityRecord> callback) {
        return forAllActivities(callback, true /*traverseTopToBottom*/);
    }
    
    boolean forAllActivities(Predicate<ActivityRecord> callback, boolean traverseTopToBottom) {
        if (traverseTopToBottom) {
            for (int i = mChildren.size() - 1; i >= 0; --i) {
                if (mChildren.get(i).forAllActivities(callback, traverseTopToBottom)) return true;
            }
        } else {
            ...
        }
    
        return false;
    }
    
    ActivityRecord.java
    @Override
    boolean forAllActivities(Predicate<ActivityRecord> callback, boolean traverseTopToBottom) {
        return callback.test(this);
    }
    
    RootWindowContainer.java
    private class AttachApplicationHelper implements Consumer<Task>, Predicate<ActivityRecord> {
        @Override
        public boolean test(ActivityRecord r) {
            ...
            try {
                if (mTaskSupervisor.realStartActivityLocked(r, mApp,
                        mTop == r && r.getTask().canBeResumed(r) /* andResume */,
                        true /* checkConfig */)) {
                    mHasActivityStarted = true;
                }
            } catch (RemoteException e) {
                Slog.w(TAG, "Exception in new application when starting activity " + mTop, e);
                mRemoteException = e;
                return true;
            }
            return false;
        }
    }
    
    

    最后回到了ActivityTaskSupervisorrealStartActivityLocked方法。

    ActivityTaskSupervisor.java
    boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
            boolean andResume, boolean checkConfig) throws RemoteException {
        ...
        //创建Activity启动事务
        final ClientTransaction clientTransaction = ClientTransaction.obtain(
            proc.getThread(), r.token);
        ...
        //添加通知客户端启动Activity的消息回调
        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(), deviceId,
                            r.getFilteredReferrer(r.launchedFromPackage), task.voiceInteractor,
                            proc.getReportedProcState(), r.getSavedState(), r.getPersistentSavedState(),
                            results, newIntents, r.takeOptions(), isTransitionForward,
                            proc.createProfilerInfoIfNeeded(), r.assistToken, activityClientController,
                            r.shareableActivityToken, r.getLaunchedFromBubble(), fragmentToken));
        //添加客户端最终执行的消息,即resume消息
        final ActivityLifecycleItem lifecycleItem;
        if (andResume) {
            lifecycleItem = ResumeActivityItem.obtain(isTransitionForward,
                    r.shouldSendCompatFakeFocus());
        } else {
            ...
        }
        clientTransaction.setLifecycleStateRequest(lifecycleItem);
    
        //执行
        mService.getLifecycleManager().scheduleTransaction(clientTransaction);
    }
    

    AMS在启动Activity时使用了ClientTransaction类,用来管理一系列需要发送给客户端的消息,比如生命周期状态变化的消息。我们可以看到前后是添加了两个执行消息,先是LaunchActivityItem,然后是ResumeActivityItem。最后调用ClientLifecycleManager.scheduleTransaction方法开始执行。
    从后续的代码里可以看到,最后执行的是从app客户端传过来的ApplicationThreadscheduleTransaction方法。

    ClientTransaction.java
    public class ClientTransaction implements Parcelable, ObjectPoolItem {
        private IApplicationThread mClient;
        public void schedule() throws RemoteException {
            mClient.scheduleTransaction(this);
        }
    }
    

    通过Binder通信回到app的ApplicationThread服务端实现方法。

    ActivityThread.java
    public final class ActivityThread extends ClientTransactionHandler implements ActivityThreadInternal {
        private class ApplicationThread extends IApplicationThread.Stub {
            @Override
            public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
                ActivityThread.this.scheduleTransaction(transaction);
            }
        }
    }
    

    ActivityThread没有重写scheduleTransaction方法,所以回到父类里面,

    ClientTransactionHandler.java
    public abstract class ClientTransactionHandler {
        void scheduleTransaction(ClientTransaction transaction) {
            //依次调用回调的preExecute方法
            transaction.preExecute(this);
            //使用Handler/Message处理AMS传过来的消息
            sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
        }
    }
    
    ActivityThread.java
    class H extends Handler {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case EXECUTE_TRANSACTION:
                    final ClientTransaction transaction = (ClientTransaction) msg.obj;
                    mTransactionExecutor.execute(transaction);
                    ...
                break;
                ...
            }
        }
    }
    
    TransactionExecutor.java
    public class TransactionExecutor {
        public void execute(ClientTransaction transaction) {
    
            final IBinder token = transaction.getActivityToken();
            ...
            //先依次执行每个回调的execute,postExecute方法,即上面我们看到的LaunchActivityItem
            executeCallbacks(transaction);
            //再执行最后的生命周期事务消息的execute,postExecute方法,即上面我们看到的ResumeActivityItem
            executeLifecycleState(transaction);
            mPendingActions.clear();
            if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "End resolving transaction");
        }
    }
    

    这里就会依次执行我们之前添加的LaunchActivityItemResumeActivityItem。这些都是可序列化对象,所以能够跨进程传输。

    LaunchActivityItem.java
    public class LaunchActivityItem extends ClientTransactionItem {
        @Override
        public void execute(ClientTransactionHandler client, IBinder token,
                PendingTransactionActions pendingActions) {
            ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
                    mOverrideConfig, mReferrer, mVoiceInteractor, mState, mPersistentState,
                    mPendingResults, mPendingNewIntents, mActivityOptions, mIsForward, mProfilerInfo,
                    client, mAssistToken, mShareableActivityToken, mLaunchedFromBubble,
                    mTaskFragmentToken);
            client.handleLaunchActivity(r, pendingActions, mDeviceId, null /* customIntent */);
        }
    }
    

    创建了ActivityClientRecord对象,其是ActivityThread的静态内部类,并执行client即ActivityThreadhandleLaunchActivity。注意,当前还是处于app进程中的。

    ActivityThread.java
    @Override
    public Activity handleLaunchActivity(ActivityClientRecord r,
            PendingTransactionActions pendingActions, int deviceId, Intent customIntent) {
        ...
        final Activity a = performLaunchActivity(r, customIntent);
        ...
        return a;
    }
        
    private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        ...
        //创建Activity的上下文
        ContextImpl appContext = createBaseContextForActivity(r);
        Activity activity = null;
        try {
            java.lang.ClassLoader cl = appContext.getClassLoader();
            //创建Activity对象
            activity = mInstrumentation.newActivity(
                    cl, component.getClassName(), r.intent);
            ...
        } catch (Exception e) {
            ...
        }
        ...
        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.activityConfigCallback,
            r.assistToken, r.shareableActivityToken);
        //设置主题
        if (theme != 0) {
            activity.setTheme(theme);
        }
        ...
        //开始执行Activity的onCreate生命周期方法
        if (r.isPersistable()) {
            mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
        } else {
            mInstrumentation.callActivityOnCreate(activity, r.state);
        }
        
        return activity;
    }
    

    performLaunchActivity方法里,正式创建了Activity对象,对其进行一些初始化操作,重点关注Activity.attachInstrumentation.callActivityOnCreate方法,开始进入我们熟悉的一些生命周期方法,如onCreate。

    Activity.java
    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, IBinder assistToken,
                IBinder shareableActivityToken) {
        ...
        //创建PhoneWindow对象,每个Activity对应一个PhoneWindow,管理Activity的窗口
        mWindow = new PhoneWindow(this, window, activityConfigCallback);
    }
    
    Instrumentation.java
    public void callActivityOnCreate(Activity activity, Bundle icicle) {
        prePerformCreate(activity);
        //执行
        activity.performCreate(icicle);
        postPerformCreate(activity);
    }
    
    Activity.java
    final void performCreate(Bundle icicle) {
        performCreate(icicle, null);
    }
    
    final void performCreate(Bundle icicle, PersistableBundle persistentState) {
        dispatchActivityPreCreated(icicle);
        mCanEnterPictureInPicture = true;
        // 判断是否分屏模式、画中画模式
        final int windowingMode = getResources().getConfiguration().windowConfiguration
                .getWindowingMode();
        mIsInMultiWindowMode = inMultiWindowMode(windowingMode);
        mIsInPictureInPictureMode = windowingMode == WINDOWING_MODE_PINNED;
        //执行onCreate方法
        if (persistentState != null) {
            onCreate(icicle, persistentState);
        } else {
            onCreate(icicle);
        }
        ...
    }
    

    到这TransactionExecutor执行完了LaunchActivityItem切换到onCreate状态,接下来执行ResumeActivityItem即切换到onResume状态,那其中的onStart中间状态呢?其实就在ResumeActivityItem里面,我们一开始就通过LaunchActivityItemResumeActivityItem这两个规定了始终状态:onCreate -> onResume,如下,在执行正式执行ResumeActivityItem前,会在cycleToPath方法里,把始终两个状态中间的状态消息添加到执行序列里,其中就包括了onStart状态,生命周期的状态值从小到大如下:

    public static final int UNDEFINED = -1;
    public static final int PRE_ON_CREATE = 0;
    public static final int ON_CREATE = 1;
    public static final int ON_START = 2;
    public static final int ON_RESUME = 3;
    public static final int ON_PAUSE = 4;
    public static final int ON_STOP = 5;
    public static final int ON_DESTROY = 6;
    public static final int ON_RESTART = 7;
    
    TransactionExecutor.java
    private void executeLifecycleState(ClientTransaction transaction) {
        ...
        // 计算当前状态到最终状态的中间态并添加到执行序列里执行
        cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */, transaction);
    
        lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
        lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
    }
    

    中间的onStart我们可以不用看了,继续关注最后的onResume状态切换。

    ResumeActivityItem.java
    @Override
    public void execute(ClientTransactionHandler client, ActivityClientRecord r,
            PendingTransactionActions pendingActions) {
        client.handleResumeActivity(r, true /* finalStateRequest */, mIsForward,
                mShouldSendCompatFakeFocus, "RESUME_ACTIVITY");
    }
    
    ActivityThread.java
    @Override
    public void handleResumeActivity(ActivityClientRecord r, boolean finalStateRequest,
            boolean isForward, boolean shouldSendCompatFakeFocus, String reason) {
        ...
        if (!performResumeActivity(r, finalStateRequest, reason)) {
                return;
        }
        ...
    }
    
    public boolean performResumeActivity(ActivityClientRecord r, boolean finalStateRequest,
            String reason) {
        ...
        r.activity.performResume(r.startsNotResumed, reason);
    }
    
    Activity.java
    final void performResume(boolean followedByPause, String reason) {
        ...
        //调用onResume方法
        mInstrumentation.callActivityOnResume(this);
        ...
    }
    

    至此,Activity的启动流程基本分析完了,进程的启动 -> Activity的创建 -> onCreate -> onStart -> onResume。至于界面的绘制,窗口的管理等等之后再梳理吧。

    相关文章

      网友评论

          本文标题:Android14 AMS源码解析

          本文链接:https://www.haomeiwen.com/subject/prwjcjtx.html