前文回顾:
Android8 从系统启动到用户见到第一个Activity的流程源码分析(三)-CSDN博客文章浏览阅读5次。本文分析了Android8系统启动第一个Activity的关键流程:从Zygote fork出新进程后,调用ActivityThread的main方法初始化主线程Looper,并通过attach方法将ApplicationThread对象绑定到AMS。重点解析了进程间通信机制,包括参数传递、安全策略检查、资源限制设置等核心步骤,最终实现应用进程与系统服务的绑定。该流程涉及Zygote进程管理、Binder通信、消息循环机制等多个系统模块的协同工作,为后续分析Activity生命周期和界面展示奠定了基础。 https://blog.csdn.net/g_i_a_o_giao/article/details/151076048?spm=1011.2124.3001.6209Android8 从系统启动到用户见到第一个Activity的流程源码分析(二)-CSDN博客文章浏览阅读544次,点赞16次,收藏8次。本文分析了Android系统启动第一个Activity的关键流程。首先通过ActivityStarter的startActivityUnchecked方法初始化状态并确定目标任务栈,接着调用ActivityStackSupervisor的resumeFocusedStackTopActivityLocked方法恢复焦点栈顶Activity。当检测到目标进程不存在时,AMS会通过startProcessLocked方法创建新进程,该方法经过多次重载最终调用Process.start,通过Zygote fork https://blog.csdn.net/g_i_a_o_giao/article/details/151027854?spm=1011.2124.3001.6209Android8 从系统启动到用户见到第一个Activity的流程源码分析(一)-CSDN博客文章浏览阅读416次,点赞3次,收藏4次。本文分析了Android系统启动过程中AMS(ActivityManagerService)的systemReady方法及其关键流程。当SystemService调用AMS的systemReady方法后,AMS会初始化各类服务,清理不允许运行的进程,最终通过startHomeActivityLocked启动主屏幕Activity。该流程涉及多个关键步骤: 创建Home Intent并解析对应Activity信息 通过ActivityStarter启动主屏幕Activity 在startActivityLoc https://blog.csdn.net/g_i_a_o_giao/article/details/150958400?spm=1011.2124.3001.6209紧接上文,我们分析到attachApplication方法会将ApplicationThread的binder对象传递给AMS。那么,我们再来详细分析一下这个方法。在这个方法中,最重要的是调用attachApplicationLocked方法。在这个attachApplicationLocked方法中,首先就是查找与验证、清理与设置、配置各种信息,然后就是调用IApplicationThread对象的bindApplication方法。

@Override
    public final void attachApplication(IApplicationThread thread) {
        synchronized (this) {
            int callingPid = Binder.getCallingPid();
            final long origId = Binder.clearCallingIdentity();
            attachApplicationLocked(thread, callingPid);
            Binder.restoreCallingIdentity(origId);
        }
    }


/**
 * 处理应用进程成功启动并通过IApplicationThread连接到系统服务后的绑定逻辑。
 * 这是一个同步方法,调用者需要持有AMS锁。
 *
 * @param thread 应用进程的IApplicationThread Binder接口,AMS通过它与应用进程通信
 * @param pid 应用进程的PID
 * @return boolean 如果应用成功绑定则返回true,否则返回false
 */
private final boolean attachApplicationLocked(IApplicationThread thread, int pid) {

    // 1. 通过PID查找对应的ProcessRecord:根据传入的pid,从mPidsSelfLocked映射表中查找之前创建的进程记录。
    ProcessRecord app;
    long startTime = SystemClock.uptimeMillis(); // 记录开始时间用于性能分析
    if (pid != MY_PID && pid >= 0) { // MY_PID是system_server的PID,排除自己
        synchronized (mPidsSelfLocked) {
            app = mPidsSelfLocked.get(pid);
        }
    } else {
        app = null;
    }

    // 2. 找不到ProcessRecord的处理:如果找不到对应的进程记录,说明状态不一致,可能是进程记录已被移除或PID冲突。
    if (app == null) {
        Slog.w(TAG, "No pending application record for pid " + pid
                + " (IApplicationThread " + thread + "); dropping process");
        EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid); // 记录事件日志
        if (pid > 0 && pid != MY_PID) {
            killProcessQuiet(pid); // 杀死这个无法识别的进程
            //TODO: killProcessGroup(app.info.uid, pid); // 未来可能会杀死整个进程组
        } else {
            try {
                thread.scheduleExit(); // 如果pid异常,则优雅地通知进程退出
            } catch (Exception e) {
                // 忽略异常
            }
        }
        return false; // 绑定失败
    }

    // 3. 清理旧的线程引用:如果这个ProcessRecord仍然附着在之前的进程上(例如进程崩溃后快速重启),
    //    则需要先清理旧的状态(handleAppDiedLocked)。
    if (app.thread != null) {
        handleAppDiedLocked(app, true, true); // 处理应用死亡,清理状态
    }

    // 4. 设置死亡接收器:绑定死亡通知,当应用进程意外终止时,AMS能够收到通知。
    if (DEBUG_ALL) Slog.v(TAG, "Binding process pid " + pid + " to record " + app);
    final String processName = app.processName;
    try {
        AppDeathRecipient adr = new AppDeathRecipient(app, pid, thread);
        thread.asBinder().linkToDeath(adr, 0); // 链接到死亡通知
        app.deathRecipient = adr; // 存储在ProcessRecord中
    } catch (RemoteException e) {
        // 如果设置死亡通知失败(例如进程已经死了),则重置包列表并重新启动进程
        app.resetPackageList(mProcessStats);
        startProcessLocked(app, "link fail", processName);
        return false;
    }
    EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.userId, app.pid, app.processName);

    // 5. 更新ProcessRecord状态:将IApplicationThread设置为活跃状态,并初始化各种状态标志。
    app.makeActive(thread, mProcessStats); // 设置thread引用,标记进程为活跃
    app.curAdj = app.setAdj = app.verifiedAdj = ProcessList.INVALID_ADJ; // 重置优先级
    app.curSchedGroup = app.setSchedGroup = ProcessList.SCHED_GROUP_DEFAULT; // 重置调度组
    app.forcingToImportant = null;
    updateProcessForegroundLocked(app, false, false); // 更新进程前台状态
    app.hasShownUi = false;  // 重置显示UI标志
    app.debugging = false;   // 重置调试标志
    app.cached = false;      // 重置缓存标志
    app.killedByAm = false;  // 重置被AMS杀死标志
    app.killed = false;      // 重置被杀标志

    // 6. 检查用户状态:判断用户是否已解锁,这与PackageManager的状态保持一致,
    //    用于决定稍后用户解锁时是否需要安装ContentProvider。
    app.unlocked = StorageManager.isUserKeyUnlocked(app.userId);

    // 7. 移除进程启动超时消息:既然进程已经成功启动并连接,不再需要超时监控。
    mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);

    // 8. 准备ContentProvider:如果系统已就绪或该应用允许在启动时运行,则生成该应用需要的ContentProvider列表。
    boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
    List<ProviderInfo> providers = normalMode ? generateApplicationProvidersLocked(app) : null;

    // 9. 设置ContentProvider发布超时:如果该进程有需要启动的Provider,设置一个超时监控。
    if (providers != null && checkAppInLaunchingProvidersLocked(app)) {
        Message msg = mHandler.obtainMessage(CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG);
        msg.obj = app;
        mHandler.sendMessageDelayed(msg, CONTENT_PROVIDER_PUBLISH_TIMEOUT);
    }

    checkTime(startTime, "attachApplicationLocked: before bindApplication");
    if (!normalMode) {
        Slog.i(TAG, "Launching preboot mode app: " + app); // 预启动模式日志
    }
    if (DEBUG_ALL) Slog.v(TAG, "New app record " + app + " thread=" + thread.asBinder() + " pid=" + pid);

    try {
        // 10. 配置调试和性能分析模式:
        int testMode = ApplicationThreadConstants.DEBUG_OFF;
        if (mDebugApp != null && mDebugApp.equals(processName)) {
            // 检查此进程是否被标记为需要调试
            testMode = mWaitForDebugger ? ApplicationThreadConstants.DEBUG_WAIT : ApplicationThreadConstants.DEBUG_ON;
            app.debugging = true; // 标记进程正在调试
            if (mDebugTransient) {
                mDebugApp = mOrigDebugApp; // 恢复原始调试应用设置
                mWaitForDebugger = mOrigWaitForDebugger;
            }
        }

        ProfilerInfo profilerInfo = null;
        String agent = null;
        if (mProfileApp != null && mProfileApp.equals(processName)) {
            // 检查此进程是否被标记为需要性能分析
            mProfileProc = app;
            profilerInfo = (mProfilerInfo != null && mProfilerInfo.profileFile != null) ? new ProfilerInfo(mProfilerInfo) : null;
            agent = mProfilerInfo != null ? mProfilerInfo.agent : null; // 获取性能分析代理
        } else if (app.instr != null && app.instr.mProfileFile != null) {
            // 如果通过Instrumentation启动且有性能分析文件,也设置ProfilerInfo
            profilerInfo = new ProfilerInfo(app.instr.mProfileFile, null, 0, false, false, null);
        }

        boolean enableTrackAllocation = false;
        if (mTrackAllocationApp != null && mTrackAllocationApp.equals(processName)) {
            // 检查是否需要跟踪内存分配
            enableTrackAllocation = true;
            mTrackAllocationApp = null;
        }

        // 11. 检查是否为备份模式:如果应用是为备份或恢复操作启动的,设置特殊标志。
        boolean isRestrictedBackupMode = false;
        if (mBackupTarget != null && mBackupAppName.equals(processName)) {
            isRestrictedBackupMode = mBackupTarget.appInfo.uid >= FIRST_APPLICATION_UID
                    && ((mBackupTarget.backupMode == BackupRecord.RESTORE)
                            || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
                            || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL));
        }

        if (app.instr != null) {
            notifyPackageUse(app.instr.mClass.getPackageName(), PackageManager.NOTIFY_PACKAGE_USE_INSTRUMENTATION);
        }

        // 12. 准备应用信息与兼容性配置:
        ApplicationInfo appInfo = app.instr != null ? app.instr.mTargetInfo : app.info;
        app.compat = compatibilityInfoForPackageLocked(appInfo); // 获取兼容性信息

        if (profilerInfo != null && profilerInfo.profileFd != null) {
            profilerInfo.profileFd = profilerInfo.profileFd.dup(); // 复制FD,用于性能分析
        }

        // 13. 处理Build.SERIAL的安全访问:针对v2安全沙箱的应用,隐藏真实的Build.SERIAL。
        String buildSerial = appInfo.targetSandboxVersion < 2 ? sTheRealBuildSerial : Build.UNKNOWN;

        // 14. 检查并关联Instrumentation:如果当前有活跃的Instrumentation,并且这是一个应该被纳入其中的次要进程。
        if (mActiveInstrumentation.size() > 0 && app.instr == null) {
            for (int i = mActiveInstrumentation.size() - 1; i >= 0 && app.instr == null; i--) {
                ActiveInstrumentation aInstr = mActiveInstrumentation.get(i);
                if (!aInstr.mFinished && aInstr.mTargetInfo.uid == app.uid) {
                    if (aInstr.mTargetProcesses.length == 0) {
                        // 通配符模式:所有为目标instrumentation启动的进程都应被包含
                        if (aInstr.mTargetInfo.packageName.equals(app.info.packageName)) {
                            app.instr = aInstr;
                            aInstr.mRunningProcesses.add(app);
                        }
                    } else {
                        for (String proc : aInstr.mTargetProcesses) {
                            if (proc.equals(app.processName)) {
                                app.instr = aInstr;
                                aInstr.mRunningProcesses.add(app);
                                break;
                            }
                        }
                    }
                }
            }
        }

        // 15. 附加启动代理:如果要求在启动时附加代理,在绑定应用代码之前完成。
        if (agent != null) {
            thread.attachAgent(agent);
        }

        // 16. 【核心调用】绑定应用到进程:通过Binder调用应用进程的bindApplication方法,
        //     将所有必要的信息(应用信息、Provider、调试设置、配置等)传递给应用进程。
        checkTime(startTime, "attachApplicationLocked: immediately before bindApplication");
        mStackSupervisor.mActivityMetricsLogger.notifyBindApplication(app); // 通知指标记录器

        if (app.instr != null) {
            // 带有Instrumentation的绑定调用
            thread.bindApplication(processName, appInfo, providers, app.instr.mClass,
                    profilerInfo, app.instr.mArguments, app.instr.mWatcher,
                    app.instr.mUiAutomationConnection, testMode,
                    mBinderTransactionTrackingEnabled, enableTrackAllocation,
                    isRestrictedBackupMode || !normalMode, app.persistent,
                    new Configuration(getGlobalConfiguration()), app.compat,
                    getCommonServicesLocked(app.isolated),
                    mCoreSettingsObserver.getCoreSettingsLocked(), buildSerial);
        } else {
            // 普通的绑定调用(加了日志打印确定是执行到这里)
            thread.bindApplication(processName, appInfo, providers, null, profilerInfo,
                    null, null, null, testMode, mBinderTransactionTrackingEnabled,
                    enableTrackAllocation, isRestrictedBackupMode || !normalMode, app.persistent,
                    new Configuration(getGlobalConfiguration()), app.compat,
                    getCommonServicesLocked(app.isolated),
                    mCoreSettingsObserver.getCoreSettingsLocked(), buildSerial);
        }

        checkTime(startTime, "attachApplicationLocked: immediately after bindApplication");
        updateLruProcessLocked(app, false, null); // 更新LRU进程列表
        checkTime(startTime, "attachApplicationLocked: after updateLruProcessLocked");
        app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis(); // 重置GC时间戳

    } catch (Exception e) {
        // 17. 绑定异常处理:如果在绑定过程中发生任何异常,记录日志并尝试重新启动进程。
        Slog.wtf(TAG, "Exception thrown during bind of " + app, e);
        app.resetPackageList(mProcessStats);
        app.unlinkDeathRecipient(); // 取消死亡通知
        startProcessLocked(app, "bind fail", processName); // 重新启动进程
        return false;
    }

    // 18. 从启动列表中移除:将进程从“正在启动”的列表中移除。
    mPersistentStartingProcesses.remove(app);
    if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG_PROCESSES, "Attach application locked removing on hold: " + app);
    mProcessesOnHold.remove(app);

    boolean badApp = false;
    boolean didSomething = false;

    // 19. 启动Activity:检查是否有顶层可见的Activity需要在这个进程中运行。
    if (normalMode) {
        try {
            if (mStackSupervisor.attachApplicationLocked(app)) { // 尝试启动Activity
                didSomething = true;
            }
        } catch (Exception e) {
            Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
            badApp = true; // 标记为坏应用
        }
    }

    // 20. 启动Service:查找应该在这个进程中运行的任何Service。
    if (!badApp) {
        try {
            didSomething |= mServices.attachApplicationLocked(app, processName); // 启动Service
            checkTime(startTime, "attachApplicationLocked: after mServices.attachApplicationLocked");
        } catch (Exception e) {
            Slog.wtf(TAG, "Exception thrown starting services in " + app, e);
            badApp = true;
        }
    }

    // 21. 处理Broadcast:检查是否有待处理的广播接收器在这个进程中。
    if (!badApp && isPendingBroadcastProcessLocked(pid)) {
        try {
            didSomething |= sendPendingBroadcastsLocked(app); // 发送待处理广播
            checkTime(startTime, "attachApplicationLocked: after sendPendingBroadcastsLocked");
        } catch (Exception e) {
            Slog.wtf(TAG, "Exception thrown dispatching broadcasts in " + app, e);
            badApp = true;
        }
    }

    // 22. 启动Backup Agent:检查下一个备份代理是否在这个进程中。
    if (!badApp && mBackupTarget != null && mBackupTarget.app == app) {
        if (DEBUG_BACKUP) Slog.v(TAG_BACKUP, "New app is backup target, launching agent for " + app);
        notifyPackageUse(mBackupTarget.appInfo.packageName, PackageManager.NOTIFY_PACKAGE_USE_BACKUP);
        try {
            thread.scheduleCreateBackupAgent(mBackupTarget.appInfo, // 创建备份代理
                    compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
                    mBackupTarget.backupMode);
        } catch (Exception e) {
            Slog.wtf(TAG, "Exception thrown creating backup agent in " + app, e);
            badApp = true;
        }
    }

    // 23. 处理坏应用:如果在启动组件过程中发生异常,杀死这个应用进程。
    if (badApp) {
        app.kill("error during init", true);
        handleAppDiedLocked(app, false, true);
        return false;
    }

    // 24. 更新OOM Adj:如果没有启动任何组件,更新进程的OOM调整值。
    if (!didSomething) {
        updateOomAdjLocked(); // 更新进程的OOM优先级
        checkTime(startTime, "attachApplicationLocked: after updateOomAdjLocked");
    }

    return true; // 绑定成功
}

去ActivityThread.java的内部类ApplicationThread去查看一下bindApplication到底干了什么。在这个方法中主要对data进行了封装,然后会调用sendMessage方法将这个data发送。

// final 方法:禁止重写,确保核心逻辑不被修改
// 参数说明:
// - processName: 当前进程名称(如主进程包名或子进程名)
// - appInfo: ApplicationInfo 对象,包含应用清单信息(权限、组件等)
// - providers: ContentProvider 信息列表,用于初始化内容提供器
// - instrumentationName: Instrumentation 组件名(用于测试监控)
// - profilerInfo: 性能分析器配置信息
// - instrumentationArgs: Instrumentation 启动参数
// - instrumentationWatcher: Instrumentation 监控接口
// - instrumentationUiConnection: UI自动化测试连接接口
// - debugMode: 调试模式标志
// - enableBinderTracking: 是否启用Binder调用跟踪
// - trackAllocation: 是否跟踪内存分配
// - isRestrictedBackupMode: 是否处于受限备份模式
// - persistent: 是否为持久性应用(如系统应用)
// - config: 设备配置信息(屏幕方向、字体缩放等)
// - compatInfo: 兼容性信息
// - services: 系统服务缓存映射(如PackageManagerService)
// - coreSettings: 核心系统设置Bundle
// - buildSerial: 设备构建序列号
public final void bindApplication(String processName, ApplicationInfo appInfo,
        List<ProviderInfo> providers, 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) {

    // 初始化系统服务缓存:将预加载的系统服务存入ServiceManager缓存
    // 避免后续每次获取服务都进行Binder调用,提升性能
    if (services != null) {
        ServiceManager.initServiceCache(services);
    }

    // 设置核心系统配置(如调试开关、动画缩放等)
    setCoreSettings(coreSettings);

    // 创建应用绑定数据对象,封装所有启动参数
    AppBindData data = new AppBindData();
    data.processName = processName;          // 进程名
    data.appInfo = appInfo;                  // 应用信息
    data.providers = providers;              // ContentProvider列表
    data.instrumentationName = instrumentationName;  // 测试组件名
    data.instrumentationArgs = instrumentationArgs;  // 测试参数
    data.instrumentationWatcher = instrumentationWatcher;    // 测试监控器
    data.instrumentationUiAutomationConnection = instrumentationUiConnection; // UI自动化连接
    data.debugMode = debugMode;              // 调试模式标志
    data.enableBinderTracking = enableBinderTracking;  // Binder跟踪开关
    data.trackAllocation = trackAllocation;  // 内存分配跟踪开关
    data.restrictedBackupMode = isRestrictedBackupMode; // 备份模式标志
    data.persistent = persistent;            // 是否持久化应用
    data.config = config;                    // 设备配置
    data.compatInfo = compatInfo;            // 兼容性配置
    data.initProfilerInfo = profilerInfo;    // 性能分析器配置
    data.buildSerial = buildSerial;          // 设备序列号

    // 发送BIND_APPLICATION消息到主线程消息队列
    // H是ActivityThread的内部Handler类,处理主线程消息
    // 后续会触发handleBindApplication方法完成应用实际初始化
    sendMessage(H.BIND_APPLICATION, data);
}

在ActivityThread的handleMessage中,当接收到BIND_APPLICATION时,会调用handleBindApplication方法。在这个方法中,首先就是进行一系列的配置,对环境初始化。然后会调用ContextImpl的createAppContext方法创建Application的context,接下来就是通过Instrumentation的callApplicationOnCreate方法来调用application的onCreate方法。

case BIND_APPLICATION:
                    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication");
                    AppBindData data = (AppBindData)msg.obj;
                    handleBindApplication(data);
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                    break;


Instrumentation mInstrumentation;


/**
 * 处理应用绑定数据的核心方法,完成Android应用进程的初始化工作
 * 包括创建Application对象、初始化ContentProvider、设置调试配置等关键操作
 * 注意:此方法运行在主线程(UI线程)
 */
private void handleBindApplication(AppBindData data) {
    // 将UI线程注册为运行时敏感线程(用于性能监控和调试)
    VMRuntime.registerSensitiveThread();
    
    // 如果启用分配跟踪,开启DDM的最近分配记录功能
    if (data.trackAllocation) {
        DdmVmInternal.enableRecentAllocations(true);
    }

    // 记录进程启动时间
    Process.setStartTimes(SystemClock.elapsedRealtime(), SystemClock.uptimeMillis());

    // 保存绑定数据和应用配置
    mBoundApplication = data;
    mConfiguration = new Configuration(data.config);
    mCompatConfiguration = new Configuration(data.config);

    // 初始化性能分析器
    mProfiler = new Profiler();
    if (data.initProfilerInfo != null) {
        mProfiler.profileFile = data.initProfilerInfo.profileFile;
        mProfiler.profileFd = data.initProfilerInfo.profileFd;
        mProfiler.samplingInterval = data.initProfilerInfo.samplingInterval;
        mProfiler.autoStopProfiler = data.initProfilerInfo.autoStopProfiler;
        mProfiler.streamingOutput = data.initProfilerInfo.streamingOutput;
    }

    // 设置进程名称(在DDM和进程列表中显示)
    Process.setArgV0(data.processName);
    android.ddm.DdmHandleAppName.setAppName(data.processName, UserHandle.myUserId());

    // 如果配置了性能分析,立即启动分析
    if (mProfiler.profileFd != null) {
        mProfiler.startProfiling();
    }

    // 针对Honeycomb MR1或更早版本的应用,使用线程池执行器而不是串行执行器
    if (data.appInfo.targetSdkVersion <= android.os.Build.VERSION_CODES.HONEYCOMB_MR1) {
        AsyncTask.setDefaultExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }

    // 根据目标SDK版本更新消息回收检查策略
    Message.updateCheckRecycle(data.appInfo.targetSdkVersion);

    // 重置时区为系统时区,确保进程使用正确的时区设置
    TimeZone.setDefault(null);

    // 设置默认区域列表
    LocaleList.setDefault(data.config.getLocales());

    // 同步更新资源配置
    synchronized (mResourcesManager) {
        // 将最新配置应用到资源管理器
        mResourcesManager.applyConfigurationToResourcesLocked(data.config, data.compatInfo);
        mCurDefaultDisplayDpi = data.config.densityDpi;
        
        // 应用兼容性配置
        applyCompatConfiguration(mCurDefaultDisplayDpi);
    }

    // 获取应用的包信息
    data.info = getPackageInfoNoCheck(data.appInfo, data.compatInfo);

    // 检查应用是否支持屏幕密度兼容模式
    if ((data.appInfo.flags & ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) == 0) {
        mDensityCompatMode = true;
        Bitmap.setDefaultDensity(DisplayMetrics.DENSITY_DEFAULT);
    }
    updateDefaultDensity();

    // 设置时间格式偏好(12小时制或24小时制)
    final String use24HourSetting = mCoreSettings.getString(Settings.System.TIME_12_24);
    Boolean is24Hr = null;
    if (use24HourSetting != null) {
        is24Hr = "24".equals(use24HourSetting) ? Boolean.TRUE : Boolean.FALSE;
    }
    DateFormat.set24HourTimePref(is24Hr);

    // 设置视图调试属性
    View.mDebugViewAttributes =
            mCoreSettings.getInt(Settings.Global.DEBUG_VIEW_ATTRIBUTES, 0) != 0;

    // 对于系统应用,在调试版本中启用StrictMode的磁盘和网络访问日志记录
    if ((data.appInfo.flags & (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0) {
        StrictMode.conditionallyEnableDebugLogging();
    }

    // 针对Honeycomb及以上目标SDK的应用,禁止在主线程进行网络操作
    if (data.appInfo.targetSdkVersion >= Build.VERSION_CODES.HONEYCOMB) {
        StrictMode.enableDeathOnNetwork();
    }

    // 针对N及以上目标SDK的应用,禁止文件Uri暴露
    if (data.appInfo.targetSdkVersion >= Build.VERSION_CODES.N) {
        StrictMode.enableDeathOnFileUriExposure();
    }

    // 修复Build.SERIAL字段的兼容性(针对旧版SDK)
    try {
        Field field = Build.class.getDeclaredField("SERIAL");
        field.setAccessible(true);
        field.set(Build.class, data.buildSerial);
    } catch (NoSuchFieldException | IllegalAccessException e) {
        /* 忽略异常 */
    }

    // 处理调试模式
    if (data.debugMode != ApplicationThreadConstants.DEBUG_OFF) {
        // 更改调试端口
        Debug.changeDebugPort(8100);
        if (data.debugMode == ApplicationThreadConstants.DEBUG_WAIT) {
            Slog.w(TAG, "Application " + data.info.getPackageName()
                  + " is waiting for the debugger on port 8100...");

            // 通知ActivityManager显示等待调试器对话框
            IActivityManager mgr = ActivityManager.getService();
            try {
                mgr.showWaitingForDebugger(mAppThread, true);
            } catch (RemoteException ex) {
                throw ex.rethrowFromSystemServer();
            }

            // 等待调试器连接
            Debug.waitForDebugger();

            // 隐藏等待调试器对话框
            try {
                mgr.showWaitingForDebugger(mAppThread, false);
            } catch (RemoteException ex) {
                throw ex.rethrowFromSystemServer();
            }
        } else {
            Slog.w(TAG, "Application " + data.info.getPackageName()
                  + " can be debugged on port 8100...");
        }
    }

    // 设置应用跟踪允许状态(仅对可调试应用启用)
    boolean isAppDebuggable = (data.appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
    Trace.setAppTracingAllowed(isAppDebuggable);
    if (isAppDebuggable && data.enableBinderTracking) {
        Binder.enableTracing(); // 启用Binder调用跟踪
    }

    // 设置网络代理
    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "Setup proxies");
    final IBinder b = ServiceManager.getService(Context.CONNECTIVITY_SERVICE);
    if (b != null) {
        final IConnectivityManager service = IConnectivityManager.Stub.asInterface(b);
        try {
            final ProxyInfo proxyInfo = service.getProxyForNetwork(null);
            Proxy.setHttpProxySystemProperty(proxyInfo);
        } catch (RemoteException e) {
            Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
            throw e.rethrowFromSystemServer();
        }
    }
    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);

    // 处理Instrumentation信息(影响类加载器,需在应用上下文设置前完成)
    final InstrumentationInfo ii;
    if (data.instrumentationName != null) {
        try {
            ii = new ApplicationPackageManager(null, getPackageManager())
                    .getInstrumentationInfo(data.instrumentationName, 0);
        } catch (PackageManager.NameNotFoundException e) {
            throw new RuntimeException(
                    "Unable to find instrumentation info for: " + data.instrumentationName);
        }

        // 保存Instrumentation相关信息
        mInstrumentationPackageName = ii.packageName;
        mInstrumentationAppDir = ii.sourceDir;
        mInstrumentationSplitAppDirs = ii.splitSourceDirs;
        mInstrumentationLibDir = getInstrumentationLibrary(data.appInfo, ii);
        mInstrumentedAppDir = data.info.getAppDir();
        mInstrumentedSplitAppDirs = data.info.getSplitAppDirs();
        mInstrumentedLibDir = data.info.getLibDir();
    } else {
        ii = null;
    }

    // 创建应用上下文
    final ContextImpl appContext = ContextImpl.createAppContext(this, data.info);
    updateLocaleListFromAppContext(appContext, mResourcesManager.getConfiguration().getLocales());

    // 为非隔离进程设置图形支持
    if (!Process.isIsolated()) {
        setupGraphicsSupport(appContext);
    }

    // 设置Dex加载报告器(用于性能优化)
    if (SystemProperties.getBoolean("dalvik.vm.usejitprofiles", false)) {
        BaseDexClassLoader.setReporter(DexLoadReporter.getInstance());
    }

    // 安装网络安全配置提供者(必须在加载应用代码前完成)
    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "NetworkSecurityConfigProvider.install");
    NetworkSecurityConfigProvider.install(appContext);
    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);

    // 继续初始化Instrumentation
    if (ii != null) {
        final ApplicationInfo instrApp = new ApplicationInfo();
        ii.copyTo(instrApp);
        instrApp.initForUser(UserHandle.myUserId());
        final LoadedApk pi = getPackageInfo(instrApp, data.compatInfo,
                appContext.getClassLoader(), false, true, false);
        final ContextImpl instrContext = ContextImpl.createAppContext(this, pi);

        try {
            // 通过反射创建Instrumentation实例
            final ClassLoader cl = instrContext.getClassLoader();
            mInstrumentation = (Instrumentation)
                cl.loadClass(data.instrumentationName.getClassName()).newInstance();
        } catch (Exception e) {
            throw new RuntimeException(
                "Unable to instantiate instrumentation "
                + data.instrumentationName + ": " + e.toString(), e);
        }

        // 初始化Instrumentation
        final ComponentName component = new ComponentName(ii.packageName, ii.name);
        mInstrumentation.init(this, instrContext, appContext, component,
                data.instrumentationWatcher, data.instrumentationUiAutomationConnection);

        // 如果需要,启动方法跟踪
        if (mProfiler.profileFile != null && !ii.handleProfiling
                && mProfiler.profileFd == null) {
            mProfiler.handlingProfiling = true;
            final File file = new File(mProfiler.profileFile);
            file.getParentFile().mkdirs();
            Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
        }
    } else {
        // 没有指定Instrumentation,创建默认实例
        mInstrumentation = new Instrumentation();
    }

    // 根据应用标志调整堆大小限制
    if ((data.appInfo.flags & ApplicationInfo.FLAG_LARGE_HEAP) != 0) {
        dalvik.system.VMRuntime.getRuntime().clearGrowthLimit(); // 大堆应用,清除增长限制
    } else {
        // 小堆应用,限制增长上限
        dalvik.system.VMRuntime.getRuntime().clampGrowthLimit();
    }

    // 允许在应用和Provider设置期间进行磁盘写入操作
    Application app;
    final StrictMode.ThreadPolicy savedPolicy = StrictMode.allowThreadDiskWrites();
    final StrictMode.ThreadPolicy writesAllowedPolicy = StrictMode.getThreadPolicy();
    try {
        // 创建Application对象(如果是备份/恢复模式,使用受限环境)
        app = data.info.makeApplication(data.restrictedBackupMode, null);
        mInitialApplication = app;

        // 如果不是受限备份模式,安装ContentProvider
        if (!data.restrictedBackupMode) {
            if (!ArrayUtils.isEmpty(data.providers)) {
                installContentProviders(app, data.providers);
                // 对于包含ContentProvider的进程,延迟启用JIT编译
                mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10*1000);
            }
        }

        // 调用Instrumentation的onCreate方法(在Provider安装后执行)
        try {
            mInstrumentation.onCreate(data.instrumentationArgs);
        } catch (Exception e) {
            throw new RuntimeException(
                "Exception thrown in onCreate() of "
                + data.instrumentationName + ": " + e.toString(), e);
        }
        
        // 调用Application的onCreate方法
        try {
            mInstrumentation.callApplicationOnCreate(app);
        } catch (Exception e) {
            if (!mInstrumentation.onException(app, e)) {
                throw new RuntimeException(
                  "Unable to create application " + app.getClass().getName()
                  + ": " + e.toString(), e);
            }
        }
    } finally {
        // 恢复StrictMode策略(针对旧版SDK或未修改策略的情况)
        if (data.appInfo.targetSdkVersion <= Build.VERSION_CODES.O
                || StrictMode.getThreadPolicy().equals(writesAllowedPolicy)) {
            StrictMode.setThreadPolicy(savedPolicy);
        }
    }

    // 预加载字体资源
    FontsContract.setApplicationContextForResources(appContext);
    try {
        final ApplicationInfo info =
                getPackageManager().getApplicationInfo(
                        data.appInfo.packageName,
                        PackageManager.GET_META_DATA /*flags*/,
                        UserHandle.myUserId());
        if (info.metaData != null) {
            final int preloadedFontsResource = info.metaData.getInt(
                    ApplicationInfo.METADATA_PRELOADED_FONTS, 0);
            if (preloadedFontsResource != 0) {
                data.info.getResources().preloadFonts(preloadedFontsResource);
            }
        }
    } catch (RemoteException e) {
        throw e.rethrowFromSystemServer();
    }
}


/**
     * Perform calling of the application's {@link Application#onCreate}
     * method.  The default implementation simply calls through to that method.
     *
     * <p>Note: This method will be called immediately after {@link #onCreate(Bundle)}.
     * Often instrumentation tests start their test thread in onCreate(); you
     * need to be careful of races between these.  (Well between it and
     * everything else, but let's start here.)
     *
     * @param app The application being created.
     */
    public void callApplicationOnCreate(Application app) {
        app.onCreate();
    }

再回到AMS的attachedApplicationLocked方法,其中normalMode为true,那么就会去调用ActivityStackSupervisor.java中的attachApplicationLocked方法。

// See if the top visible activity is waiting to run in this process...
        
ProcessRecord app;
if (normalMode) {
            try {
                if (mStackSupervisor.attachApplicationLocked(app)) {
                    didSomething = true;
                }
            } catch (Exception e) {
                Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
                badApp = true;
            }
        }

那么分析一下attachApplicationLocked方法。这个方法十分重要,它会遍历所有的Activity堆栈,然后获取堆栈中所有可见的Activity,如果该Activity是待运行的状态并且条件都满足,那么就会调用realStartActivityLocked方法去尝试真正启动Activity。

/**
 * 将已启动的应用进程与待运行的Activity进行绑定并启动
 * 这个方法在AMS(ActivityManagerService)中调用,用于将新创建的应用进程与需要在该进程中运行的Activity关联起来
 * 
 * @param app 已创建的应用进程记录(ProcessRecord)
 * @return boolean 表示是否成功启动了任何Activity
 * @throws RemoteException 远程调用异常
 */
boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
    final String processName = app.processName;
    boolean didSomething = false; // 标记是否成功启动了Activity
    
    // 遍历所有显示设备(多显示器支持)
    for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
        ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
        
        // 遍历当前显示设备上的所有Activity堆栈
        for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
            final ActivityStack stack = stacks.get(stackNdx);
            
            // 只处理获得焦点的堆栈(前台堆栈)
            if (!isFocusedStack(stack)) {
                continue;
            }
            
            // 获取堆栈中所有正在运行且可见的Activity
            stack.getAllRunningVisibleActivitiesLocked(mTmpActivityList);
            final ActivityRecord top = stack.topRunningActivityLocked(); // 获取栈顶Activity
            
            // 遍历所有可见Activity
            final int size = mTmpActivityList.size();
            for (int i = 0; i < size; i++) {
                final ActivityRecord activity = mTmpActivityList.get(i);
                
                // 检查Activity是否满足启动条件:
                // 1. Activity尚未绑定到应用进程 (activity.app == null)
                // 2. UID匹配 (app.uid == activity.info.applicationInfo.uid)
                // 3. 进程名匹配 (processName.equals(activity.processName))
                if (activity.app == null && app.uid == activity.info.applicationInfo.uid
                        && processName.equals(activity.processName)) {
                    try {
                        // 尝试真正启动Activity
                        // 参数说明:
                        // - activity: 要启动的Activity记录
                        // - app: 目标应用进程
                        // - top == activity: 如果是栈顶Activity则需要resume
                        // - true: 检查配置变更
                        if (realStartActivityLocked(activity, app,
                                top == activity /* andResume */, true /* checkConfig */)) {
                            didSomething = true; // 标记已成功启动Activity
                        }
                    } catch (RemoteException e) {
                        Slog.w(TAG, "Exception in new application when starting activity "
                                + top.intent.getComponent().flattenToShortString(), e);
                        throw e; // 重新抛出异常
                    }
                }
            }
        }
    }
    
    // 如果没有启动任何Activity,确保当前可见的Activity正确显示
    if (!didSomething) {
        ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
    }
    
    return didSomething; // 返回是否成功启动了Activity
}

那么再来看看这个realStartActivityLocked方法。首先进行一系列的前置检查,然后进行启动前的准备,接下来就是核心步骤通过Binder调用app.thread.scheduleLaunchActivity()通知应用进程启动Activity,最后就是更新Activity的状态。

/**
 * 真正启动Activity的核心方法,处理Activity启动的详细逻辑
 * 这个方法在AMS中调用,负责将Activity绑定到应用进程并执行启动流程
 * 
 * @param r 要启动的Activity记录(ActivityRecord)
 * @param app 目标应用进程(ProcessRecord)
 * @param andResume 是否在启动后立即执行resume操作
 * @param checkConfig 是否检查配置变更
 * @return boolean 表示是否成功启动了Activity
 * @throws RemoteException 远程调用异常
 */
final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
        boolean andResume, boolean checkConfig) throws RemoteException {

    // 检查是否有Activity正在暂停中,如果有则等待暂停完成
    if (!allPausedActivitiesComplete()) {
        if (DEBUG_SWITCH || DEBUG_PAUSE || DEBUG_STATES) Slog.v(TAG_PAUSE,
                "realStartActivityLocked: Skipping start of r=" + r
                + " some activities pausing...");
        return false; // 有Activity正在暂停,暂不启动新Activity
    }

    final TaskRecord task = r.getTask(); // 获取Activity所在的任务
    final ActivityStack stack = task.getStack(); // 获取Activity所在的堆栈

    beginDeferResume(); // 开始延迟resume操作

    try {
        // 启动屏幕冻结(防止启动过程中的视觉闪烁)
        r.startFreezingScreenLocked(app, 0);

        // 启动启动耗时检测(收集慢启动应用的信息)
        r.startLaunchTickingLocked();

        // 将Activity绑定到应用进程
        r.app = app;

        // 如果设备处于锁屏状态,通知Activity可见性未知
        if (mKeyguardController.isKeyguardLocked()) {
            r.notifyUnknownVisibilityLaunched();
        }

        // 更新屏幕方向配置
        if (checkConfig) {
            final int displayId = r.getDisplayId();
            final Configuration config = mWindowManager.updateOrientationFromAppTokens(
                    getDisplayOverrideConfiguration(displayId),
                    r.mayFreezeScreenLocked(app) ? r.appToken : null, displayId);
            // 更新显示配置,延迟resume操作
            mService.updateDisplayOverrideConfigurationLocked(config, r, true /* deferResume */,
                    displayId);
        }

        // 检查Keyguard状态并设置Activity可见性
        if (r.getStack().checkKeyguardVisibility(r, true /* shouldBeVisible */,
                true /* isTop */)) {
            r.setVisibility(true); // 允许可见时才设置可见性
        }

        // 验证用户ID和应用UID的一致性
        final int applicationInfoUid =
                (r.info.applicationInfo != null) ? r.info.applicationInfo.uid : -1;
        if ((r.userId != app.userId) || (r.appInfo.uid != applicationInfoUid)) {
            Slog.wtf(TAG,
                    "User ID for activity changing for " + r
                            + " appInfo.uid=" + r.appInfo.uid
                            + " info.ai.uid=" + applicationInfoUid
                            + " old=" + r.app + " new=" + app);
        }

        // 重置等待杀死状态,增加启动计数和记录最后启动时间
        app.waitingToKill = null;
        r.launchCount++;
        r.lastLaunchTime = SystemClock.uptimeMillis();

        if (DEBUG_ALL) Slog.v(TAG, "Launching: " + r);

        // 将Activity添加到进程的Activity列表中
        int idx = app.activities.indexOf(r);
        if (idx < 0) {
            app.activities.add(r);
        }
        
        // 更新进程LRU列表和OOM调整
        mService.updateLruProcessLocked(app, true, null);
        mService.updateOomAdjLocked();

        // 检查并设置锁屏任务模式
        if (task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE ||
                task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE_PRIV) {
            setLockTaskModeLocked(task, LOCK_TASK_MODE_LOCKED, "mLockTaskAuth==LAUNCHABLE",
                    false);
        }

        try {
            // 检查应用线程是否存在
            if (app.thread == null) {
                throw new RemoteException();
            }
            
            // 准备结果数据和新的Intent
            List<ResultInfo> results = null;
            List<ReferrerIntent> newIntents = null;
            if (andResume) {
                // 只有在Activity不会立即暂停的情况下才需要传递结果和Intent
                results = r.results;
                newIntents = r.newIntents;
            }
            
            if (DEBUG_SWITCH) Slog.v(TAG_SWITCH,
                    "Launching: " + r + " icicle=" + r.icicle + " with results=" + results
                            + " newIntents=" + newIntents + " andResume=" + andResume);
            
            // 记录Activity重启事件
            EventLog.writeEvent(EventLogTags.AM_RESTART_ACTIVITY, r.userId,
                    System.identityHashCode(r), task.taskId, r.shortComponentName);
            
            // 如果是Home Activity,设置Home进程
            if (r.isHomeActivity()) {
                mService.mHomeProcess = task.mActivities.get(0).app;
            }
            
            // 通知包使用情况
            mService.notifyPackageUse(r.intent.getComponent().getPackageName(),
                    PackageManager.NOTIFY_PACKAGE_USE_ACTIVITY);
            
            // 重置Activity状态
            r.sleeping = false;
            r.forceNewConfig = false;
            
            // 显示兼容性相关对话框
            mService.showUnsupportedZoomDialogIfNeededLocked(r);
            mService.showAskCompatModeDialogLocked(r);
            
            // 获取兼容性信息
            r.compat = mService.compatibilityInfoForPackageLocked(r.info.applicationInfo);
            
            // 设置性能分析器信息
            ProfilerInfo profilerInfo = null;
            if (mService.mProfileApp != null && mService.mProfileApp.equals(app.processName)) {
                if (mService.mProfileProc == null || mService.mProfileProc == app) {
                    mService.mProfileProc = app;
                    ProfilerInfo profilerInfoSvc = mService.mProfilerInfo;
                    if (profilerInfoSvc != null && profilerInfoSvc.profileFile != null) {
                        if (profilerInfoSvc.profileFd != null) {
                            try {
                                profilerInfoSvc.profileFd = profilerInfoSvc.profileFd.dup();
                            } catch (IOException e) {
                                profilerInfoSvc.closeFd();
                            }
                        }
                        profilerInfo = new ProfilerInfo(profilerInfoSvc);
                    }
                }
            }

            // 更新进程状态
            app.hasShownUi = true;
            app.pendingUiClean = true;
            app.forceProcessStateUpTo(mService.mTopProcessState);
            
            // 创建合并的配置信息
            final MergedConfiguration mergedConfiguration = new MergedConfiguration(
                    mService.getGlobalConfiguration(), r.getMergedOverrideConfiguration());
            r.setLastReportedConfiguration(mergedConfiguration);

            // 检查Intent数据是否过大
            logIfTransactionTooLarge(r.intent, r.icicle);
            
            // 关键调用:通过Binder通知应用进程启动Activity
            app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
                    System.identityHashCode(r), r.info,
                    mergedConfiguration.getGlobalConfiguration(),
                    mergedConfiguration.getOverrideConfiguration(), r.compat,
                    r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,
                    r.persistentState, results, newIntents, !andResume,
                    mService.isNextTransitionForward(), profilerInfo);

            // 处理重量级进程
            if ((app.info.privateFlags & ApplicationInfo.PRIVATE_FLAG_CANT_SAVE_STATE) != 0) {
                if (app.processName.equals(app.info.packageName)) {
                    if (mService.mHeavyWeightProcess != null
                            && mService.mHeavyWeightProcess != app) {
                        Slog.w(TAG, "Starting new heavy weight process " + app
                                + " when already running "
                                + mService.mHeavyWeightProcess);
                    }
                    mService.mHeavyWeightProcess = app;
                    // 发送重量级进程通知
                    Message msg = mService.mHandler.obtainMessage(
                            ActivityManagerService.POST_HEAVY_NOTIFICATION_MSG);
                    msg.obj = r;
                    mService.mHandler.sendMessage(msg);
                }
            }

        } catch (RemoteException e) {
            if (r.launchFailed) {
                // 第二次启动失败,放弃并结束Activity
                Slog.e(TAG, "Second failure launching "
                        + r.intent.getComponent().flattenToShortString()
                        + ", giving up", e);
                mService.appDiedLocked(app);
                stack.requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
                        "2nd-crash", false);
                return false;
            }

            // 第一次启动失败,移除Activity记录并重新抛出异常
            r.launchFailed = true;
            app.activities.remove(r);
            throw e;
        }
    } finally {
        endDeferResume(); // 结束延迟resume操作
    }

    // 重置启动失败标志
    r.launchFailed = false;
    
    // 更新LRU列表
    if (stack.updateLRUListLocked(r)) {
        Slog.w(TAG, "Activity " + r + " being launched, but already in LRU list");
    }

    // 如果需要且准备好resume,执行最小化resume操作
    if (andResume && readyToResume()) {
        stack.minimalResumeActivityLocked(r);
    } else {
        // 否则将Activity状态设置为PAUSED
        if (DEBUG_STATES) Slog.v(TAG_STATES,
                "Moving to PAUSED: " + r + " (starting in paused state)");
        r.state = PAUSED;
    }

    // 如果是焦点堆栈,启动设置Activity(如果需要)
    if (isFocusedStack(stack)) {
        mService.startSetupActivityLocked();
    }

    // 更新与服务连接相关的Activity信息
    if (r.app != null) {
        mService.mServices.updateServiceConnectionActivitiesLocked(r.app);
    }

    return true; // 启动成功
}

那么再回到ActivityThread.java中分析一下scheduleLaunchActivity方法。同样是对data进行配置,然后通过sendMesage方法进行发送。

// we use token to identify this activity without having to send the
        // activity itself back to the activity manager. (matters more with ipc)
        @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);

            sendMessage(H.LAUNCH_ACTIVITY, r);
        }

在ActivityThread的handleMessage中,接收到LAUNCH_ACTIVITY消息会调用handleLunchActivity方法。在这个方法中首先会进行配置,然后调用核心方法performLunchActivity。接下来会调用handleResumeActivity来处理Activity的onResumed生命周期。

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;


/**
 * 处理Activity启动的核心方法,运行在应用进程的主线程中
 * 这个方法负责创建Activity实例、处理配置变更、执行生命周期回调
 * 
 * @param r Activity客户端记录,包含启动所需的所有信息
 * @param customIntent 自定义的Intent(可能为null)
 * @param reason 启动原因描述,用于调试和日志记录
 */
private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
    // 取消计划中的GC操作,因为应用即将回到前台变为活跃状态
    unscheduleGcIdler();
    mSomeActivitiesChanged = true; // 标记有Activity状态发生变化

    // 设置性能分析器(如果提供了性能分析信息)
    if (r.profilerInfo != null) {
        mProfiler.setProfiler(r.profilerInfo);
        mProfiler.startProfiling(); // 开始性能分析
    }

    // 确保使用最新的配置信息
    handleConfigurationChanged(null, null);

    if (localLOGV) Slog.v(TAG, "Handling launch of " + r);

    // 在创建Activity之前进行初始化
    if (!ThreadedRenderer.sRendererDisabled) {
        GraphicsEnvironment.earlyInitEGL(); // 早期初始化EGL图形环境
    }
    WindowManagerGlobal.initialize(); // 初始化窗口管理器

    // 核心方法:执行Activity的启动,创建Activity实例并调用onCreate等生命周期方法
    Activity a = performLaunchActivity(r, customIntent);

    if (a != null) { // Activity成功创建
        // 保存当前配置信息
        r.createdConfig = new Configuration(mConfiguration);
        // 报告尺寸配置信息
        reportSizeConfigurations(r);
        Bundle oldState = r.state; // 保存旧状态
        
        // 处理Activity的resume生命周期
        handleResumeActivity(r.token, false, r.isForward,
                !r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);

        // 如果Activity没有结束但需要以暂停状态启动
        if (!r.activity.mFinished && r.startsNotResumed) {
            /*
             * Activity管理器希望此Activity一开始处于暂停状态,因为它需要可见但不在前台。
             * 我们通过正常启动流程实现这一点(因为Activity期望在第一次运行时经过onResume(),
             * 然后才显示其窗口),然后将其暂停。
             * 但是,在这种情况下,我们不需要完整的暂停周期(如冻结等),因为Activity管理器
             * 假定它可以保持当前状态。
             */
            performPauseActivityIfNeeded(r, reason);

            /*
             * 我们需要保留原始状态,以防需要再次创建Activity。
             * 但仅对Honeycomb之前的应用这样做,这些应用在暂停时总是保存其状态,
             * 因此我们不能让它们在从暂停状态重新启动时保存状态。
             * 对于HC及更高版本,我们希望(并且可以)让状态作为停止Activity的正常部分保存。
             */
            if (r.isPreHoneycomb()) {
                r.state = oldState; // 恢复旧状态
            }
        }
    } else { // Activity创建失败
        // 出现错误时,通知Activity管理器停止我们
        try {
            ActivityManager.getService()
                .finishActivity(r.token, Activity.RESULT_CANCELED, null,
                        Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
        } catch (RemoteException ex) {
            throw ex.rethrowFromSystemServer();
        }
    }
}

那么再来分析一下performLunchActivity方法,首先会对intent进行解析,然后调用createBaseContextForActivity来为Activity创建context,接下来就是通过类加载器和反射创建Activity实例并且将这个Activity添加到Application中,并通过callActivityOnCreate方法调用其onCreate方法。然后就是调用onStart方法。

/**
 * 执行Activity启动的核心方法,负责创建Activity实例并完成初始化
 * 这个方法在应用进程的主线程中执行,是Activity生命周期开始的起点
 * 
 * @param r Activity客户端记录,包含启动所需的所有信息
 * @param customIntent 自定义的Intent(可能为null)
 * @return Activity 成功创建的Activity实例,如果创建失败则返回null
 */
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    // 获取Activity信息
    ActivityInfo aInfo = r.activityInfo;
    
    // 确保包信息已加载
    if (r.packageInfo == null) {
        r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
                Context.CONTEXT_INCLUDE_CODE);
    }

    // 解析Activity组件名称
    ComponentName component = r.intent.getComponent();
    if (component == null) {
        component = r.intent.resolveActivity(
            mInitialApplication.getPackageManager());
        r.intent.setComponent(component);
    }

    // 处理目标Activity重定向(如alias活动)
    if (r.activityInfo.targetActivity != null) {
        component = new ComponentName(r.activityInfo.packageName,
                r.activityInfo.targetActivity);
    }

    // 为Activity创建基础上下文环境
    ContextImpl appContext = createBaseContextForActivity(r);
    Activity activity = null;
    try {
        // 通过类加载器和反射创建Activity实例
        java.lang.ClassLoader cl = appContext.getClassLoader();
        activity = mInstrumentation.newActivity(
                cl, component.getClassName(), r.intent);
        
        // 增加StrictMode期望的Activity计数
        StrictMode.incrementExpectedActivityCount(activity.getClass());
        
        // 设置Intent的类加载器
        r.intent.setExtrasClassLoader(cl);
        r.intent.prepareToEnterProcess();
        
        // 设置状态Bundle的类加载器
        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 {
        // 获取或创建Application实例
        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) {
            // 加载Activity标题
            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);
            
            /**
             * 关键调用:将Activity附加到上下文
             * 这个方法完成Activity的初始化工作,包括:
             * - 设置上下文和资源
             * - 关联Window和WindowManager
             * - 设置主题和配置
             * - 初始化其他关键组件
             */
            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);

            // 如果提供了自定义Intent,替换原始Intent
            if (customIntent != null) {
                activity.mIntent = customIntent;
            }
            
            // 清理非配置实例
            r.lastNonConfigurationInstances = null;
            
            // 检查网络访问权限并阻塞如果需要
            checkAndBlockForNetworkAccess();
            
            // 重置启动标志
            activity.mStartedActivity = false;
            
            // 设置Activity主题
            int theme = r.activityInfo.getThemeResource();
            if (theme != 0) {
                activity.setTheme(theme);
            }

            /**
             * 调用Activity的onCreate方法
             * 这是Activity生命周期的第一个回调
             */
            activity.mCalled = false; // 重置调用标志
            if (r.isPersistable()) {
                // 持久化Activity调用带有持久化状态的onCreate
                mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
            } else {
                // 普通Activity调用onCreate
                mInstrumentation.callActivityOnCreate(activity, r.state);
            }
            
            // 检查是否调用了super.onCreate()
            if (!activity.mCalled) {
                throw new SuperNotCalledException(
                    "Activity " + r.intent.getComponent().toShortString() +
                    " did not call through to super.onCreate()");
            }
            
            // 更新记录信息
            r.activity = activity;
            r.stopped = true;
            
            // 调用onStart方法(如果Activity尚未结束)
            if (!r.activity.mFinished) {
                activity.performStart();
                r.stopped = false;
            }
            
            // 恢复实例状态(如果Activity尚未结束且有保存的状态)
            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);
                }
            }
            
            // 调用onPostCreate方法(如果Activity尚未结束)
            if (!r.activity.mFinished) {
                activity.mCalled = false;
                if (r.isPersistable()) {
                    mInstrumentation.callActivityOnPostCreate(activity, r.state,
                            r.persistentState);
                } else {
                    mInstrumentation.callActivityOnPostCreate(activity, r.state);
                }
                
                // 检查是否调用了super.onPostCreate()
                if (!activity.mCalled) {
                    throw new SuperNotCalledException(
                        "Activity " + r.intent.getComponent().toShortString() +
                        " did not call through to super.onPostCreate()");
                }
            }
        }
        
        // 标记Activity为暂停状态
        r.paused = true;
        
        // 将Activity记录添加到管理映射中
        mActivities.put(r.token, r);

    } catch (SuperNotCalledException e) {
        // 直接重新抛出SuperNotCalledException
        throw e;

    } catch (Exception e) {
        // 处理其他异常
        if (!mInstrumentation.onException(activity, e)) {
            throw new RuntimeException(
                "Unable to start activity " + component
                + ": " + e.toString(), e);
        }
    }

    return activity;
}

最后分析一下handleResumedActivity方法。这个方法主要是处理Activity resume的核心方法,负责将Activity带到前台并使其可见。首先会进行一系列配置,然后就是调用performResumeActivity方法,调用Activity的onResumed方法。然后判断Activity是否可见,如果不可见那么就添加到窗口并且使得该Activity可见。

/**
 * 处理Activity resume的核心方法,负责将Activity带到前台并使其可见
 * 这个方法在应用进程的主线程中执行,处理Activity从PAUSED到RESUMED状态的转换
 * 
 * @param token Activity的标识token
 * @param clearHide 是否清除隐藏标志
 * @param isForward 是否向前导航(影响软键盘行为)
 * @param reallyResume 是否真正执行resume(通知AMS)
 * @param seq 生命周期序列号,用于检查顺序
 * @param reason 执行原因描述,用于调试
 */
final void handleResumeActivity(IBinder token,
        boolean clearHide, boolean isForward, boolean reallyResume, int seq, String reason) {
    // 获取Activity客户端记录
    ActivityClientRecord r = mActivities.get(token);
    
    // 检查并更新生命周期序列号,确保操作顺序正确
    if (!checkAndUpdateLifecycleSeq(seq, r, "resumeActivity")) {
        return; // 序列号不匹配,直接返回
    }

    // 取消计划中的GC操作,因为应用即将回到前台变为活跃状态
    unscheduleGcIdler();
    mSomeActivitiesChanged = true; // 标记有Activity状态发生变化

    // 执行Activity的resume操作,这会调用Activity的onResume方法
    r = performResumeActivity(token, clearHide, reason);

    if (r != null) { // Activity成功resume
        final Activity a = r.activity;

        if (localLOGV) Slog.v(
            TAG, "Resume " + r + " started activity: " +
            a.mStartedActivity + ", hideForNow: " + r.hideForNow
            + ", finished: " + a.mFinished);

        // 设置向前导航位(影响软输入模式)
        final int forwardBit = isForward ?
                WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;

        // 判断Activity是否应该可见
        boolean willBeVisible = !a.mStartedActivity;
        if (!willBeVisible) {
            // 检查Activity是否会被ActivityManager视为可见
            try {
                willBeVisible = ActivityManager.getService().willActivityBeVisible(
                        a.getActivityToken());
            } catch (RemoteException e) {
                throw e.rethrowFromSystemServer();
            }
        }
        
        // 如果窗口尚未添加到窗口管理器,且Activity未结束且应该可见
        if (r.window == null && !a.mFinished && willBeVisible) {
            r.window = r.activity.getWindow();
            View decor = r.window.getDecorView();
            decor.setVisibility(View.INVISIBLE); // 初始设置为不可见
            
            ViewManager wm = a.getWindowManager();
            WindowManager.LayoutParams l = r.window.getAttributes();
            a.mDecor = decor;
            l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
            l.softInputMode |= forwardBit; // 设置软输入模式
            
            if (r.mPreserveWindow) {
                // 保留窗口的情况(如配置变更)
                a.mWindowAdded = true;
                r.mPreserveWindow = false;
                // 通知ViewRootImpl回调可能已更改
                ViewRootImpl impl = decor.getViewRootImpl();
                if (impl != null) {
                    impl.notifyChildRebuilt();
                }
            }
            
            // 如果客户端要求可见,添加窗口或更新属性
            if (a.mVisibleFromClient) {
                if (!a.mWindowAdded) {
                    a.mWindowAdded = true;
                    wm.addView(decor, l); // 添加窗口到窗口管理器
                } else {
                    // 窗口已添加,更新属性
                    a.onWindowAttributesChanged(l);
                }
            }

        // 如果窗口已添加,但在resume期间启动了另一个Activity,则暂时不使窗口可见
        } else if (!willBeVisible) {
            if (localLOGV) Slog.v(TAG, "Launch " + r + " mStartedActivity set");
            r.hideForNow = true; // 设置隐藏标志
        }

        // 清理任何挂起的窗口移除操作
        cleanUpPendingRemoveWindows(r, false /* force */);

        // 如果Activity未结束、应该可见、有装饰视图且不隐藏,则使其可见
        if (!r.activity.mFinished && willBeVisible
                && r.activity.mDecor != null && !r.hideForNow) {
            // 处理新的配置变更
            if (r.newConfig != null) {
                performConfigurationChangedForActivity(r, r.newConfig);
                if (DEBUG_CONFIGURATION) Slog.v(TAG, "Resuming activity "
                        + r.activityInfo.name + " with newConfig " + r.activity.mCurrentConfig);
                r.newConfig = null;
            }
            
            if (localLOGV) Slog.v(TAG, "Resuming " + r + " with isForward=" + isForward);
            
            // 更新软输入模式
            WindowManager.LayoutParams l = r.window.getAttributes();
            if ((l.softInputMode & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) != forwardBit) {
                l.softInputMode = (l.softInputMode & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)) | forwardBit;
                if (r.activity.mVisibleFromClient) {
                    ViewManager wm = a.getWindowManager();
                    View decor = r.window.getDecorView();
                    wm.updateViewLayout(decor, l); // 更新视图布局
                }
            }

            // 标记Activity为服务器端可见
            r.activity.mVisibleFromServer = true;
            mNumVisibleActivities++; // 增加可见Activity计数
            
            // 如果客户端要求可见,使Activity真正可见
            if (r.activity.mVisibleFromClient) {
                r.activity.makeVisible();
            }
        }

        // 如果不是仅本地请求,安排空闲处理
        if (!r.onlyLocalRequest) {
            r.nextIdle = mNewActivities;
            mNewActivities = r;
            if (localLOGV) Slog.v(TAG, "Scheduling idle handler for " + r);
            Looper.myQueue().addIdleHandler(new Idler()); // 添加空闲处理器
        }
        r.onlyLocalRequest = false;

        // 通知ActivityManagerService我们已经resumed
        if (reallyResume) {
            try {
                ActivityManager.getService().activityResumed(token);
            } catch (RemoteException ex) {
                throw ex.rethrowFromSystemServer();
            }
        }

    } else { // Activity resume失败
        // 如果resume时抛出异常,结束此Activity
        try {
            ActivityManager.getService()
                .finishActivity(token, Activity.RESULT_CANCELED, null,
                        Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
        } catch (RemoteException ex) {
            throw ex.rethrowFromSystemServer();
        }
    }
}

至此,我们已经分析从SystemServer启动以后,启动AMS的systemReady方法,再到App进程的创建,Application的创建和执行onCreate生命周期方法。还有Activity的创建,并执行相应的onCreate方法和onResumed方法并且展示在用户面前。

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐