SystemServer 启动流程

SystemServer由zygote启动,后续研究zygote时再看如何启动的。

本文从SystemServer的main函数开始研究。

/*** SystemServer.java ***/
public static void main(String[] args) {
    new SystemServer().run();
}

public SystemServer() {
    mFactoryTestMode = FactoryTest.getMode();
}
SystemServer的初始化,只是简单的检查了一下是否处于工厂测试模式。
关于工厂测试模式请参考“Android FactoryTest框架”一文。

创建了SystemServer对象后,直接调用它的run函数。
/*** SystemServer.java ***/
private void run() {
    //如果系统时间早于1970,则设置系统时间为1970年。
    if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
        Slog.w(TAG, "System clock is before 1970; setting to 1970.");
        SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
    }

    //设置区域,语言等选项
    if (!SystemProperties.get("persist.sys.language").isEmpty()) {
        final String languageTag = Locale.getDefault().toLanguageTag();

        SystemProperties.set("persist.sys.locale", languageTag);
        SystemProperties.set("persist.sys.language", "");
        SystemProperties.set("persist.sys.country", "");
        SystemProperties.set("persist.sys.localevar", "");
    }

    // Here we go!
    Slog.i(TAG, "Entered the Android system server!");
    EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN, SystemClock.uptimeMillis());

    //虚拟机使用 dvm 或 art。参考“Android ART运行时无缝替换Dalvik虚拟机的过程分析”一文
    SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());

    //启动采样分析,分析性能时使用
    if (SamplingProfilerIntegration.isEnabled()) {
        SamplingProfilerIntegration.start();
        mProfilerSnapshotTimer = new Timer();
        mProfilerSnapshotTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                SamplingProfilerIntegration.writeSnapshot("system_server", null);
            }
        }, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL);
    }

    //清除vm内存增长上限,由于启动过程需要较多的虚拟机内存空间
    VMRuntime.getRuntime().clearGrowthLimit();

    //设置堆栈利用率。GC后会重新计算堆栈空间大小。
    VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);

    //针对部分设备依赖于运行时就产生指纹信息,因此需要在开机完成前已经定义
    Build.ensureFingerprintProperty();

    //访问环境变量前,需要明确地指定用户
    Environment.setUserRequired(true);

    //确保当前系统进程的binder调用,总是运行在前台优先级(foreground priority)
    BinderInternal.disableBackgroundScheduling(true);

    android.os.Process.setThreadPriority(
            android.os.Process.THREAD_PRIORITY_FOREGROUND);
    android.os.Process.setCanSelfBackground(false);
    Looper.prepareMainLooper();

    // Initialize native services.
    //frameworks/base/services/Android.mk
    //LOCAL_MODULE:= libandroid_servers
    System.loadLibrary("android_servers");

    //检测上次关机过程是否失败,该方法可能不会返回
    performPendingShutdown();

    //初始化系统上下文
    createSystemContext();

    //创建系统服务管理
    mSystemServiceManager = new SystemServiceManager(mSystemContext);
    LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);

    //启动各种系统服务
    try {
        startBootstrapServices(); //启动引导服务
        startCoreServices();      //启动核心服务
        startOtherServices();     //启动其他服务
    } catch (Throwable ex) {
        Slog.e("System", "******************************************");
        Slog.e("System", "************ Failure starting system services", ex);
        throw ex;
    }

    //用于debug版本,将log事件不断循环地输出到dropbox(用于分析)
    if (StrictMode.conditionallyEnableDebugLogging()) {
        Slog.i(TAG, "Enabled StrictMode for system server main thread.");
    }

    //一直循环执行
    Looper.loop();
    throw new RuntimeException("Main thread loop unexpectedly exited");
}
去掉一些初始化设置,简化后的run函数如下:
/*** SystemServer.java ***/
private void run() {
    Looper.prepareMainLooper();

    //初始化系统上下文
    createSystemContext();

    //创建系统服务管理
    mSystemServiceManager = new SystemServiceManager(mSystemContext);
    LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);

    //启动各种系统服务
    try {
        startBootstrapServices(); //启动引导服务
        startCoreServices();      //启动核心服务
        startOtherServices();     //启动其他服务
    } catch (Throwable ex) {
        Slog.e("System", "******************************************");
        Slog.e("System", "************ Failure starting system services", ex);
        throw ex;
    }

    Looper.loop();
    throw new RuntimeException("Main thread loop unexpectedly exited");
}
简单来看,SystemServer启动时主要做了以下几件事:
1. 初始化系统上下文
2. 创建系统服务管理
3. 启动各种系统服务

1. 初始化系统上下文

/*** SystemServer.java ***/
private void createSystemContext() {
    ActivityThread activityThread = ActivityThread.systemMain();
    mSystemContext = activityThread.getSystemContext();
    mSystemContext.setTheme(android.R.style.Theme_DeviceDefault_Light_DarkActionBar);
}
1.创建ActivityThread
2.获取系统上下文
3.设置主题

1.1 创建ActivityThread

/*** ActivityThread.java ***/
public static ActivityThread systemMain() {
    //对于低内存的设备,禁用硬件加速
    if (!ActivityManager.isHighEndGfx()) {
        HardwareRenderer.disable(true);
    } else {
        HardwareRenderer.enableForegroundTrimming();
    }
    ActivityThread thread = new ActivityThread();
    thread.attach(true);
    return thread;
}

ActivityThread() {
    //使用单例模式获得一个ResourcesManager实例
    mResourcesManager = ResourcesManager.getInstance();
}
/*** ActivityThread.java ***/
private void attach(boolean system) {
    sCurrentActivityThread = this;
    mSystemThread = system;
    if (!system) {
        ...
    } else {
        //设置SystemServer进程在DDMS中显示的名字为"system_process"
        //如不设置,则显示"?",无法调试该进程。app一般显示包名。
        android.ddm.DdmHandleAppName.setAppName("system_process",
                UserHandle.myUserId());
        try {
            mInstrumentation = new Instrumentation();
            //首先通过getSystemContext()创建系统上下文,然后创建应用上下文
            ContextImpl context = ContextImpl.createAppContext(
                    this, getSystemContext().mPackageInfo);
            //创建Application
            mInitialApplication = context.mPackageInfo.makeApplication(true, null);
            //调用Application的onCreate()
            mInitialApplication.onCreate();
        } catch (Exception e) {
            throw new RuntimeException(
                    "Unable to instantiate Application():" + e.toString(), e);
        }
    }

    // add dropbox logging to libcore
    DropBox.setReporter(new DropBoxReporter());

    ViewRootImpl.addConfigCallback(new ComponentCallbacks2() {
        @Override
        public void onConfigurationChanged(Configuration newConfig) {
            synchronized (mResourcesManager) {
                // We need to apply this change to the resources
                // immediately, because upon returning the view
                // hierarchy will be informed about it.
                if (mResourcesManager.applyConfigurationToResourcesLocked(newConfig, null)) {
                    // This actually changed the resources!  Tell
                    // everyone about it.
                    if (mPendingConfiguration == null ||
                            mPendingConfiguration.isOtherSeqNewer(newConfig)) {
                        mPendingConfiguration = newConfig;

                        sendMessage(H.CONFIGURATION_CHANGED, newConfig);
                    }
                }
            }
        }
        @Override
        public void onLowMemory() {
        }
        @Override
        public void onTrimMemory(int level) {
        }
    });
}
attach做的主要事情有:
1.创建系统上下文 getSystemContext()-->ContextImpl.createSystemContext()-->new ContextImpl()
2.创建应用上下文 ContextImpl.createAppContext()-->new ContextImpl(),由应用上下文创建Application,并调用其onCreate()方法
3.添加回调ComponentCallbacks2到ViewRootImpl上

创建系统上下文/应用上下文

/*** ContextImpl.java ***/
static ContextImpl createSystemContext(ActivityThread mainThread) {
    LoadedApk packageInfo = new LoadedApk(mainThread);
    ContextImpl context = new ContextImpl(null, mainThread,
            packageInfo, null, null, false, null, null, Display.INVALID_DISPLAY);
    context.mResources.updateConfiguration(context.mResourcesManager.getConfiguration(),
            context.mResourcesManager.getDisplayMetricsLocked());
    return context;
}
static ContextImpl createAppContext(ActivityThread mainThread, LoadedApk packageInfo) {
    if (packageInfo == null) throw new IllegalArgumentException("packageInfo");
    return new ContextImpl(null, mainThread,
            packageInfo, null, null, false, null, null, Display.INVALID_DISPLAY);
}
new ContextImpl时,系统上下文和应用上下文的参数是一样的,createAppContext()的参数packageInfo,就是createSystemContext()中new的LoadedApk。
创建完成之后,系统上下文赋值给了ActivityThread的成员变量mSystemContext,而应用上下文只是作为函数中的局部变量临时使用。
/*** ActivityThread.java ***/
private ContextImpl mSystemContext;

创建Application

/*** LoadedApk.java ***/
public Application makeApplication(boolean forceDefaultAppClass,
        Instrumentation instrumentation) {
    if (mApplication != null) {
        return mApplication;
    }

    Application app = null;

    String appClass = mApplicationInfo.className;
    //参数forceDefaultAppClass为true
    if (forceDefaultAppClass || (appClass == null)) {
        appClass = "android.app.Application";
    }

    try {
        java.lang.ClassLoader cl = getClassLoader();
        //此LoadedApk对象是createSystemContext时new的,mPackageName="android"
        if (!mPackageName.equals("android")) {
            initializeJavaContextClassLoader();
        }
        //又创建了一个局部应用上下文
        ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
        //创建Application
        app = mActivityThread.mInstrumentation.newApplication(
                cl, appClass, appContext);
        appContext.setOuterContext(app);
    } catch (Exception e) {
        ...
    }
    //将前面创建的app添加到应用列表。
    mActivityThread.mAllApplications.add(app);
    mApplication = app;

    ...

    return app;
}

这一步主要创建了一个ActivityThread对象,然后执行了该对象的attach()方法。
attach()方法中创建了系统上下文mSystemContext(类型为ContextImpl),并创建Application对象。
系统上下文中,new了一个LoadedApk的成员变量,并将ActivityThread对象传给LoadedApk成员。
后面的Application对象就是LoadedApk使用ActivityThread创建的。
LoadedApk创建了Application对象后,将Application添加到ActivityThread的应用列表中。


2. 创建系统服务管理

/*** SystemServer.java ***/
mSystemServiceManager = new SystemServiceManager(mSystemContext);
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
这一步比较简单,只是new了一个SystemServiceManager,并将其添加到本地服务列表中。
mSystemContext为第一步中创建的系统上下文。
本地服务列表是以类为key保存的一个列表,即列表中某种类型的对象最多只能有一个。
/*** SystemServiceManager.java ***/

//系统服务列表,系统服务必须继承SystemService
private final ArrayList<SystemService> mServices = new ArrayList<SystemService>();

//当前处于开机过程的哪个阶段,SystemService.PHASE_XXXXX
private int mCurrentPhase = -1;

//通过类名启动系统服务,可能会找不到类而抛异常
public SystemService startService(String className) {
    final Class<SystemService> serviceClass;
    try {
        serviceClass = (Class<SystemService>)Class.forName(className);
    } catch (ClassNotFoundException ex) {
        Slog.i(TAG, "Starting " + className);
        throw new RuntimeException("Failed to create service " + className
                + ": service class not found, usually indicates that the caller should "
                + "have called PackageManager.hasSystemFeature() to check whether the "
                + "feature is available on this device before trying to start the "
                + "services that implement it", ex);
    }
    return startService(serviceClass);
}

//创建并启动系统服务,系统服务类必须继承SystemService
public <T extends SystemService> T startService(Class<T> serviceClass) {
    final String name = serviceClass.getName();
    Slog.i(TAG, "Starting " + name);

    // Create the service.
    if (!SystemService.class.isAssignableFrom(serviceClass)) {
        throw new RuntimeException("Failed to create " + name
                + ": service must extend " + SystemService.class.getName());
    }
    final T service;
    try {
        Constructor<T> constructor = serviceClass.getConstructor(Context.class);
        service = constructor.newInstance(mContext);
    } catch (InstantiationException ex) {
        throw new RuntimeException("Failed to create service " + name
                + ": service could not be instantiated", ex);
    } catch (IllegalAccessException ex) {
        throw new RuntimeException("Failed to create service " + name
                + ": service must have a public constructor with a Context argument", ex);
    } catch (NoSuchMethodException ex) {
        throw new RuntimeException("Failed to create service " + name
                + ": service must have a public constructor with a Context argument", ex);
    } catch (InvocationTargetException ex) {
        throw new RuntimeException("Failed to create service " + name
                + ": service constructor threw an exception", ex);
    }

    // Register it.
    mServices.add(service);

    // Start it.
    try {
        service.onStart();
    } catch (RuntimeException ex) {
        throw new RuntimeException("Failed to start service " + name
                + ": onStart threw an exception", ex);
    }
    return service;
}

//通知系统服务到了开机的哪个阶段,会遍历调用所有系统服务的onBootPhase()函数
public void startBootPhase(final int phase) {
    if (phase <= mCurrentPhase) {
        throw new IllegalArgumentException("Next phase must be larger than previous");
    }
    mCurrentPhase = phase;

    Slog.i(TAG, "Starting phase " + mCurrentPhase);

    final int serviceLen = mServices.size();
    for (int i = 0; i < serviceLen; i++) {
        final SystemService service = mServices.get(i);
        try {
            service.onBootPhase(mCurrentPhase);
        } catch (Exception ex) {
            throw new RuntimeException("Failed to boot service "
                    + service.getClass().getName()
                    + ": onBootPhase threw an exception during phase "
                    + mCurrentPhase, ex);
        }
    }
}

/*** SystemService.java ***/

/*
 * Boot Phases
 */
public static final int PHASE_WAIT_FOR_DEFAULT_DISPLAY = 100; // maybe should be a dependency?

/**
 * After receiving this boot phase, services can obtain lock settings data.
 */
public static final int PHASE_LOCK_SETTINGS_READY = 480;

/**
 * After receiving this boot phase, services can safely call into core system services
 * such as the PowerManager or PackageManager.
 */
public static final int PHASE_SYSTEM_SERVICES_READY = 500;

/**
 * After receiving this boot phase, services can broadcast Intents.
 */
public static final int PHASE_ACTIVITY_MANAGER_READY = 550;

/**
 * After receiving this boot phase, services can start/bind to third party apps.
 * Apps will be able to make Binder calls into services at this point.
 */
public static final int PHASE_THIRD_PARTY_APPS_CAN_START = 600;

/**
 * After receiving this boot phase, services can allow user interaction with the device.
 * This phase occurs when boot has completed and the home application has started.
 * System services may prefer to listen to this phase rather than registering a
 * broadcast receiver for ACTION_BOOT_COMPLETED to reduce overall latency.
 */
public static final int PHASE_BOOT_COMPLETED = 1000;


//子类必须定义只有一个Context参数的构造,并调用父类的此构造将Context参数传给父类。
//SystemServiceManager创建SystemService时,使用反射机制调用的此构造方法
public SystemService(Context context) {
    mContext = context;
}

//启动系统服务时,调用
public abstract void onStart();

//开机的每个阶段都会调用
public void onBootPhase(int phase) {}

系统服务区别于普通服务,普通服务由ServiceManager来管理。ServiceManager涉及到Binder机制,是如何管理普通服务的,后续再研究。

3. 启动各种系统服务

/*** SystemServer.java ***/
startBootstrapServices(); //启动引导服务
startCoreServices();      //启动核心服务
startOtherServices();     //启动其他服务

3.1 启动引导服务

/*** SystemServer.java ***/
private void startBootstrapServices() {
    //启动Installer服务,阻塞等待与installd建立socket通道
    Installer installer = mSystemServiceManager.startService(Installer.class);

    //启动AMS(后面做详细分析)
    mActivityManagerService = mSystemServiceManager.startService(
            ActivityManagerService.Lifecycle.class).getService();
    mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
    mActivityManagerService.setInstaller(installer);

    //启动PowerManagerService
    mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);

    //PowerManagerService就绪,AMS初始化电源管理
    mActivityManagerService.initPowerManagement();

    //启动LightsService
    mSystemServiceManager.startService(LightsService.class);

    //启动DisplayManagerService(before package manager)
    mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);

    //初始化package manager之前,需要默认显示。阻塞,10s超时,see DisplayManagerService.onBootPhase()
    mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);

    //当设备正在加密时,仅运行核心应用
    String cryptState = SystemProperties.get("vold.decrypt");
    if (ENCRYPTING_STATE.equals(cryptState)) {
        Slog.w(TAG, "Detected encryption in progress - only parsing core apps");
        mOnlyCore = true;
    } else if (ENCRYPTED_STATE.equals(cryptState)) {
        Slog.w(TAG, "Device encrypted - only parsing core apps");
        mOnlyCore = true;
    }

    //启动PackageManagerService
    Slog.i(TAG, "Package Manager");
    mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
            mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
    mFirstBoot = mPackageManagerService.isFirstBoot();
    mPackageManager = mSystemContext.getPackageManager();

    //将UserManagerService添加到服务列表,该服务是在PackageManagerService中初始化的
    Slog.i(TAG, "User Service");
    ServiceManager.addService(Context.USER_SERVICE, UserManagerService.getInstance());

    //初始化用来缓存包资源的属性缓存
    AttributeCache.init(mSystemContext);

    //设置AMS
    mActivityManagerService.setSystemProcess();

    //启动传感器服务(native 服务,依赖PackageManagerService、AppOpsService、permissions service)
    startSensorService();
}
这步首先等待installd启动完成,然后启动一些相互依赖的关键服务。
所创建的服务:ActivityManagerService,PowerManagerService,LightsService,DisplayManagerService,PackageManagerService,UserManagerService,sensor服务。

3.2 启动核心服务

/*** SystemServer.java ***/
/**
 * Starts some essential services that are not tangled up in the bootstrap process.
 */
private void startCoreServices() {
    //启动BatteryService,用于统计电池电量,需要LightService
    mSystemServiceManager.startService(BatteryService.class);

    //启动UsageStatsService,用于统计应用使用情况
    mSystemServiceManager.startService(UsageStatsService.class);
    mActivityManagerService.setUsageStatsManager(
            LocalServices.getService(UsageStatsManagerInternal.class));
    // Update after UsageStatsService is available, needed before performBootDexOpt.
    mPackageManagerService.getUsageStatsIfNoPackageUsageInfo();

    //启动WebViewUpdateService
    mSystemServiceManager.startService(WebViewUpdateService.class);
}
启动服务BatteryService,UsageStatsService,WebViewUpdateService。

3.3 启动其他服务

此函数代码较长,但是逻辑简单,主要是启动各种服务。以下代码仅按顺序列出启动的服务,有些服务根据条件,如是否是工厂模式,或系统属性配置,选择性启动,这里不考虑条件判断和异常处理。

/*** SystemServer.java ***/
private void startOtherServices() {
    ...
    try {
        SchedulingPolicyService       // 调度策略
        TelecomLoaderService          //
        TelephonyRegistry             // 提供电话注册、管理服务,可以获取电话的链接状态、信号强度等
        EntropyMixer                  // 随机数相关,原名EntropyService。 参考“EntropyService分析”
        CameraService                 //
        AccountManagerService         // 提供所有账号、密码、认证管理等等的服务
        ContentService                // ContentProvider服务,提供跨进程数据交换
        VibratorService               // 振动器服务
        ConsumerIrService             // 红外远程控制服务
        AlarmManagerService           // 提供闹铃和定时器等功能

        //初始化 Watchdog。是在AMS的systemReady回调中运行的:Watchdog.getInstance().start();
        final Watchdog watchdog = Watchdog.getInstance();
        watchdog.init(context, mActivityManagerService);

        WindowManagerService          // 窗口管理服务
        InputManagerService           // 事件传递分发服务
        BluetoothService              // 蓝牙服务
    } catch (RuntimeException e) {
        Slog.e("System", "******************************************");
        Slog.e("System", "************ Failure starting core service", e);
    }


    InputMethodManagerService         // 输入法服务
    AccessibilityManagerService       // 辅助管理程序截获所有的用户输入,并根据这些输入给用户一些额外的反馈,起到辅助的效果
    MountService                      // 挂载服务
    UiModeManagerService              // 管理当前Android设备的夜间模式和行车模式

    //frameworks/base/core/res/res/values-zh-rCN/strings.xml
    ActivityManagerNative.getDefault().showBootMessage(
            context.getResources().getText(
                    com.android.internal.R.string.android_upgrading_starting_apps),
            false);

    LockSettingsService               // 屏幕锁定服务,管理每个用户的相关锁屏信息
    PersistentDataBlockService        //
    DeviceIdleController              // Doze模式的主要驱动,参考“深入Android 'M' Doze”
    DevicePolicyManagerService        // 提供一些系统级别的设置及属性
    StatusBarManagerService           // 状态栏管理服务
    ClipboardService                  // 系统剪切板服务
    NetworkManagementService          // 网络管理服务
    TextServicesManagerService        // 文本服务,例如文本检查等
    NetworkScoreService               // 网络评分服务
    NetworkStatsService               // 网络状态服务
    NetworkPolicyManagerService       // 网络策略服务
    WifiP2pService                    // Wifi Direct服务
    WifiService                       // Wifi服务
    WifiScanningService               // Wifi扫描服务
    RttService                        // Wifi相关
    EthernetService                   // 以太网服务
    ConnectivityService               // 网络连接管理服务
    NsdService                        // 网络发现服务(Network Service Discovery Service)
    UpdateLockService                 //


    //等待MountService完全启动,后面有些依赖
    mountService.waitForAsecScan();

    accountManager.systemReady();
    contentService.systemReady();

    NotificationManagerService        // 通知栏管理服务
    DeviceStorageMonitorService       // 磁盘空间状态检测服务
    LocationManagerService            // 位置服务,GPS、定位等
    CountryDetectorService            // 检测用户国家
    SearchManagerService              // 搜索管理服务
    DropBoxManagerService             // 用于系统运行时日志的存储于管理
    WallpaperManagerService           // 壁纸管理服务
    AudioService                      // AudioFlinger的上层管理封装,主要是音量、音效、声道及铃声等的管理
    DockObserver                      // 如果系统有个座子,当手机装上或拔出这个座子的话,就得靠他来管理了
    WiredAccessoryManager             // 监视手机和底座上的耳机
    MidiService                       //
    UsbService                        // USB服务
    SerialService                     // 串口服务
    TwilightService                   // 指出用户当前所在位置是否为晚上,被UiModeManager等用来调整夜间模式。
    JobSchedulerService               //
    BackupManagerService              // 备份服务
    AppWidgetService                  // 提供Widget的管理和相关服务
    VoiceInteractionManagerService    // 语音交互管理服务
    DiskStatsService                  // 磁盘统计服务,供dumpsys使用
    SamplingProfilerService           // 用于耗时统计等
    NetworkTimeUpdateService          // 监视网络时间,当网络时间变化时更新本地时间。
    CommonTimeManagementService       // 管理本地常见的时间服务的配置,在网络配置变化时重新配置本地服务。
    CertBlacklister                   // 提供一种机制更新SSL certificate blacklist
    DreamManagerService               // 屏幕保护
    AssetAtlasService                 // 负责将预加载的bitmap组装成纹理贴图,生成的纹理贴图可以被用来跨进程使用,以减少内存。
    GraphicsStatsService              //
    PrintManagerService               // 打印服务
    RestrictionsManagerService        //
    MediaSessionService               //
    HdmiControlService                // HDMI控制服务
    TvInputManagerService             //
    MediaRouterService                //
    TrustManagerService               //
    FingerprintService                // 指纹服务
    BackgroundDexOptService           // 主要用于classes文件的odex优化
    LauncherAppsService               //
    MediaProjectionManagerService     // 管理媒体投影会话
    MmsServiceBroker                  // MmsService的代理


    // It is now time to start up the app processes...
    vibrator.systemReady();
    lockSettings.systemReady();

    // Needed by DevicePolicyManager for initialization
    mSystemServiceManager.startBootPhase(SystemService.PHASE_LOCK_SETTINGS_READY);

    mSystemServiceManager.startBootPhase(SystemService.PHASE_SYSTEM_SERVICES_READY);

    wm.systemReady();

    if (safeMode) {
        mActivityManagerService.showSafeModeOverlay();
    }

    // Update the configuration for this context by hand
    context.getResources().updateConfiguration(config, metrics);

    mPowerManagerService.systemReady(mActivityManagerService.getAppOpsService());
    mPackageManagerService.systemReady();
    mDisplayManagerService.systemReady(safeMode, mOnlyCore);
    mActivityManagerService.systemReady(new Runnable() {
        @Override
        public void run() {
            mSystemServiceManager.startBootPhase(SystemService.PHASE_ACTIVITY_MANAGER_READY);

            mActivityManagerService.startObservingNativeCrashes();
            WebViewFactory.prepareWebViewInSystemServer();
            startSystemUi(context);
            networkScoreF.systemReady();
            networkManagementF.systemReady();
            networkStatsF.systemReady();
            networkPolicyF.systemReady();
            connectivityF.systemReady();
            audioServiceF.systemReady();

            //开启 Watchdog
            Watchdog.getInstance().start();

            mSystemServiceManager.startBootPhase(SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);

            wallpaperF.systemRunning();
            immF.systemRunning(statusBarF);
            locationF.systemRunning();
            countryDetectorF.systemRunning();
            networkTimeUpdaterF.systemRunning();
            commonTimeMgmtServiceF.systemRunning();
            textServiceManagerServiceF.systemRunning();
            atlasF.systemRunning();
            inputManagerF.systemRunning();
            telephonyRegistryF.systemRunning();
            mediaRouterF.systemRunning();
            mmsServiceF.systemRunning();
        }
    });
}


参考

Android系统启动-SystemServer上篇

Android系统启动-SystemServer下篇


Android FactoryTest框架

Android ART运行时无缝替换Dalvik虚拟机的过程分析

SamplingProfilerIntegration分析

EntropyService分析

Android 系统服务一览表

深入Android 'M' Doze

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android 12 SystemServer启动流程如下: 1. 引导加载:系统启动时,先加载引导程序,进行硬件初始化、内核加载等操作。 2. Zygote 进程启动:Zygote 是 Android 系统中的一个特殊进程,负责孵化其他应用进程。Zygote 进程会预加载一些常用的类和资源,以加快应用的启动速度。 3. SystemServer 进程启动:Zygote 进程会 fork 出 SystemServer 进程,该进程是 Android 系统中的核心服务进程。SystemServer 进程负责启动和管理系统级别的服务,例如 ActivityManagerService、PackageManagerService、WindowManagerService 等。 4. SystemServer 初始化:SystemServer 进程启动后,会进行一系列的初始化操作。首先会创建 Looper 线程,用于接收消息并处理各个服务的初始化工作。然后依次创建各个系统服务,并调用它们的启动方法。 5. 启动系统服务:SystemServer 进程会按照一定顺序启动各个系统服务。每个系统服务都有自己的初始化流程,例如 PackageManagerService 会加载应用程序列表、数据目录等;ActivityManagerService 会初始化进程间通信机制等。 6. 启动应用进程:在系统服务启动完成后,SystemServer 进程会通过 Zygote 孵化出其他应用进程。应用进程会根据 AndroidManifest.xml 中的配置进行初始化,包括创建 Application、加载资源等。 总结来说,Android 12 SystemServer启动流程包括引导加载、Zygote 进程启动、SystemServer 进程启动、SystemServer 初始化、启动系统服务和启动应用进程等步骤。这些步骤都是为了在系统启动时提供必要的服务和资源。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值