Android启动续-------SystemSever启动

诚如上一篇,我们说到Zygote的启动,我们可以看到 目录(/android/4.4/frameworks/base/core/java/com/android/internal/os/ZygoteInit.java)
public class ZygoteInit {public static void main(String argv[]) {        try {            // Start profiling the zygote initialization.            SamplingProfilerIntegration.start();           registerZygoteSocket();            EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_START,                SystemClock.uptimeMillis());            preload();            EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_END,                SystemClock.uptimeMillis());            // Finish profiling the zygote initialization.            SamplingProfilerIntegration.writeZygoteSnapshot();            // Do an initial gc to clean up after startup            gc();            // Disable tracing so that forked processes do not inherit stale tracing tags from            // Zygote.            Trace.setTracingEnabled(false);            // If requested, start system server directly from Zygote            if (argv.length != 2) {                throw new RuntimeException(argv[0] + USAGE_STRING);            }            if (argv[1].equals("start-system-server")) {                startSystemServer();            } else if (!argv[1].equals("")) {                throw new RuntimeException(argv[0] + USAGE_STRING);            }            Log.i(TAG, "Accepting command socket connections");            runSelectLoop();            closeServerSocket();        } catch (MethodAndArgsCaller caller) {           caller.run();        } catch (RuntimeException ex) {            Log.e(TAG, "Zygote died with exception", ex);            closeServerSocket();            throw ex;        }    }}

毫无疑问,这里我们的重点在
startSystemServer();

目录/android/4.4/frameworks/base/services/java/com/android/server/SystemServer.java
      class ServerThread {80    private static final String TAG = "SystemServer";81    private static final String ENCRYPTING_STATE = "trigger_restart_min_framework";82    private static final String ENCRYPTED_STATE = "1";8384    ContentResolver mContentResolver;8586    void reportWtf(String msg, Throwable e) {87        Slog.w(TAG, "***********************************************");88        Log.wtf(TAG, "BOOT FAILURE " + msg, e);89    }9091    public void initAndLoop() {92        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN,93            SystemClock.uptimeMillis());9495        Looper.prepareMainLooper();9697        android.os.Process.setThreadPriority(98                android.os.Process.THREAD_PRIORITY_FOREGROUND);99100        BinderInternal.disableBackgroundScheduling(true);101        android.os.Process.setCanSelfBackground(false);102103        // Check whether we failed to shut down last time we tried.104        {105            final String shutdownAction = SystemProperties.get(106                    ShutdownThread.SHUTDOWN_ACTION_PROPERTY, "");107            if (shutdownAction != null && shutdownAction.length() > 0) {108                boolean reboot = (shutdownAction.charAt(0) == '1');109110                final String reason;111                if (shutdownAction.length() > 1) {112                    reason = shutdownAction.substring(1, shutdownAction.length());113                } else {114                    reason = null;115                }116117                ShutdownThread.rebootOrShutdown(reboot, reason);118            }119        }120121        String factoryTestStr = SystemProperties.get("ro.factorytest");122        int factoryTest = "".equals(factoryTestStr) ? SystemServer.FACTORY_TEST_OFF123                : Integer.parseInt(factoryTestStr);124        final boolean headless = "1".equals(SystemProperties.get("ro.config.headless", "0"));125126        Installer installer = null;127        AccountManagerService accountManager = null;128        ContentService contentService = null;129        LightsService lights = null;130        PowerManagerService power = null;131        DisplayManagerService display = null;132        BatteryService battery = null;133        VibratorService vibrator = null;134        AlarmManagerService alarm = null;135        MountService mountService = null;136        NetworkManagementService networkManagement = null;137        NetworkStatsService networkStats = null;138        NetworkPolicyManagerService networkPolicy = null;139        ConnectivityService connectivity = null;140        WifiP2pService wifiP2p = null;141        WifiService wifi = null;142        NsdService serviceDiscovery= null;143        IPackageManager pm = null;144        Context context = null;145        WindowManagerService wm = null;146        BluetoothManagerService bluetooth = null;147        DockObserver dock = null;148        UsbService usb = null;149        SerialService serial = null;150        TwilightService twilight = null;151        UiModeManagerService uiMode = null;152        RecognitionManagerService recognition = null;153        NetworkTimeUpdateService networkTimeUpdater = null;154        CommonTimeManagementService commonTimeMgmtService = null;155        InputManagerService inputManager = null;156        TelephonyRegistry telephonyRegistry = null;157        ConsumerIrService consumerIr = null;158159        // Create a handler thread just for the window manager to enjoy.160        HandlerThread wmHandlerThread = new HandlerThread("WindowManager");161        wmHandlerThread.start();162        Handler wmHandler = new Handler(wmHandlerThread.getLooper());163        wmHandler.post(new Runnable() {164            @Override165            public void run() {166                //Looper.myLooper().setMessageLogging(new LogPrinter(167                //        android.util.Log.DEBUG, TAG, android.util.Log.LOG_ID_SYSTEM));168                android.os.Process.setThreadPriority(169                        android.os.Process.THREAD_PRIORITY_DISPLAY);170                android.os.Process.setCanSelfBackground(false);171172                // For debug builds, log event loop stalls to dropbox for analysis.173                if (StrictMode.conditionallyEnableDebugLogging()) {174                    Slog.i(TAG, "Enabled StrictMode logging for WM Looper");175                }176            }177        });178179        // bootstrap services180        boolean onlyCore = false;181        boolean firstBoot = false;182        try {183            // Wait for installd to finished starting up so that it has a chance to184            // create critical directories such as /data/user with the appropriate185            // permissions.  We need this to complete before we initialize other services.186            Slog.i(TAG, "Waiting for installd to be ready.");187            installer = new Installer();188            installer.ping();189190            Slog.i(TAG, "Power Manager");191            power = new PowerManagerService();192            ServiceManager.addService(Context.POWER_SERVICE, power);193194            Slog.i(TAG, "Activity Manager");195            context = ActivityManagerService.main(factoryTest);196        } catch (RuntimeException e) {197            Slog.e("System", "******************************************");198            Slog.e("System", "************ Failure starting bootstrap service", e);199        }200201        boolean disableStorage = SystemProperties.getBoolean("config.disable_storage", false);202        boolean disableMedia = SystemProperties.getBoolean("config.disable_media", false);203        boolean disableBluetooth = SystemProperties.getBoolean("config.disable_bluetooth", false);204        boolean disableTelephony = SystemProperties.getBoolean("config.disable_telephony", false);205        boolean disableLocation = SystemProperties.getBoolean("config.disable_location", false);206        boolean disableSystemUI = SystemProperties.getBoolean("config.disable_systemui", false);207        boolean disableNonCoreServices = SystemProperties.getBoolean("config.disable_noncore", false);208        boolean disableNetwork = SystemProperties.getBoolean("config.disable_network", false);209210        try {211            Slog.i(TAG, "Display Manager");212            display = new DisplayManagerService(context, wmHandler);213            ServiceManager.addService(Context.DISPLAY_SERVICE, display, true);214215            Slog.i(TAG, "Telephony Registry");216            telephonyRegistry = new TelephonyRegistry(context);217            ServiceManager.addService("telephony.registry", telephonyRegistry);218219            Slog.i(TAG, "Scheduling Policy");220            ServiceManager.addService("scheduling_policy", new SchedulingPolicyService());221222            AttributeCache.init(context);223224            if (!display.waitForDefaultDisplay()) {225                reportWtf("Timeout waiting for default display to be initialized.",226                        new Throwable());227            }228229            Slog.i(TAG, "Package Manager");230            // Only run "core" apps if we're encrypting the device.231            String cryptState = SystemProperties.get("vold.decrypt");232            if (ENCRYPTING_STATE.equals(cryptState)) {233                Slog.w(TAG, "Detected encryption in progress - only parsing core apps");234                onlyCore = true;235            } else if (ENCRYPTED_STATE.equals(cryptState)) {236                Slog.w(TAG, "Device encrypted - only parsing core apps");237                onlyCore = true;238            }239240            pm = PackageManagerService.main(context, installer,241                    factoryTest != SystemServer.FACTORY_TEST_OFF,242                    onlyCore);243            try {244                firstBoot = pm.isFirstBoot();245            } catch (RemoteException e) {246            }247248            ActivityManagerService.setSystemProcess();249250            Slog.i(TAG, "Entropy Mixer");251            ServiceManager.addService("entropy", new EntropyMixer(context));252253            Slog.i(TAG, "User Service");254            ServiceManager.addService(Context.USER_SERVICE,255                    UserManagerService.getInstance());256257            mContentResolver = context.getContentResolver();258259            // The AccountManager must come before the ContentService260            try {261                // TODO: seems like this should be disable-able, but req'd by ContentService262                Slog.i(TAG, "Account Manager");263                accountManager = new AccountManagerService(context);264                ServiceManager.addService(Context.ACCOUNT_SERVICE, accountManager);265            } catch (Throwable e) {266                Slog.e(TAG, "Failure starting Account Manager", e);267            }268269            Slog.i(TAG, "Content Manager");270            contentService = ContentService.main(context,271                    factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL);272273            Slog.i(TAG, "System Content Providers");274            ActivityManagerService.installSystemProviders();275276            Slog.i(TAG, "Lights Service");277            lights = new LightsService(context);278279            Slog.i(TAG, "Battery Service");280            battery = new BatteryService(context, lights);281            ServiceManager.addService("battery", battery);282283            Slog.i(TAG, "Vibrator Service");284            vibrator = new VibratorService(context);285            ServiceManager.addService("vibrator", vibrator);286287            Slog.i(TAG, "Consumer IR Service");288            consumerIr = new ConsumerIrService(context);289            ServiceManager.addService(Context.CONSUMER_IR_SERVICE, consumerIr);290291            // only initialize the power service after we have started the292            // lights service, content providers and the battery service.293            power.init(context, lights, ActivityManagerService.self(), battery,294                    BatteryStatsService.getService(),295                    ActivityManagerService.self().getAppOpsService(), display);296297            Slog.i(TAG, "Alarm Manager");298            alarm = new AlarmManagerService(context);299            ServiceManager.addService(Context.ALARM_SERVICE, alarm);300301            Slog.i(TAG, "Init Watchdog");302            Watchdog.getInstance().init(context, battery, power, alarm,303                    ActivityManagerService.self());304            Watchdog.getInstance().addThread(wmHandler, "WindowManager thread");305306            Slog.i(TAG, "Input Manager");307            inputManager = new InputManagerService(context, wmHandler);308309            Slog.i(TAG, "Window Manager");310            wm = WindowManagerService.main(context, power, display, inputManager,311                    wmHandler, factoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL,312                    !firstBoot, onlyCore);313            ServiceManager.addService(Context.WINDOW_SERVICE, wm);314            ServiceManager.addService(Context.INPUT_SERVICE, inputManager);315316            ActivityManagerService.self().setWindowManager(wm);317318            inputManager.setWindowManagerCallbacks(wm.getInputMonitor());319            inputManager.start();320321            display.setWindowManager(wm);322            display.setInputManager(inputManager);323324            // Skip Bluetooth if we have an emulator kernel325            // TODO: Use a more reliable check to see if this product should326            // support Bluetooth - see bug 988521327            if (SystemProperties.get("ro.kernel.qemu").equals("1")) {328                Slog.i(TAG, "No Bluetooh Service (emulator)");329            } else if (factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {330                Slog.i(TAG, "No Bluetooth Service (factory test)");331            } else if (!context.getPackageManager().hasSystemFeature332                       (PackageManager.FEATURE_BLUETOOTH)) {333                Slog.i(TAG, "No Bluetooth Service (Bluetooth Hardware Not Present)");334            } else if (disableBluetooth) {335                Slog.i(TAG, "Bluetooth Service disabled by config");336            } else {337                Slog.i(TAG, "Bluetooth Manager Service");338                bluetooth = new BluetoothManagerService(context);339                ServiceManager.addService(BluetoothAdapter.BLUETOOTH_MANAGER_SERVICE, bluetooth);340            }341        } catch (RuntimeException e) {342            Slog.e("System", "******************************************");343            Slog.e("System", "************ Failure starting core service", e);344        }345346        DevicePolicyManagerService devicePolicy = null;347        StatusBarManagerService statusBar = null;348        InputMethodManagerService imm = null;349        AppWidgetService appWidget = null;350        NotificationManagerService notification = null;351        WallpaperManagerService wallpaper = null;352        LocationManagerService location = null;353        CountryDetectorService countryDetector = null;354        TextServicesManagerService tsms = null;355        LockSettingsService lockSettings = null;356        DreamManagerService dreamy = null;357        AssetAtlasService atlas = null;358        PrintManagerService printManager = null;359360        // Bring up services needed for UI.361        if (factoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {362            //if (!disableNonCoreServices) { // TODO: View depends on these; mock them?363            if (true) {364                try {365                    Slog.i(TAG, "Input Method Service");366                    imm = new InputMethodManagerService(context, wm);367                    ServiceManager.addService(Context.INPUT_METHOD_SERVICE, imm);368                } catch (Throwable e) {369                    reportWtf("starting Input Manager Service", e);370                }371372                try {373                    Slog.i(TAG, "Accessibility Manager");374                    ServiceManager.addService(Context.ACCESSIBILITY_SERVICE,375                            new AccessibilityManagerService(context));376                } catch (Throwable e) {377                    reportWtf("starting Accessibility Manager", e);378                }379            }380        }381382        try {383            wm.displayReady();384        } catch (Throwable e) {385            reportWtf("making display ready", e);386        }387388        try {389            pm.performBootDexOpt();390        } catch (Throwable e) {391            reportWtf("performing boot dexopt", e);392        }393394        try {395            ActivityManagerNative.getDefault().showBootMessage(396                    context.getResources().getText(397                            com.android.internal.R.string.android_upgrading_starting_apps),398                            false);399        } catch (RemoteException e) {400        }401402        if (factoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {403            if (!disableStorage &&404                !"0".equals(SystemProperties.get("system_init.startmountservice"))) {405                try {406                    /*407                     * NotificationManagerService is dependant on MountService,408                     * (for media / usb notifications) so we must start MountService first.409                     */410                    Slog.i(TAG, "Mount Service");411                    mountService = new MountService(context);412                    ServiceManager.addService("mount", mountService);413                } catch (Throwable e) {414                    reportWtf("starting Mount Service", e);415                }416            }417418            if (!disableNonCoreServices) {419                try {420                    Slog.i(TAG,  "LockSettingsService");421                    lockSettings = new LockSettingsService(context);422                    ServiceManager.addService("lock_settings", lockSettings);423                } catch (Throwable e) {424                    reportWtf("starting LockSettingsService service", e);425                }426427                try {428                    Slog.i(TAG, "Device Policy");429                    devicePolicy = new DevicePolicyManagerService(context);430                    ServiceManager.addService(Context.DEVICE_POLICY_SERVICE, devicePolicy);431                } catch (Throwable e) {432                    reportWtf("starting DevicePolicyService", e);433                }434            }435436            if (!disableSystemUI) {437                try {438                    Slog.i(TAG, "Status Bar");439                    statusBar = new StatusBarManagerService(context, wm);440                    ServiceManager.addService(Context.STATUS_BAR_SERVICE, statusBar);441                } catch (Throwable e) {442                    reportWtf("starting StatusBarManagerService", e);443                }444            }445446            if (!disableNonCoreServices) {447                try {448                    Slog.i(TAG, "Clipboard Service");449                    ServiceManager.addService(Context.CLIPBOARD_SERVICE,450                            new ClipboardService(context));451                } catch (Throwable e) {452                    reportWtf("starting Clipboard Service", e);453                }454            }455456            if (!disableNetwork) {457                try {458                    Slog.i(TAG, "NetworkManagement Service");459                    networkManagement = NetworkManagementService.create(context);460                    ServiceManager.addService(Context.NETWORKMANAGEMENT_SERVICE, networkManagement);461                } catch (Throwable e) {462                    reportWtf("starting NetworkManagement Service", e);463                }464            }465466            if (!disableNonCoreServices) {467                try {468                    Slog.i(TAG, "Text Service Manager Service");469                    tsms = new TextServicesManagerService(context);470                    ServiceManager.addService(Context.TEXT_SERVICES_MANAGER_SERVICE, tsms);471                } catch (Throwable e) {472                    reportWtf("starting Text Service Manager Service", e);473                }474            }475476            if (!disableNetwork) {477                try {478                    Slog.i(TAG, "NetworkStats Service");479                    networkStats = new NetworkStatsService(context, networkManagement, alarm);480                    ServiceManager.addService(Context.NETWORK_STATS_SERVICE, networkStats);481                } catch (Throwable e) {482                    reportWtf("starting NetworkStats Service", e);483                }484485                try {486                    Slog.i(TAG, "NetworkPolicy Service");487                    networkPolicy = new NetworkPolicyManagerService(488                            context, ActivityManagerService.self(), power,489                            networkStats, networkManagement);490                    ServiceManager.addService(Context.NETWORK_POLICY_SERVICE, networkPolicy);491                } catch (Throwable e) {492                    reportWtf("starting NetworkPolicy Service", e);493                }494495               try {496                    Slog.i(TAG, "Wi-Fi P2pService");497                    wifiP2p = new WifiP2pService(context);498                    ServiceManager.addService(Context.WIFI_P2P_SERVICE, wifiP2p);499                } catch (Throwable e) {500                    reportWtf("starting Wi-Fi P2pService", e);501                }502503               try {504                    Slog.i(TAG, "Wi-Fi Service");505                    wifi = new WifiService(context);506                    ServiceManager.addService(Context.WIFI_SERVICE, wifi);507                } catch (Throwable e) {508                    reportWtf("starting Wi-Fi Service", e);509                }510511                try {512                    Slog.i(TAG, "Connectivity Service");513                    connectivity = new ConnectivityService(514                            context, networkManagement, networkStats, networkPolicy);515                    ServiceManager.addService(Context.CONNECTIVITY_SERVICE, connectivity);516                    networkStats.bindConnectivityManager(connectivity);517                    networkPolicy.bindConnectivityManager(connectivity);518519                    wifiP2p.connectivityServiceReady();520                    wifi.checkAndStartWifi();521                } catch (Throwable e) {522                    reportWtf("starting Connectivity Service", e);523                }524525                try {526                    Slog.i(TAG, "Network Service Discovery Service");527                    serviceDiscovery = NsdService.create(context);528                    ServiceManager.addService(529                            Context.NSD_SERVICE, serviceDiscovery);530                } catch (Throwable e) {531                    reportWtf("starting Service Discovery Service", e);532                }533            }534535            if (!disableNonCoreServices) {536                try {537                    Slog.i(TAG, "UpdateLock Service");538                    ServiceManager.addService(Context.UPDATE_LOCK_SERVICE,539                            new UpdateLockService(context));540                } catch (Throwable e) {541                    reportWtf("starting UpdateLockService", e);542                }543            }544545            /*546             * MountService has a few dependencies: Notification Manager and547             * AppWidget Provider. Make sure MountService is completely started548             * first before continuing.549             */550            if (mountService != null && !onlyCore) {551                mountService.waitForAsecScan();552            }553554            try {555                if (accountManager != null)556                    accountManager.systemReady();557            } catch (Throwable e) {558                reportWtf("making Account Manager Service ready", e);559            }560561            try {562                if (contentService != null)563                    contentService.systemReady();564            } catch (Throwable e) {565                reportWtf("making Content Service ready", e);566            }567568            try {569                Slog.i(TAG, "Notification Manager");570                notification = new NotificationManagerService(context, statusBar, lights);571                ServiceManager.addService(Context.NOTIFICATION_SERVICE, notification);572                networkPolicy.bindNotificationManager(notification);573            } catch (Throwable e) {574                reportWtf("starting Notification Manager", e);575            }576577            try {578                Slog.i(TAG, "Device Storage Monitor");579                ServiceManager.addService(DeviceStorageMonitorService.SERVICE,580                        new DeviceStorageMonitorService(context));581            } catch (Throwable e) {582                reportWtf("starting DeviceStorageMonitor service", e);583            }584585            if (!disableLocation) {586                try {587                    Slog.i(TAG, "Location Manager");588                    location = new LocationManagerService(context);589                    ServiceManager.addService(Context.LOCATION_SERVICE, location);590                } catch (Throwable e) {591                    reportWtf("starting Location Manager", e);592                }593594                try {595                    Slog.i(TAG, "Country Detector");596                    countryDetector = new CountryDetectorService(context);597                    ServiceManager.addService(Context.COUNTRY_DETECTOR, countryDetector);598                } catch (Throwable e) {599                    reportWtf("starting Country Detector", e);600                }601            }602603            if (!disableNonCoreServices) {604                try {605                    Slog.i(TAG, "Search Service");606                    ServiceManager.addService(Context.SEARCH_SERVICE,607                            new SearchManagerService(context));608                } catch (Throwable e) {609                    reportWtf("starting Search Service", e);610                }611            }612613            try {614                Slog.i(TAG, "DropBox Service");615                ServiceManager.addService(Context.DROPBOX_SERVICE,616                        new DropBoxManagerService(context, new File("/data/system/dropbox")));617            } catch (Throwable e) {618                reportWtf("starting DropBoxManagerService", e);619            }620621            if (!disableNonCoreServices && context.getResources().getBoolean(622                        R.bool.config_enableWallpaperService)) {623                try {624                    Slog.i(TAG, "Wallpaper Service");625                    if (!headless) {626                        wallpaper = new WallpaperManagerService(context);627                        ServiceManager.addService(Context.WALLPAPER_SERVICE, wallpaper);628                    }629                } catch (Throwable e) {630                    reportWtf("starting Wallpaper Service", e);631                }632            }633634            if (!disableMedia && !"0".equals(SystemProperties.get("system_init.startaudioservice"))) {635                try {636                    Slog.i(TAG, "Audio Service");637                    ServiceManager.addService(Context.AUDIO_SERVICE, new AudioService(context));638                } catch (Throwable e) {639                    reportWtf("starting Audio Service", e);640                }641            }642643            if (!disableNonCoreServices) {644                try {645                    Slog.i(TAG, "Dock Observer");646                    // Listen for dock station changes647                    dock = new DockObserver(context);648                } catch (Throwable e) {649                    reportWtf("starting DockObserver", e);650                }651            }652653            if (!disableMedia) {654                try {655                    Slog.i(TAG, "Wired Accessory Manager");656                    // Listen for wired headset changes657                    inputManager.setWiredAccessoryCallbacks(658                            new WiredAccessoryManager(context, inputManager));659                } catch (Throwable e) {660                    reportWtf("starting WiredAccessoryManager", e);661                }662            }663664            if (!disableNonCoreServices) {665                try {666                    Slog.i(TAG, "USB Service");667                    // Manage USB host and device support668                    usb = new UsbService(context);669                    ServiceManager.addService(Context.USB_SERVICE, usb);670                } catch (Throwable e) {671                    reportWtf("starting UsbService", e);672                }673674                try {675                    Slog.i(TAG, "Serial Service");676                    // Serial port support677                    serial = new SerialService(context);678                    ServiceManager.addService(Context.SERIAL_SERVICE, serial);679                } catch (Throwable e) {680                    Slog.e(TAG, "Failure starting SerialService", e);681                }682            }683684            try {685                Slog.i(TAG, "Twilight Service");686                twilight = new TwilightService(context);687            } catch (Throwable e) {688                reportWtf("starting TwilightService", e);689            }690691            try {692                Slog.i(TAG, "UI Mode Manager Service");693                // Listen for UI mode changes694                uiMode = new UiModeManagerService(context, twilight);695            } catch (Throwable e) {696                reportWtf("starting UiModeManagerService", e);697            }698699            if (!disableNonCoreServices) {700                try {701                    Slog.i(TAG, "Backup Service");702                    ServiceManager.addService(Context.BACKUP_SERVICE,703                            new BackupManagerService(context));704                } catch (Throwable e) {705                    Slog.e(TAG, "Failure starting Backup Service", e);706                }707708                try {709                    Slog.i(TAG, "AppWidget Service");710                    appWidget = new AppWidgetService(context);711                    ServiceManager.addService(Context.APPWIDGET_SERVICE, appWidget);712                } catch (Throwable e) {713                    reportWtf("starting AppWidget Service", e);714                }715716                try {717                    Slog.i(TAG, "Recognition Service");718                    recognition = new RecognitionManagerService(context);719                } catch (Throwable e) {720                    reportWtf("starting Recognition Service", e);721                }722            }723724            try {725                Slog.i(TAG, "DiskStats Service");726                ServiceManager.addService("diskstats", new DiskStatsService(context));727            } catch (Throwable e) {728                reportWtf("starting DiskStats Service", e);729            }730731            try {732                // need to add this service even if SamplingProfilerIntegration.isEnabled()733                // is false, because it is this service that detects system property change and734                // turns on SamplingProfilerIntegration. Plus, when sampling profiler doesn't work,735                // there is little overhead for running this service.736                Slog.i(TAG, "SamplingProfiler Service");737                ServiceManager.addService("samplingprofiler",738                            new SamplingProfilerService(context));739            } catch (Throwable e) {740                reportWtf("starting SamplingProfiler Service", e);741            }742743            if (!disableNetwork) {744                try {745                    Slog.i(TAG, "NetworkTimeUpdateService");746                    networkTimeUpdater = new NetworkTimeUpdateService(context);747                } catch (Throwable e) {748                    reportWtf("starting NetworkTimeUpdate service", e);749                }750            }751752            if (!disableMedia) {753                try {754                    Slog.i(TAG, "CommonTimeManagementService");755                    commonTimeMgmtService = new CommonTimeManagementService(context);756                    ServiceManager.addService("commontime_management", commonTimeMgmtService);757                } catch (Throwable e) {758                    reportWtf("starting CommonTimeManagementService service", e);759                }760            }761762            if (!disableNetwork) {763                try {764                    Slog.i(TAG, "CertBlacklister");765                    CertBlacklister blacklister = new CertBlacklister(context);766                } catch (Throwable e) {767                    reportWtf("starting CertBlacklister", e);768                }769            }770771            if (!disableNonCoreServices &&772                context.getResources().getBoolean(R.bool.config_dreamsSupported)) {773                try {774                    Slog.i(TAG, "Dreams Service");775                    // Dreams (interactive idle-time views, a/k/a screen savers)776                    dreamy = new DreamManagerService(context, wmHandler);777                    ServiceManager.addService(DreamService.DREAM_SERVICE, dreamy);778                } catch (Throwable e) {779                    reportWtf("starting DreamManagerService", e);780                }781            }782783            if (!disableNonCoreServices) {784                try {785                    Slog.i(TAG, "Assets Atlas Service");786                    atlas = new AssetAtlasService(context);787                    ServiceManager.addService(AssetAtlasService.ASSET_ATLAS_SERVICE, atlas);788                } catch (Throwable e) {789                    reportWtf("starting AssetAtlasService", e);790                }791            }792793            try {794                Slog.i(TAG, "IdleMaintenanceService");795                new IdleMaintenanceService(context, battery);796            } catch (Throwable e) {797                reportWtf("starting IdleMaintenanceService", e);798            }799800            try {801                Slog.i(TAG, "Print Service");802                printManager = new PrintManagerService(context);803                ServiceManager.addService(Context.PRINT_SERVICE, printManager);804            } catch (Throwable e) {805                reportWtf("starting Print Service", e);806            }807        }808809        // Before things start rolling, be sure we have decided whether810        // we are in safe mode.811        final boolean safeMode = wm.detectSafeMode();812        if (safeMode) {813            ActivityManagerService.self().enterSafeMode();814            // Post the safe mode state in the Zygote class815            Zygote.systemInSafeMode = true;816            // Disable the JIT for the system_server process817            VMRuntime.getRuntime().disableJitCompilation();818        } else {819            // Enable the JIT for the system_server process820            VMRuntime.getRuntime().startJitCompilation();821        }822823        // It is now time to start up the app processes...824825        try {826            vibrator.systemReady();827        } catch (Throwable e) {828            reportWtf("making Vibrator Service ready", e);829        }830831        if (lockSettings != null) {832            try {833                lockSettings.systemReady();834            } catch (Throwable e) {835                reportWtf("making Lock Settings Service ready", e);836            }837        }838839        if (devicePolicy != null) {840            try {841                devicePolicy.systemReady();842            } catch (Throwable e) {843                reportWtf("making Device Policy Service ready", e);844            }845        }846847        if (notification != null) {848            try {849                notification.systemReady();850            } catch (Throwable e) {851                reportWtf("making Notification Service ready", e);852            }853        }854855        try {856            wm.systemReady();857        } catch (Throwable e) {858            reportWtf("making Window Manager Service ready", e);859        }860861        if (safeMode) {862            ActivityManagerService.self().showSafeModeOverlay();863        }864865        // Update the configuration for this context by hand, because we're going866        // to start using it before the config change done in wm.systemReady() will867        // propagate to it.868        Configuration config = wm.computeNewConfiguration();869        DisplayMetrics metrics = new DisplayMetrics();870        WindowManager w = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);871        w.getDefaultDisplay().getMetrics(metrics);872        context.getResources().updateConfiguration(config, metrics);873874        try {875            power.systemReady(twilight, dreamy);876        } catch (Throwable e) {877            reportWtf("making Power Manager Service ready", e);878        }879880        try {881            pm.systemReady();882        } catch (Throwable e) {883            reportWtf("making Package Manager Service ready", e);884        }885886        try {887            display.systemReady(safeMode, onlyCore);888        } catch (Throwable e) {889            reportWtf("making Display Manager Service ready", e);890        }891892        // These are needed to propagate to the runnable below.893        final Context contextF = context;894        final MountService mountServiceF = mountService;895        final BatteryService batteryF = battery;896        final NetworkManagementService networkManagementF = networkManagement;897        final NetworkStatsService networkStatsF = networkStats;898        final NetworkPolicyManagerService networkPolicyF = networkPolicy;899        final ConnectivityService connectivityF = connectivity;900        final DockObserver dockF = dock;901        final UsbService usbF = usb;902        final TwilightService twilightF = twilight;903        final UiModeManagerService uiModeF = uiMode;904        final AppWidgetService appWidgetF = appWidget;905        final WallpaperManagerService wallpaperF = wallpaper;906        final InputMethodManagerService immF = imm;907        final RecognitionManagerService recognitionF = recognition;908        final LocationManagerService locationF = location;909        final CountryDetectorService countryDetectorF = countryDetector;910        final NetworkTimeUpdateService networkTimeUpdaterF = networkTimeUpdater;911        final CommonTimeManagementService commonTimeMgmtServiceF = commonTimeMgmtService;912        final TextServicesManagerService textServiceManagerServiceF = tsms;913        final StatusBarManagerService statusBarF = statusBar;914        final DreamManagerService dreamyF = dreamy;915        final AssetAtlasService atlasF = atlas;916        final InputManagerService inputManagerF = inputManager;917        final TelephonyRegistry telephonyRegistryF = telephonyRegistry;918        final PrintManagerService printManagerF = printManager;919920        // We now tell the activity manager it is okay to run third party921        // code.  It will call back into us once it has gotten to the state922        // where third party code can really run (but before it has actually923        // started launching the initial applications), for us to complete our924        // initialization.925        ActivityManagerService.self().systemReady(new Runnable() {926            public void run() {927                Slog.i(TAG, "Making services ready");928929                try {930                    ActivityManagerService.self().startObservingNativeCrashes();931                } catch (Throwable e) {932                    reportWtf("observing native crashes", e);933                }934                if (!headless) {935                    startSystemUi(contextF);936                }937                try {938                    if (mountServiceF != null) mountServiceF.systemReady();939                } catch (Throwable e) {940                    reportWtf("making Mount Service ready", e);941                }942                try {943                    if (batteryF != null) batteryF.systemReady();944                } catch (Throwable e) {945                    reportWtf("making Battery Service ready", e);946                }947                try {948                    if (networkManagementF != null) networkManagementF.systemReady();949                } catch (Throwable e) {950                    reportWtf("making Network Managment Service ready", e);951                }952                try {953                    if (networkStatsF != null) networkStatsF.systemReady();954                } catch (Throwable e) {955                    reportWtf("making Network Stats Service ready", e);956                }957                try {958                    if (networkPolicyF != null) networkPolicyF.systemReady();959                } catch (Throwable e) {960                    reportWtf("making Network Policy Service ready", e);961                }962                try {963                    if (connectivityF != null) connectivityF.systemReady();964                } catch (Throwable e) {965                    reportWtf("making Connectivity Service ready", e);966                }967                try {968                    if (dockF != null) dockF.systemReady();969                } catch (Throwable e) {970                    reportWtf("making Dock Service ready", e);971                }972                try {973                    if (usbF != null) usbF.systemReady();974                } catch (Throwable e) {975                    reportWtf("making USB Service ready", e);976                }977                try {978                    if (twilightF != null) twilightF.systemReady();979                } catch (Throwable e) {980                    reportWtf("makin Twilight Service ready", e);981                }982                try {983                    if (uiModeF != null) uiModeF.systemReady();984                } catch (Throwable e) {985                    reportWtf("making UI Mode Service ready", e);986                }987                try {988                    if (recognitionF != null) recognitionF.systemReady();989                } catch (Throwable e) {990                    reportWtf("making Recognition Service ready", e);991                }992                Watchdog.getInstance().start();993994                // It is now okay to let the various system services start their995                // third party code...996997                try {998                    if (appWidgetF != null) appWidgetF.systemRunning(safeMode);999                } catch (Throwable e) {1000                    reportWtf("Notifying AppWidgetService running", e);1001                }1002                try {1003                    if (wallpaperF != null) wallpaperF.systemRunning();1004                } catch (Throwable e) {1005                    reportWtf("Notifying WallpaperService running", e);1006                }1007                try {1008                    if (immF != null) immF.systemRunning(statusBarF);1009                } catch (Throwable e) {1010                    reportWtf("Notifying InputMethodService running", e);1011                }1012                try {1013                    if (locationF != null) locationF.systemRunning();1014                } catch (Throwable e) {1015                    reportWtf("Notifying Location Service running", e);1016                }1017                try {1018                    if (countryDetectorF != null) countryDetectorF.systemRunning();1019                } catch (Throwable e) {1020                    reportWtf("Notifying CountryDetectorService running", e);1021                }1022                try {1023                    if (networkTimeUpdaterF != null) networkTimeUpdaterF.systemRunning();1024                } catch (Throwable e) {1025                    reportWtf("Notifying NetworkTimeService running", e);1026                }1027                try {1028                    if (commonTimeMgmtServiceF != null) commonTimeMgmtServiceF.systemRunning();1029                } catch (Throwable e) {1030                    reportWtf("Notifying CommonTimeManagementService running", e);1031                }1032                try {1033                    if (textServiceManagerServiceF != null)1034                        textServiceManagerServiceF.systemRunning();1035                } catch (Throwable e) {1036                    reportWtf("Notifying TextServicesManagerService running", e);1037                }1038                try {1039                    if (dreamyF != null) dreamyF.systemRunning();1040                } catch (Throwable e) {1041                    reportWtf("Notifying DreamManagerService running", e);1042                }1043                try {1044                    if (atlasF != null) atlasF.systemRunning();1045                } catch (Throwable e) {1046                    reportWtf("Notifying AssetAtlasService running", e);1047                }1048                try {1049                    // TODO(BT) Pass parameter to input manager1050                    if (inputManagerF != null) inputManagerF.systemRunning();1051                } catch (Throwable e) {1052                    reportWtf("Notifying InputManagerService running", e);1053                }10541055                try {1056                    if (telephonyRegistryF != null) telephonyRegistryF.systemRunning();1057                } catch (Throwable e) {1058                    reportWtf("Notifying TelephonyRegistry running", e);1059                }10601061                try {1062                    if (printManagerF != null) printManagerF.systemRuning();1063                } catch (Throwable e) {1064                    reportWtf("Notifying PrintManagerService running", e);1065                }1066            }1067        });10681069        // For debug builds, log event loop stalls to dropbox for analysis.1070        if (StrictMode.conditionallyEnableDebugLogging()) {1071            Slog.i(TAG, "Enabled StrictMode for system server main thread.");1072        }10731074        Looper.loop();1075        Slog.d(TAG, "System ServerThread is exiting!");1076    }10771078    static final void startSystemUi(Context context) {1079        Intent intent = new Intent();1080        intent.setComponent(new ComponentName("com.android.systemui",1081                    "com.android.systemui.SystemUIService"));1082        //Slog.d(TAG, "Starting service: " + intent);1083        context.startServiceAsUser(intent, UserHandle.OWNER);1084    }1085}10861087public class SystemServer {1088    private static final String TAG = "SystemServer";10891090    public static final int FACTORY_TEST_OFF = 0;1091    public static final int FACTORY_TEST_LOW_LEVEL = 1;1092    public static final int FACTORY_TEST_HIGH_LEVEL = 2;10931094    static Timer timer;1095    static final long SNAPSHOT_INTERVAL = 60 * 60 * 1000; // 1hr10961097    // The earliest supported time.  We pick one day into 1970, to1098    // give any timezone code room without going into negative time.1099    private static final long EARLIEST_SUPPORTED_TIME = 86400 * 1000;11001101    /**1102     * Called to initialize native system services.1103     */1104    private static native void nativeInit();11051106    public static void main(String[] args) {11071108        /*1109         * In case the runtime switched since last boot (such as when1110         * the old runtime was removed in an OTA), set the system1111         * property so that it is in sync. We can't do this in1112         * libnativehelper's JniInvocation::Init code where we already1113         * had to fallback to a different runtime because it is1114         * running as root and we need to be the system user to set1115         * the property. http://b/114631821116         */1117        SystemProperties.set("persist.sys.dalvik.vm.lib",1118                             VMRuntime.getRuntime().vmLibrary());11191120        if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {1121            // If a device's clock is before 1970 (before 0), a lot of1122            // APIs crash dealing with negative numbers, notably1123            // java.io.File#setLastModified, so instead we fake it and1124            // hope that time from cell towers or NTP fixes it1125            // shortly.1126            Slog.w(TAG, "System clock is before 1970; setting to 1970.");1127            SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);1128        }11291130        if (SamplingProfilerIntegration.isEnabled()) {1131            SamplingProfilerIntegration.start();1132            timer = new Timer();1133            timer.schedule(new TimerTask() {1134                @Override1135                public void run() {1136                    SamplingProfilerIntegration.writeSnapshot("system_server", null);1137                }1138            }, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL);1139        }11401141        // Mmmmmm... more memory!1142        dalvik.system.VMRuntime.getRuntime().clearGrowthLimit();11431144        // The system server has to run all of the time, so it needs to be1145        // as efficient as possible with its memory usage.1146        VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);11471148        Environment.setUserRequired(true);11491150        System.loadLibrary("android_servers");11511152        Slog.i(TAG, "Entered the Android system server!");11531154        // Initialize native services.1155        nativeInit();11561157        // This used to be its own separate thread, but now it is1158        // just the loop we run on the main thread.1159        ServerThread thr = new ServerThread();1160        thr.initAndLoop();1161    }1162}

这里,我们给出了全部的代码,但是很明显我们的重点在SystemSever中的main入口 前面一大堆关于Time 和Dalvik处理我们不管,我们只用关心
1159        ServerThread thr = new ServerThread();1160        thr.initAndLoop();
很明显,所有的系统服务都是在SeverThread中开启 我们进一步追踪到SeverThread中initAndLoop(),那么initAndLoop又是做什么的,查看源码很容易发现 基本上所有的系统服务都是在这里初始化 和SystemReady() 例如
    public void initAndLoop() {.......        BatteryService battery = null;        VibratorService vibrator = null;........        boolean disableTelephony = SystemProperties.getBoolean("config.disable_telephony", false);        boolean disableSystemUI = SystemProperties.getBoolean("config.disable_systemui", false);.........        try {......            telephonyRegistry = new TelephonyRegistry(context);            ServiceManager.addService("telephony.registry", telephonyRegistry);.......          }            battery = new BatteryService(context, lights);            ServiceManager.addService("battery", battery);.......            vibrator = new VibratorService(context);            ServiceManager.addService("vibrator", vibrator);....            if (!disableSystemUI) {                 try{                    statusBar = new StatusBarManagerService(context, wm);                    ServiceManager.addService(Context.STATUS_BAR_SERVICE, statusBar);                       }             }..........           try{            vibrator.systemReady();              }catch(Throwable e){            reportWtf("making Vibrator Service ready", e);                  }}

这里,我抽出最典型的VibratorService启动过程给打击看,这也就解释了为什么我们通过
WindowManager WM= (WindowManager)Context.getSystemService(Context.WINDOW_SERVICE); 
这种方式 获取系统服务(系统已经初始化完成)

同时,在这里我也想提醒大家,我们的SystemUI也是在这里初始化的
1078    static final void startSystemUi(Context context) {1079        Intent intent = new Intent();1080        intent.setComponent(new ComponentName("com.android.systemui",1081                    "com.android.systemui.SystemUIService"));1082        //Slog.d(TAG, "Starting service: " + intent);1083        context.startServiceAsUser(intent, UserHandle.OWNER);1084    }



更多相关文章

  1. 从零开始--系统深入学习android(实践-让我们开始写代码-Android框
  2. [Android 新特性] 改进明显 Android 4.4系统新特性解析
  3. Android图形系统的分析与移植--一、Android GUI系统简介
  4. android 获取系统硬件信息
  5. Android系统应用不支持读写存储
  6. android基础知识15:获得android系统信息03—PackageManager
  7. Android 编译系统

随机推荐

  1. Android 弹出键盘向上顶布局
  2. android 如何判断去电或来电已经接通
  3. Android Binder的使用和设计[android nat
  4. AndroidStudio试用
  5. Android opencore 2.02 howto
  6. Android(安卓)APK签名
  7. android style的使用
  8. 我的Android成长之路(11)----Android之Shar
  9. Caused by: com.android.tools.r8.Compil
  10. android Select at least one project