Android啓動續-------SystemSever啓動

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";
83
84    ContentResolver mContentResolver;
85
86    void reportWtf(String msg, Throwable e) {
87        Slog.w(TAG, "***********************************************");
88        Log.wtf(TAG, "BOOT FAILURE " + msg, e);
89    }
90
91    public void initAndLoop() {
92        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN,
93            SystemClock.uptimeMillis());
94
95        Looper.prepareMainLooper();
96
97        android.os.Process.setThreadPriority(
98                android.os.Process.THREAD_PRIORITY_FOREGROUND);
99
100        BinderInternal.disableBackgroundScheduling(true);
101        android.os.Process.setCanSelfBackground(false);
102
103        // 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');
109
110                final String reason;
111                if (shutdownAction.length() > 1) {
112                    reason = shutdownAction.substring(1, shutdownAction.length());
113                } else {
114                    reason = null;
115                }
116
117                ShutdownThread.rebootOrShutdown(reboot, reason);
118            }
119        }
120
121        String factoryTestStr = SystemProperties.get("ro.factorytest");
122        int factoryTest = "".equals(factoryTestStr) ? SystemServer.FACTORY_TEST_OFF
123                : Integer.parseInt(factoryTestStr);
124        final boolean headless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
125
126        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;
158
159        // 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            @Override
165            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);
171
172                // 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        });
178
179        // bootstrap services
180        boolean onlyCore = false;
181        boolean firstBoot = false;
182        try {
183            // Wait for installd to finished starting up so that it has a chance to
184            // create critical directories such as /data/user with the appropriate
185            // 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();
189
190            Slog.i(TAG, "Power Manager");
191            power = new PowerManagerService();
192            ServiceManager.addService(Context.POWER_SERVICE, power);
193
194            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        }
200
201        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);
209
210        try {
211            Slog.i(TAG, "Display Manager");
212            display = new DisplayManagerService(context, wmHandler);
213            ServiceManager.addService(Context.DISPLAY_SERVICE, display, true);
214
215            Slog.i(TAG, "Telephony Registry");
216            telephonyRegistry = new TelephonyRegistry(context);
217            ServiceManager.addService("telephony.registry", telephonyRegistry);
218
219            Slog.i(TAG, "Scheduling Policy");
220            ServiceManager.addService("scheduling_policy", new SchedulingPolicyService());
221
222            AttributeCache.init(context);
223
224            if (!display.waitForDefaultDisplay()) {
225                reportWtf("Timeout waiting for default display to be initialized.",
226                        new Throwable());
227            }
228
229            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            }
239
240            pm = PackageManagerService.main(context, installer,
241                    factoryTest != SystemServer.FACTORY_TEST_OFF,
242                    onlyCore);
243            try {
244                firstBoot = pm.isFirstBoot();
245            } catch (RemoteException e) {
246            }
247
248            ActivityManagerService.setSystemProcess();
249
250            Slog.i(TAG, "Entropy Mixer");
251            ServiceManager.addService("entropy", new EntropyMixer(context));
252
253            Slog.i(TAG, "User Service");
254            ServiceManager.addService(Context.USER_SERVICE,
255                    UserManagerService.getInstance());
256
257            mContentResolver = context.getContentResolver();
258
259            // The AccountManager must come before the ContentService
260            try {
261                // TODO: seems like this should be disable-able, but req'd by ContentService
262                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            }
268
269            Slog.i(TAG, "Content Manager");
270            contentService = ContentService.main(context,
271                    factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL);
272
273            Slog.i(TAG, "System Content Providers");
274            ActivityManagerService.installSystemProviders();
275
276            Slog.i(TAG, "Lights Service");
277            lights = new LightsService(context);
278
279            Slog.i(TAG, "Battery Service");
280            battery = new BatteryService(context, lights);
281            ServiceManager.addService("battery", battery);
282
283            Slog.i(TAG, "Vibrator Service");
284            vibrator = new VibratorService(context);
285            ServiceManager.addService("vibrator", vibrator);
286
287            Slog.i(TAG, "Consumer IR Service");
288            consumerIr = new ConsumerIrService(context);
289            ServiceManager.addService(Context.CONSUMER_IR_SERVICE, consumerIr);
290
291            // only initialize the power service after we have started the
292            // lights service, content providers and the battery service.
293            power.init(context, lights, ActivityManagerService.self(), battery,
294                    BatteryStatsService.getService(),
295                    ActivityManagerService.self().getAppOpsService(), display);
296
297            Slog.i(TAG, "Alarm Manager");
298            alarm = new AlarmManagerService(context);
299            ServiceManager.addService(Context.ALARM_SERVICE, alarm);
300
301            Slog.i(TAG, "Init Watchdog");
302            Watchdog.getInstance().init(context, battery, power, alarm,
303                    ActivityManagerService.self());
304            Watchdog.getInstance().addThread(wmHandler, "WindowManager thread");
305
306            Slog.i(TAG, "Input Manager");
307            inputManager = new InputManagerService(context, wmHandler);
308
309            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);
315
316            ActivityManagerService.self().setWindowManager(wm);
317
318            inputManager.setWindowManagerCallbacks(wm.getInputMonitor());
319            inputManager.start();
320
321            display.setWindowManager(wm);
322            display.setInputManager(inputManager);
323
324            // Skip Bluetooth if we have an emulator kernel
325            // TODO: Use a more reliable check to see if this product should
326            // support Bluetooth - see bug 988521
327            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().hasSystemFeature
332                       (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        }
345
346        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;
359
360        // 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                }
371
372                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        }
381
382        try {
383            wm.displayReady();
384        } catch (Throwable e) {
385            reportWtf("making display ready", e);
386        }
387
388        try {
389            pm.performBootDexOpt();
390        } catch (Throwable e) {
391            reportWtf("performing boot dexopt", e);
392        }
393
394        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        }
401
402        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            }
417
418            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                }
426
427                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            }
435
436            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            }
445
446            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            }
455
456            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            }
465
466            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            }
475
476            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                }
484
485                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                }
494
495               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                }
502
503               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                }
510
511                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);
518
519                    wifiP2p.connectivityServiceReady();
520                    wifi.checkAndStartWifi();
521                } catch (Throwable e) {
522                    reportWtf("starting Connectivity Service", e);
523                }
524
525                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            }
534
535            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            }
544
545            /*
546             * MountService has a few dependencies: Notification Manager and
547             * AppWidget Provider. Make sure MountService is completely started
548             * first before continuing.
549             */
550            if (mountService != null && !onlyCore) {
551                mountService.waitForAsecScan();
552            }
553
554            try {
555                if (accountManager != null)
556                    accountManager.systemReady();
557            } catch (Throwable e) {
558                reportWtf("making Account Manager Service ready", e);
559            }
560
561            try {
562                if (contentService != null)
563                    contentService.systemReady();
564            } catch (Throwable e) {
565                reportWtf("making Content Service ready", e);
566            }
567
568            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            }
576
577            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            }
584
585            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                }
593
594                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            }
602
603            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            }
612
613            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            }
620
621            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            }
633
634            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            }
642
643            if (!disableNonCoreServices) {
644                try {
645                    Slog.i(TAG, "Dock Observer");
646                    // Listen for dock station changes
647                    dock = new DockObserver(context);
648                } catch (Throwable e) {
649                    reportWtf("starting DockObserver", e);
650                }
651            }
652
653            if (!disableMedia) {
654                try {
655                    Slog.i(TAG, "Wired Accessory Manager");
656                    // Listen for wired headset changes
657                    inputManager.setWiredAccessoryCallbacks(
658                            new WiredAccessoryManager(context, inputManager));
659                } catch (Throwable e) {
660                    reportWtf("starting WiredAccessoryManager", e);
661                }
662            }
663
664            if (!disableNonCoreServices) {
665                try {
666                    Slog.i(TAG, "USB Service");
667                    // Manage USB host and device support
668                    usb = new UsbService(context);
669                    ServiceManager.addService(Context.USB_SERVICE, usb);
670                } catch (Throwable e) {
671                    reportWtf("starting UsbService", e);
672                }
673
674                try {
675                    Slog.i(TAG, "Serial Service");
676                    // Serial port support
677                    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            }
683
684            try {
685                Slog.i(TAG, "Twilight Service");
686                twilight = new TwilightService(context);
687            } catch (Throwable e) {
688                reportWtf("starting TwilightService", e);
689            }
690
691            try {
692                Slog.i(TAG, "UI Mode Manager Service");
693                // Listen for UI mode changes
694                uiMode = new UiModeManagerService(context, twilight);
695            } catch (Throwable e) {
696                reportWtf("starting UiModeManagerService", e);
697            }
698
699            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                }
707
708                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                }
715
716                try {
717                    Slog.i(TAG, "Recognition Service");
718                    recognition = new RecognitionManagerService(context);
719                } catch (Throwable e) {
720                    reportWtf("starting Recognition Service", e);
721                }
722            }
723
724            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            }
730
731            try {
732                // need to add this service even if SamplingProfilerIntegration.isEnabled()
733                // is false, because it is this service that detects system property change and
734                // 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            }
742
743            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            }
751
752            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            }
761
762            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            }
770
771            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            }
782
783            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            }
792
793            try {
794                Slog.i(TAG, "IdleMaintenanceService");
795                new IdleMaintenanceService(context, battery);
796            } catch (Throwable e) {
797                reportWtf("starting IdleMaintenanceService", e);
798            }
799
800            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        }
808
809        // Before things start rolling, be sure we have decided whether
810        // 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 class
815            Zygote.systemInSafeMode = true;
816            // Disable the JIT for the system_server process
817            VMRuntime.getRuntime().disableJitCompilation();
818        } else {
819            // Enable the JIT for the system_server process
820            VMRuntime.getRuntime().startJitCompilation();
821        }
822
823        // It is now time to start up the app processes...
824
825        try {
826            vibrator.systemReady();
827        } catch (Throwable e) {
828            reportWtf("making Vibrator Service ready", e);
829        }
830
831        if (lockSettings != null) {
832            try {
833                lockSettings.systemReady();
834            } catch (Throwable e) {
835                reportWtf("making Lock Settings Service ready", e);
836            }
837        }
838
839        if (devicePolicy != null) {
840            try {
841                devicePolicy.systemReady();
842            } catch (Throwable e) {
843                reportWtf("making Device Policy Service ready", e);
844            }
845        }
846
847        if (notification != null) {
848            try {
849                notification.systemReady();
850            } catch (Throwable e) {
851                reportWtf("making Notification Service ready", e);
852            }
853        }
854
855        try {
856            wm.systemReady();
857        } catch (Throwable e) {
858            reportWtf("making Window Manager Service ready", e);
859        }
860
861        if (safeMode) {
862            ActivityManagerService.self().showSafeModeOverlay();
863        }
864
865        // Update the configuration for this context by hand, because we're going
866        // to start using it before the config change done in wm.systemReady() will
867        // 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);
873
874        try {
875            power.systemReady(twilight, dreamy);
876        } catch (Throwable e) {
877            reportWtf("making Power Manager Service ready", e);
878        }
879
880        try {
881            pm.systemReady();
882        } catch (Throwable e) {
883            reportWtf("making Package Manager Service ready", e);
884        }
885
886        try {
887            display.systemReady(safeMode, onlyCore);
888        } catch (Throwable e) {
889            reportWtf("making Display Manager Service ready", e);
890        }
891
892        // 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;
919
920        // We now tell the activity manager it is okay to run third party
921        // code.  It will call back into us once it has gotten to the state
922        // where third party code can really run (but before it has actually
923        // started launching the initial applications), for us to complete our
924        // initialization.
925        ActivityManagerService.self().systemReady(new Runnable() {
926            public void run() {
927                Slog.i(TAG, "Making services ready");
928
929                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();
993
994                // It is now okay to let the various system services start their
995                // third party code...
996
997                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 manager
1050                    if (inputManagerF != null) inputManagerF.systemRunning();
1051                } catch (Throwable e) {
1052                    reportWtf("Notifying InputManagerService running", e);
1053                }
1054
1055                try {
1056                    if (telephonyRegistryF != null) telephonyRegistryF.systemRunning();
1057                } catch (Throwable e) {
1058                    reportWtf("Notifying TelephonyRegistry running", e);
1059                }
1060
1061                try {
1062                    if (printManagerF != null) printManagerF.systemRuning();
1063                } catch (Throwable e) {
1064                    reportWtf("Notifying PrintManagerService running", e);
1065                }
1066            }
1067        });
1068
1069        // 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        }
1073
1074        Looper.loop();
1075        Slog.d(TAG, "System ServerThread is exiting!");
1076    }
1077
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    }
1085}
1086
1087public class SystemServer {
1088    private static final String TAG = "SystemServer";
1089
1090    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;
1093
1094    static Timer timer;
1095    static final long SNAPSHOT_INTERVAL = 60 * 60 * 1000; // 1hr
1096
1097    // The earliest supported time.  We pick one day into 1970, to
1098    // give any timezone code room without going into negative time.
1099    private static final long EARLIEST_SUPPORTED_TIME = 86400 * 1000;
1100
1101    /**
1102     * Called to initialize native system services.
1103     */
1104    private static native void nativeInit();
1105
1106    public static void main(String[] args) {
1107
1108        /*
1109         * In case the runtime switched since last boot (such as when
1110         * the old runtime was removed in an OTA), set the system
1111         * property so that it is in sync. We can't do this in
1112         * libnativehelper's JniInvocation::Init code where we already
1113         * had to fallback to a different runtime because it is
1114         * running as root and we need to be the system user to set
1115         * the property. http://b/11463182
1116         */
1117        SystemProperties.set("persist.sys.dalvik.vm.lib",
1118                             VMRuntime.getRuntime().vmLibrary());
1119
1120        if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
1121            // If a device's clock is before 1970 (before 0), a lot of
1122            // APIs crash dealing with negative numbers, notably
1123            // java.io.File#setLastModified, so instead we fake it and
1124            // hope that time from cell towers or NTP fixes it
1125            // shortly.
1126            Slog.w(TAG, "System clock is before 1970; setting to 1970.");
1127            SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
1128        }
1129
1130        if (SamplingProfilerIntegration.isEnabled()) {
1131            SamplingProfilerIntegration.start();
1132            timer = new Timer();
1133            timer.schedule(new TimerTask() {
1134                @Override
1135                public void run() {
1136                    SamplingProfilerIntegration.writeSnapshot("system_server", null);
1137                }
1138            }, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL);
1139        }
1140
1141        // Mmmmmm... more memory!
1142        dalvik.system.VMRuntime.getRuntime().clearGrowthLimit();
1143
1144        // The system server has to run all of the time, so it needs to be
1145        // as efficient as possible with its memory usage.
1146        VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
1147
1148        Environment.setUserRequired(true);
1149
1150        System.loadLibrary("android_servers");
1151
1152        Slog.i(TAG, "Entered the Android system server!");
1153
1154        // Initialize native services.
1155        nativeInit();
1156
1157        // This used to be its own separate thread, but now it is
1158        // 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    }



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章