SystemServer的启动

简介: SystemServer的启动

frameworks\base\core\java\com\android\internal\os\ZygoteInit.java的forkSystemServer

   /* Request to fork the system server process */
            pid = Zygote.forkSystemServer(
                    parsedArgs.mUid, parsedArgs.mGid,
                    parsedArgs.mGids,
                    parsedArgs.mRuntimeFlags,
                    null,
                    parsedArgs.mPermittedCapabilities,
                    parsedArgs.mEffectiveCapabilities);
        } catch (IllegalArgumentException ex) {
            throw new RuntimeException(ex);
        }
 
        /* For child process */
        if (pid == 0) {
            if (hasSecondZygote(abiList)) {
                waitForSecondaryZygote(socketName);
            }
 
            zygoteServer.closeServerSocket();
            return handleSystemServerProcess(parsedArgs);
        }

handleSystemServerProcess来启动SyetemServer进程。

handleSystemServerProcess关键代码

/*
             * Pass the remaining arguments to SystemServer.
             */
            return ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion,
                    parsedArgs.mDisabledCompatChanges,
                    parsedArgs.mRemainingArgs, cl);
    public static final Runnable zygoteInit(int targetSdkVersion, long[] disabledCompatChanges,
            String[] argv, ClassLoader classLoader) {
        if (RuntimeInit.DEBUG) {
            Slog.d(RuntimeInit.TAG, "RuntimeInit: Starting application from zygote");
        }
 
        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ZygoteInit");
        RuntimeInit.redirectLogStreams();
 
        RuntimeInit.commonInit();
        ZygoteInit.nativeZygoteInit();
        return RuntimeInit.applicationInit(targetSdkVersion, disabledCompatChanges, argv,
                classLoader);
    }

nativeZygoteInit方法在 frameworks/base/core/jni/AndroidRuntime.cpp中定义

int register_com_android_internal_os_ZygoteInit_nativeZygoteInit(JNIEnv* env)
{
    const JNINativeMethod methods[] = {
        { "nativeZygoteInit", "()V",
            (void*) com_android_internal_os_ZygoteInit_nativeZygoteInit },
    };
    return jniRegisterNativeMethods(env, "com/android/internal/os/ZygoteInit",
        methods, NELEM(methods));
}

对应的方法为com_android_internal_os_ZygoteInit_nativeZygoteInit

static void com_android_internal_os_ZygoteInit_nativeZygoteInit(JNIEnv* env, jobject clazz)
{
    gCurRuntime->onZygoteInit();
}

这里gCurRuntime是AndroidRuntime类型的指针,AndroidRuntime的子类AppRuntime在app_main.cpp中定义,我们来查看AppRuntime的onZygoteInit函数,代码如下所示。

frameworks\base\cmds\app_process\app_main.cpp

 virtual void onZygoteInit()
    {
        sp<ProcessState> proc = ProcessState::self();
        ALOGV("App process: starting thread pool.\n");
        //启动一个Binder线程池,这样SyetemServer进程就可以使用Binder来与其他进程进行通信了
        proc->startThreadPool();
    }

applicationInit在frameworks\base\core\java\com\android\internal\os\RuntimeInit.java中

 protected static Runnable applicationInit(int targetSdkVersion, long[] disabledCompatChanges,
            String[] argv, ClassLoader classLoader) {
        // If the application calls System.exit(), terminate the process
        // immediately without running any shutdown hooks.  It is not possible to
        // shutdown an Android application gracefully.  Among other things, the
        // Android runtime shutdown hooks close the Binder driver, which can cause
        // leftover running threads to crash before the process actually exits.
        nativeSetExitWithoutCleanup(true);
 
        VMRuntime.getRuntime().setTargetSdkVersion(targetSdkVersion);
        VMRuntime.getRuntime().setDisabledCompatChanges(disabledCompatChanges);
 
        final Arguments args = new Arguments(argv);
 
        // The end of of the RuntimeInit event (see #zygoteInit).
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
 
        // Remaining arguments are passed to the start class's static main
        return findStaticMain(args.startClass, args.startArgs, classLoader);
    }

findStaticMain方法主要调用了MethodAndArgsCaller(m, argv);

protected static Runnable findStaticMain(String className, String[] argv,
            ClassLoader classLoader) {
        Class<?> cl;
 
        try {
            cl = Class.forName(className, true, classLoader);
        } catch (ClassNotFoundException ex) {
            throw new RuntimeException(
                    "Missing class when invoking static main " + className,
                    ex);
        }
 
        Method m;
        try {
            m = cl.getMethod("main", new Class[] { String[].class });
        } catch (NoSuchMethodException ex) {
            throw new RuntimeException(
                    "Missing static main on " + className, ex);
        } catch (SecurityException ex) {
            throw new RuntimeException(
                    "Problem getting static main on " + className, ex);
        }
 
        int modifiers = m.getModifiers();
        if (! (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))) {
            throw new RuntimeException(
                    "Main method is not public and static on " + className);
        }
 
        /*
         * This throw gets caught in ZygoteInit.main(), which responds
         * by invoking the exception's run() method. This arrangement
         * clears up all the stack frames that were required in setting
         * up the process.
         */
        return new MethodAndArgsCaller(m, argv);
    }

MethodAndArgsCaller的run方法调用

mMethod.invoke(null, new Object[] { mArgs });

SystemServer的main函数被动态调用。

进入SystemServer

frameworks\base\services\java\com\android\server\SystemServer.java

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

run方法关键代码如下

System.loadLibrary("android_servers");加载了libandroid_servers.so
// Create the system service manager.
mSystemServiceManager = new SystemServiceManager(mSystemContext);创建SystemServiceManager,它会对系统的服务进行创建、启动和生命周期管理
 
startBootstrapServices(t);
startCoreServices(t);
startOtherServices(t);
BootstrapServices 作用
Installer 系统安装apk时的一个服务类,启动完成Installer服务之后才能启动其他的系统服务
ActivityManagerService 负责四大组件的启动、切换、调度。
PowerManagerService 计算系统中和Power相关的计算,然后决策系统应该如何反应
LightsService 管理和显示背光LED
DisplayManagerService 用来管理所有显示设备
UserManagerService 多用户模式管理
SensorService 为系统提供各种感应器服务
PackageManagerService 用来对apk进行安装、解析、删除、卸载等等操作
CoreServices
BatteryService 管理电池相关的服务
UsageStatsService 收集用户使用每一个APP的频率、使用时常
WebViewUpdateService WebView更新服务
OtherServices
CameraService 摄像头相关服务
AlarmManagerService 全局定时器管理服务
InputManagerService 管理输入事件
WindowManagerService 窗口管理服务
VrManagerService VR模式管理服务
BluetoothService 蓝牙管理服务
NotificationManagerService 通知管理服务
DeviceStorageMonitorService 存储相关管理服务
LocationManagerService 定位管理服务
AudioService 音频相关管理服务
… ….

显示详细信息

 

要启动那个服务,调用SystemServiceManager的startService方法即可

mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);

frameworks\base\services\core\java\com\android\server\SystemServiceManager.java

    public SystemService startService(String className) {
        final Class<SystemService> serviceClass = loadClassFromLoader(className,
                this.getClass().getClassLoader());
        return startService(serviceClass);
    }
    public <T extends SystemService> T startService(Class<T> serviceClass) {
        try {
            final String name = serviceClass.getName();
            Slog.i(TAG, "Starting " + name);
            Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartService " + 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);创建service实例
            } 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);
            }
 
            startService(service);
            return service;
        } finally {
            Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
        }
    }
 
    public void startService(@NonNull final SystemService service) {
        // Register it.
        mServices.add(service);
        // Start it.
        long time = SystemClock.elapsedRealtime();
        try {
            service.onStart();
        } catch (RuntimeException ex) {
            throw new RuntimeException("Failed to start service " + service.getClass().getName()
                    + ": onStart threw an exception", ex);
        }
        warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart");
    }

总结SyetemServer进程

SyetemServer在启动时做了如下工作:

1.启动Binder线程池,这样就可以与其他进程进行通信。

2.创建SystemServiceManager用于对系统的服务进行创建、启动和生命周期管理。

3.启动各种系统服务。


目录
相关文章
|
数据可视化 Linux 数据中心
服务器版Rstudio-server初体验丨随时随地云端处理数据,不再担心电脑崩盘重启了!
服务器版Rstudio-server初体验丨随时随地云端处理数据,不再担心电脑崩盘重启了!
|
传感器 弹性计算 人工智能
简介Multi-Agent
多智能体系统(MAS)是由多个自主智能体组成的计算系统,各智能体能独立决策、协同作业,无需中央控制。其特点包括自主性、分布性、交互性、异构性和适应性,广泛应用于人工智能、经济、交通、医疗和环保等领域,展现出巨大潜力。然而,MAS也面临通信开销、一致性、安全性和可扩展性等挑战。
1695 3
|
并行计算 PyTorch 算法框架/工具
阿里云PAI-部署Qwen2-VL-72B
阿里云PAI-部署Qwen2-VL-72B踩坑实录
6429 1
|
数据采集 存储 NoSQL
爬虫在金融领域的应用:股票数据收集
本文探讨了网络爬虫在金融领域的应用,特别是在收集股票价格数据方面的实践。文章介绍了使用Scrapy框架和代理IP技术来构建爬虫,以应对反爬策略和提高数据采集效率。通过安装Scrapy和PyMongo,创建Scrapy项目,配置代理中间件,以及编写爬虫代码,实现了从Yahoo Finance抓取股票信息并存储至MongoDB。这种方法能有效助力市场分析和投资决策,提升数据采集的效率与质量。
1326 0
爬虫在金融领域的应用:股票数据收集
|
存储 消息中间件 JSON
DDD基础教程:一文带你读懂DDD分层架构
DDD基础教程:一文带你读懂DDD分层架构
|
SQL 监控 安全
web应用防火墙
【8月更文挑战第16天】
332 1
|
搜索推荐
常用排序算法复杂度和稳定性总结
排序算法 平均时间复杂度 最好情况 最坏情况 空间复杂度 稳定性 冒泡排序 O(n2) O(n) O(n2) O(1) 稳定 选择排序 O(n2) O(n2) O(n2) O(1) 不稳定 插入排序 O(n2) O(n) O(n2) O(1) 稳定 希尔排序 O(nlogn)...
3009 0
|
安全 Java 关系型数据库
游戏道具平台|基于Springboot+Vue实现游戏道具平台系统
游戏道具平台|基于Springboot+Vue实现游戏道具平台系统
975 2
游戏道具平台|基于Springboot+Vue实现游戏道具平台系统
|
Java
一文读懂继承性
一文读懂继承性
574 0
|
移动开发 数据可视化 前端开发
F2Native 1.0 新的起点
F2Native,开箱即用的跨平台高性能可视化解决方案,国民级应用支付宝上的图表组件,在经历3代架构的升级和大量的优化后,终于正式开源 🎉🎉🎉!!!。完美支持 Android、iOS 平台。完备的图形语法理论,满足你的各种可视化需求。
F2Native 1.0 新的起点

热门文章

最新文章