systemserver探究笔记



其实一开始本来打算写Activity启动的,后来发现自己老是弄不明白AMSActivityThread调用关系,于是再往上深究,发现是自己的基础没打好,缺少对Android整体的认知,所以才会知其然而不知其所以然。在讲system之前先上一张Android整体架构图。

分析的时候参考了http://quanminchaoren.iteye.com/blog/1252322不过它发布文章的版本大概还在Android2.2左右 ,源码可能会有一些出入


systemserver实际上不是一个server,源码中也可以看出

public final class SystemServer

当daivik虚拟机启动的时候,调用了

    public static void main(String[] args) {

        new SystemServer().run();

    }

而在run方法完成了这么几件事

1.检查设备的时间是不是在1970以后,如果不是的话程序有可能crash

2.创建主Thread并循环looper

3.加载Android_server   loadLibrary

4.初始化各种服务

5.初始化systemcontext

6.systemcontext作为参数创建SystemServiceManager,并以键值对的形式存储到LocalServices

7.开启各种服务

源码如下

    private void run() {

        // If a device's clock is before 1970 (before 0), a lot of

        // APIs crash dealing with negative numbers, notably

        // java.io.File#setLastModified, so instead we fake it and

        // hope that time from cell towers or NTP fixes it shortly.

        //检查系统时间,要是在1970年之前,许多API会crash掉,所以我们希望程序一会通过信号塔或者NTP来修复它

        if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {

            Slog.w(TAG, "System clock is before 1970; setting to 1970.");

            SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);

        }

 

        // Here we go!

        Slog.i(TAG, "Entered the Android system server!");

        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN, SystemClock.uptimeMillis());

 

        // In case the runtime switched since last boot (such as when

        // the old runtime was removed in an OTA), set the system

        // property so that it is in sync. We can't do this in

        // libnativehelper's JniInvocation::Init code where we already

        // had to fallback to a different runtime because it is

        // running as root and we need to be the system user to set

        // the property. http://b/11463182

        //万一runtime切换成上次启动,例如上次runtime因为OTA被删除了,我们需要设置一个系统属性以便于同步

        //我们不能在一个回退到的runtime中初始化代码,因为它已经作为root运行了

        SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());

 

        // Enable the sampling profiler.

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

        }

 

        // Mmmmmm... more memory!

        VMRuntime.getRuntime().clearGrowthLimit();

 

        // The system server has to run all of the time, so it needs to be

        // as efficient as possible with its memory usage.

        //系统system server必须一直运行,所以它需要尽可能的高效使用内存

        VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);

 

        // Some devices rely on runtime fingerprint generation, so make sure

        // we've defined it before booting further.

        //一些设备依赖runtime指纹生成,所以我们应该确保在启动之前就定义了它

        Build.ensureFingerprintProperty();

 

        // Within the system server, it is an error to access Environment paths without

        // explicitly specifying a user.

        //在system server中,隐式确定的用户访问环境路径是错误的

        Environment.setUserRequired(true);

 

        // Ensure binder calls into the system always run at foreground priority.

        //确保binder与system通信时总是以前台优先级运行

        BinderInternal.disableBackgroundScheduling(true);

 

        // Prepare the main looper thread (this thread).

        android.os.Process.setThreadPriority(

                android.os.Process.THREAD_PRIORITY_FOREGROUND);

        android.os.Process.setCanSelfBackground(false);

        Looper.prepareMainLooper();

 

        // Initialize native services.

        System.loadLibrary("android_servers");

        nativeInit();

 

        // Check whether we failed to shut down last time we tried.

        // This call may not return.

        performPendingShutdown();

 

        // Initialize the system context.

        //初始化了systemcontext,通过ActivityThr

ead创建

        createSystemContext();

 

        // Create the system service manager.

        mSystemServiceManager = new SystemServiceManager(mSystemContext);

//将mSystemServiceManager存储到数组中,通过键值对指定mSystemServiceManager为SystemServiceManager

        LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);

 

        // Start services.

        try {

            startBootstrapServices();

            startCoreServices();

            startOtherServices();

        } catch (Throwable ex) {

            Slog.e("System", "******************************************");

            Slog.e("System", "************ Failure starting system services", ex);

            throw ex;

        }

 

        // For debug builds, log event loop stalls to dropbox for analysis.

        if (StrictMode.conditionallyEnableDebugLogging()) {

            Slog.i(TAG, "Enabled StrictMode for system server main thread.");

        }

 

        // Loop forever.

        Looper.loop();

        throw new RuntimeException("Main thread loop unexpectedly exited");

    }

初始化各种服务调用的是nativeInit();方法涉及到native层的实现,我们只需要知道它初始化了什么服务就好



接下来,让我们看看startBootstrapServices();startCoreServices();startOtherServices();这三个函数分别干了什么

startBootstrapServices();

    /**

     * Starts the small tangle of critical services that are needed to get

     * the system off the ground.  These services have complex mutual dependencies

     * which is why we initialize them all in one place here.  Unless your service

     * is also entwined in these dependencies, it should be initialized in one of

     * the other functions.

     */

    private void startBootstrapServices() {

        // Wait for installd to finish starting up so that it has a chance to

        // create critical directories such as /data/user with the appropriate

        // permissions.  We need this to complete before we initialize other services.

        Installer installer = mSystemServiceManager.startService(Installer.class);

 

        // Activity manager runs the show.

        mActivityManagerService = mSystemServiceManager.startService(

                ActivityManagerService.Lifecycle.class).getService();

        mActivityManagerService.setSystemServiceManager(mSystemServiceManager);

        mActivityManagerService.setInstaller(installer);

 

        // Power manager needs to be started early because other services need it.

        // Native daemons may be watching for it to be registered so it must be ready

        // to handle incoming binder calls immediately (including being able to verify

        // the permissions for those calls).

        mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);

 

        // Now that the power manager has been started, let the activity manager

        // initialize power management features.

        mActivityManagerService.initPowerManagement();

 

        // Display manager is needed to provide display metrics before package manager

        // starts up.

        mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);

 

        // We need the default display before we can initialize the package manager.

        mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);

 

        // Only run "core" apps if we're encrypting the device.

        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;

        }

 

        // Start the package manager.

        Slog.i(TAG, "Package Manager");

        mPackageManagerService = PackageManagerService.main(mSystemContext, installer,

                mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);

        mFirstBoot = mPackageManagerService.isFirstBoot();

        mPackageManager = mSystemContext.getPackageManager();

 

        Slog.i(TAG, "User Service");

        ServiceManager.addService(Context.USER_SERVICE, UserManagerService.getInstance());

 

        // Initialize attribute cache used to cache resources from packages.

        AttributeCache.init(mSystemContext);

 

        // Set up the Application instance for the system process and get started.

        mActivityManagerService.setSystemProcess();

    }

代码这么多,我总结了一下

1.创建了AMS并启动它,关于它的启动采用了JAVA的反射机制。源码如下

        mActivityManagerService = mSystemServiceManager.startService(
                ActivityManagerService.Lifecycle.class).getService();
        mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
        mActivityManagerService.setInstaller(installer);
startServer中通过反射机制拿到ActivityManagerService.Lifecycle的实例

    public static final class Lifecycle extends SystemService {
        private final ActivityManagerService mService;

        public Lifecycle(Context context) {
            super(context);
            mService = new ActivityManagerService(context);
        }

        @Override
        public void onStart() {
            mService.start();
        }

        public ActivityManagerService getService() {
            return mService;
        }
    }
再通过getService拿到AMS,而构造AMS所传入的context就是构造mSystemServiceManager所用的context

2.开启其他服务,例如PMS,调用了PMS.main方法

3.为系统进程创建APP实例并启动

startCoreServices();

这个没什么好说的,开启一些必要服务,灯光电池什么的

    /**

     * Starts some essential services that are not tangled up in the bootstrap process.

     */

    private void startCoreServices() {

        // Manages LEDs and display backlight.

        mSystemServiceManager.startService(LightsService.class);

 

        // Tracks the battery level.  Requires LightService.

        mSystemServiceManager.startService(BatteryService.class);

 

        // Tracks application usage stats.

        mSystemServiceManager.startService(UsageStatsService.class);

        mActivityManagerService.setUsageStatsManager(

                LocalServices.getService(UsageStatsManagerInternal.class));

        // Update after UsageStatsService is available, needed before performBootDexOpt.

        mPackageManagerService.getUsageStatsIfNoPackageUsageInfo();

 

        // Tracks whether the updatable WebView is in a ready state and watches for update installs.

        mSystemServiceManager.startService(WebViewUpdateService.class);

    }

startOtherServices();

    /**

     * Starts a miscellaneous grab bag of stuff that has yet to be refactored

     * and organized.

     */

    private void startOtherServices() {

        final Context context = mSystemContext;

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
SystemServerAndroid 系统启动过程中的关键组件之一,它负责启动和管理系统中的各种服务和进程。SystemServer 的主要功能如下: 1. 启动 Android 系统中的各种系统服务,如 ActivityManagerService、PackageManagerService、WindowManagerService 等; 2. 初始化和启动 Zygote 进程,该进程将作为应用程序进程的父进程; 3. 启动系统中的各种进程,如系统进程、系统应用进程等; 4. 加载和初始化 Android 系统的各种服务和组件。 下面是 SystemServer源码解析: 1. SystemServer 的入口 SystemServer 的入口在 frameworks/base/services/java/com/android/server/SystemServer.java 文件中。在该文件中,SystemServer 类继承了 Binder 和 Runnable 接口,并且实现了 Runnable 接口的 run() 方法,该方法是 SystemServer 的入口。 在 run() 方法中,SystemServer 执行了以下操作: 1.1. 初始化 SystemServer 的环境 SystemServer 首先初始化自己的环境,包括设置系统属性、设置线程优先级等。 1.2. 启动各种系统服务 SystemServer 启动 Android 系统中的各种系统服务,包括 ActivityManagerService、PackageManagerService、WindowManagerService 等。这些服务都是在 SystemServer 的构造方法中创建的。 1.3. 初始化和启动 Zygote 进程 SystemServer 初始化和启动 Zygote 进程,该进程将作为应用程序进程的父进程。具体而言,SystemServer 调用 Zygote 的 main() 方法启动 Zygote 进程,并且设置 Zygote 的命令行参数。 1.4. 启动系统中的各种进程 SystemServer 启动 Android 系统中的各种进程,包括系统进程、系统应用进程等。具体而言,SystemServer 调用 ActivityManagerService 的 startSystemServer() 方法启动系统进程,并且调用 PackageManagerService 的 scanDirTracedLI() 方法扫描系统应用。 1.5. 加载和初始化 Android 系统的各种服务和组件 SystemServer 加载和初始化 Android 系统的各种服务和组件,包括 SystemUI、Launcher、InputMethodService 等。具体而言,SystemServer 调用 ActivityManagerService 的 startHomeActivity() 方法启动 Launcher,并且调用 PackageManagerService 的 packageInstalled() 方法加载和初始化应用程序。 2. SystemServer 的启动流程 SystemServer 的启动流程如下: 2.1. 启动 init 进程 在 Android 系统启动过程中,init 进程是第一个进程。init 进程启动时,会执行 init.rc 脚本中的命令,并且启动 SystemServer 进程。 2.2. 创建 SystemServer 进程 SystemServer 进程是在 init.rc 脚本中通过 service 命令创建的。具体而言,init.rc 脚本中会执行以下命令: ``` service system_server /system/bin/app_process -Xbootclasspath:/system/framework/core-libart.jar:/system/framework/conscrypt.jar:/system/framework/okhttp.jar:/system/framework/bouncycastle.jar:/system/framework/apache-xml.jar:/system/framework/core-junit.jar -classpath /system/framework/services.jar com.android.server.SystemServer ``` 该命令会启动 SystemServer 进程,并且设置 SystemServer 的启动参数。 2.3. 执行 SystemServer 的 run() 方法 当 SystemServer 进程启动后,会执行 SystemServer 的 run() 方法。在 run() 方法中,SystemServer 完成了 Android 系统的初始化和启动过程。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值