安卓7.0 系统服务启动流程

原创 2017年09月20日 20:40:56

安卓的系统服务都是由SystemServer这个进程创建的,那从他的main函数开始看看

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

新建了一个SystemServer类,并调用他的run方法

private void run() {
        ......
        startBootstrapServices();
        startCoreServices();
        startOtherServices();
        ......
    }

启动系统服务就是靠这三个方法

其中startBootstrapServices启动的是那些比较重要,而且相互之间有依赖关系的服务

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.
        Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "InitPowerManagement");
        mActivityManagerService.initPowerManagement();
        Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);

        // Manages LEDs and display backlight so we need it to bring up the display.
        mSystemServiceManager.startService(LightsService.class);

        // 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.
        traceBeginAndSlog("StartPackageManagerService");
        mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
                mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
        mFirstBoot = mPackageManagerService.isFirstBoot();
        mPackageManager = mSystemContext.getPackageManager();
        Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);

        // Manages A/B OTA dexopting. This is a bootstrap service as we need it to rename
        // A/B artifacts after boot, before anything else might touch/need them.
        // Note: this isn't needed during decryption (we don't have /data anyways).
        if (!mOnlyCore) {
            boolean disableOtaDexopt = SystemProperties.getBoolean("config.disable_otadexopt",
                    false);
            if (!disableOtaDexopt) {
                traceBeginAndSlog("StartOtaDexOptService");
                try {
                    OtaDexoptService.main(mSystemContext, mPackageManagerService);
                } catch (Throwable e) {
                    reportWtf("starting OtaDexOptService", e);
                } finally {
                    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
                }
            }
        }

        traceBeginAndSlog("StartUserManagerService");
        mSystemServiceManager.startService(UserManagerService.LifeCycle.class);
        Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);

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

        // The sensor service needs access to package manager service, app ops
        // service, and permissions service, therefore we start it after them.
        startSensorService();
    }

可以看到ActivityManagerService,PackageManagerService等都是在这个方法中启动的

startCoreServices启动的就是那些也很重要,但是没什么依赖关系的服务

private void startCoreServices() {
        // Tracks the battery level.  Requires LightService.
        mSystemServiceManager.startService(BatteryService.class);

        // Tracks application usage stats.
        mSystemServiceManager.startService(UsageStatsService.class);
        mActivityManagerService.setUsageStatsManager(
                LocalServices.getService(UsageStatsManagerInternal.class));

        // Tracks whether the updatable WebView is in a ready state and watches for update installs.
        mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);
    }

而startOtherServices就是其他的服务

private void startOtherServices() {
        final Context context = mSystemContext;
        VibratorService vibrator = null;
        IMountService mountService = null;
        NetworkManagementService networkManagement = null;
        NetworkStatsService networkStats = null;
        NetworkPolicyManagerService networkPolicy = null;
        ConnectivityService connectivity = null;
        NetworkScoreService networkScore = null;
        NsdService serviceDiscovery= null;
        WindowManagerService wm = null;
        SerialService serial = null;
        NetworkTimeUpdateService networkTimeUpdater = null;
        CommonTimeManagementService commonTimeMgmtService = null;
        InputManagerService inputManager = null;
        TelephonyRegistry telephonyRegistry = null;
        ConsumerIrService consumerIr = null;
        MmsServiceBroker mmsService = null;
        HardwarePropertiesManagerService hardwarePropertiesService = null;
        ......
        mActivityManagerService.systemReady(new Runnable() {
            @Override
            public void run() {
                ......
            }
        };
}

注意在startOtherServices的最后,也就是当系统的服务都已经启动的时候,会调用ActivityManagerService的systemReady方法

在systemReady方法中,又会调用startHomeActivityLocked方法

    boolean startHomeActivityLocked(int userId, String reason) {
        if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL
                && mTopAction == null) {
            // We are running in factory test mode, but unable to find
            // the factory test app, so just sit around displaying the
            // error message and don't try to start anything.
            return false;
        }
        Intent intent = getHomeIntent();
        ActivityInfo aInfo = resolveActivityInfo(intent, STOCK_PM_FLAGS, userId);
        if (aInfo != null) {
            intent.setComponent(new ComponentName(aInfo.applicationInfo.packageName, aInfo.name));
            // Don't do this if the home app is currently being
            // instrumented.
            aInfo = new ActivityInfo(aInfo);
            aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
            ProcessRecord app = getProcessRecordLocked(aInfo.processName,
                    aInfo.applicationInfo.uid, true);
            if (app == null || app.instrumentationClass == null) {
                intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
                mActivityStarter.startHomeActivityLocked(intent, aInfo, reason);
            }
        } else {
            Slog.wtf(TAG, "No home screen found for " + intent, new Throwable());
        }

        return true;
    }

    Intent getHomeIntent() {
        Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
        intent.setComponent(mTopComponent);
        intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
        if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
            intent.addCategory(Intent.CATEGORY_HOME);
        }
        return intent;
    }

    private ActivityInfo resolveActivityInfo(Intent intent, int flags, int userId) {
        ActivityInfo ai = null;
        ComponentName comp = intent.getComponent();
        try {
            if (comp != null) {
                // Factory test.
                ai = AppGlobals.getPackageManager().getActivityInfo(comp, flags, userId);
            } else {
                ResolveInfo info = AppGlobals.getPackageManager().resolveIntent(
                        intent,
                        intent.resolveTypeIfNeeded(mContext.getContentResolver()),
                        flags, userId);

                if (info != null) {
                    ai = info.activityInfo;
                }
            }
        } catch (RemoteException e) {
            // ignore
        }

        return ai;
    }

这个方法的作用就是去启动Launcher

我们知道Launcher其实也是一个特殊的apk,系统通过调用getHomeIntent获得启动Launcher所需要的Intent,之后通过mActivityStarter的startHomeActivityLocked方法启动Launcher,成功启动后手机桌面就展现在我们面前

版权声明:本文为博主原创文章,未经博主允许不得转载。

Android系统启动流程总览

即将开始

Android Launcher 分析

1. Launcher的启动过程 从网络上找了一段关于Launcher的启动过程的文章,作为学习Launcher的背景知识: Linux kernel启动以后会通过app_main进程来初始化an...

安卓系统服务10个实例

  • 2015年08月30日 02:00
  • 3MB
  • 下载

Cloud Foundry参赛博文——CLOUD FOUNDRY启动流程及为其添加系统服务

前提 已经正确使用dev_setup安装Cloud Foundry 启动流程 1.流程分析 通过dev_setup安装的Cloud Foundry可以通过以下代码启动 ~...

Ubuntu启动流程及系统服务设置

Ubuntu启动流程及系统服务设置启动流程 ======== Linux系统主要通过以下步骤启动: 1、读取MBR的信息,启动Boot Manager Windows使用NTLDR作为Boot...

安卓Service系统服务

引言:安卓的系统服务 首先获取系统服务的话是通过Context.getSystemSerview获取的,他需要一个字符串参数,也就是系统自带的服务ID,这个ID在安卓平台中是唯一的,你们可以在Audi...

关于android 7.0系统怎么添加自定义的系统服务

1  \frameworks\base\core\java\android\content\Context.java 添加一个服务名称 eg:          public static final...
  • ieiqny1
  • ieiqny1
  • 2017年12月07日 17:28
  • 14

如何增加系统服务启动项

  • 2009年07月02日 16:59
  • 26KB
  • 下载

bat文件启动jar包做成Windows系统服务

此次项目使用的是Win7系统 at文件[含有启动jar包]做成系统服务 Bat文件内容: cd d:/test/ echo in success! ping 127.1 > test11log.t...
  • jj88888
  • jj88888
  • 2015年11月19日 13:22
  • 3505
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:安卓7.0 系统服务启动流程
举报原因:
原因补充:

(最多只允许输入30个字)