SystemServer.java revision 34196187365687d3f144a6de5fef811b52545ac0
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
19import android.accounts.AccountManagerService;
20import android.app.ActivityManagerNative;
21import android.bluetooth.BluetoothAdapter;
22import android.content.ComponentName;
23import android.content.ContentResolver;
24import android.content.ContentService;
25import android.content.Context;
26import android.content.Intent;
27import android.content.pm.IPackageManager;
28import android.content.res.Configuration;
29import android.media.AudioService;
30import android.net.wifi.p2p.WifiP2pService;
31import android.os.Looper;
32import android.os.RemoteException;
33import android.os.SchedulingPolicyService;
34import android.os.ServiceManager;
35import android.os.StrictMode;
36import android.os.SystemClock;
37import android.os.SystemProperties;
38import android.provider.Settings;
39import android.server.search.SearchManagerService;
40import android.service.dreams.DreamManagerService;
41import android.util.DisplayMetrics;
42import android.util.EventLog;
43import android.util.Log;
44import android.util.Slog;
45import android.view.WindowManager;
46
47import com.android.internal.os.BinderInternal;
48import com.android.internal.os.SamplingProfilerIntegration;
49import com.android.internal.widget.LockSettingsService;
50import com.android.server.accessibility.AccessibilityManagerService;
51import com.android.server.am.ActivityManagerService;
52import com.android.server.input.InputManagerService;
53import com.android.server.net.NetworkPolicyManagerService;
54import com.android.server.net.NetworkStatsService;
55import com.android.server.pm.PackageManagerService;
56import com.android.server.power.PowerManagerService;
57import com.android.server.power.ShutdownThread;
58import com.android.server.usb.UsbService;
59import com.android.server.wm.WindowManagerService;
60
61import dalvik.system.VMRuntime;
62import dalvik.system.Zygote;
63
64import java.io.File;
65import java.util.Timer;
66import java.util.TimerTask;
67
68class ServerThread extends Thread {
69    private static final String TAG = "SystemServer";
70    private static final String ENCRYPTING_STATE = "trigger_restart_min_framework";
71    private static final String ENCRYPTED_STATE = "1";
72
73    ContentResolver mContentResolver;
74
75    void reportWtf(String msg, Throwable e) {
76        Slog.w(TAG, "***********************************************");
77        Log.wtf(TAG, "BOOT FAILURE " + msg, e);
78    }
79
80    @Override
81    public void run() {
82        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN,
83            SystemClock.uptimeMillis());
84
85        Looper.prepareMainLooper();
86
87        android.os.Process.setThreadPriority(
88                android.os.Process.THREAD_PRIORITY_FOREGROUND);
89
90        BinderInternal.disableBackgroundScheduling(true);
91        android.os.Process.setCanSelfBackground(false);
92
93        // Check whether we failed to shut down last time we tried.
94        {
95            final String shutdownAction = SystemProperties.get(
96                    ShutdownThread.SHUTDOWN_ACTION_PROPERTY, "");
97            if (shutdownAction != null && shutdownAction.length() > 0) {
98                boolean reboot = (shutdownAction.charAt(0) == '1');
99
100                final String reason;
101                if (shutdownAction.length() > 1) {
102                    reason = shutdownAction.substring(1, shutdownAction.length());
103                } else {
104                    reason = null;
105                }
106
107                ShutdownThread.rebootOrShutdown(reboot, reason);
108            }
109        }
110
111        String factoryTestStr = SystemProperties.get("ro.factorytest");
112        int factoryTest = "".equals(factoryTestStr) ? SystemServer.FACTORY_TEST_OFF
113                : Integer.parseInt(factoryTestStr);
114        final boolean headless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
115
116        LightsService lights = null;
117        PowerManagerService power = null;
118        BatteryService battery = null;
119        VibratorService vibrator = null;
120        AlarmManagerService alarm = null;
121        NetworkManagementService networkManagement = null;
122        NetworkStatsService networkStats = null;
123        NetworkPolicyManagerService networkPolicy = null;
124        ConnectivityService connectivity = null;
125        WifiP2pService wifiP2p = null;
126        WifiService wifi = null;
127        NsdService serviceDiscovery= null;
128        IPackageManager pm = null;
129        Context context = null;
130        WindowManagerService wm = null;
131        DockObserver dock = null;
132        UsbService usb = null;
133        SerialService serial = null;
134        UiModeManagerService uiMode = null;
135        RecognitionManagerService recognition = null;
136        ThrottleService throttle = null;
137        NetworkTimeUpdateService networkTimeUpdater = null;
138        CommonTimeManagementService commonTimeMgmtService = null;
139        InputManagerService inputManager = null;
140
141        // Critical services...
142        try {
143            Slog.i(TAG, "Entropy Mixer");
144            ServiceManager.addService("entropy", new EntropyMixer());
145
146            Slog.i(TAG, "Power Manager");
147            power = new PowerManagerService();
148            ServiceManager.addService(Context.POWER_SERVICE, power);
149
150            Slog.i(TAG, "Activity Manager");
151            context = ActivityManagerService.main(factoryTest);
152
153            Slog.i(TAG, "Telephony Registry");
154            ServiceManager.addService("telephony.registry", new TelephonyRegistry(context));
155
156            Slog.i(TAG, "Scheduling Policy");
157            ServiceManager.addService(Context.SCHEDULING_POLICY_SERVICE,
158                    new SchedulingPolicyService());
159
160            AttributeCache.init(context);
161
162            Slog.i(TAG, "Package Manager");
163            // Only run "core" apps if we're encrypting the device.
164            String cryptState = SystemProperties.get("vold.decrypt");
165            boolean onlyCore = false;
166            if (ENCRYPTING_STATE.equals(cryptState)) {
167                Slog.w(TAG, "Detected encryption in progress - only parsing core apps");
168                onlyCore = true;
169            } else if (ENCRYPTED_STATE.equals(cryptState)) {
170                Slog.w(TAG, "Device encrypted - only parsing core apps");
171                onlyCore = true;
172            }
173
174            pm = PackageManagerService.main(context,
175                    factoryTest != SystemServer.FACTORY_TEST_OFF,
176                    onlyCore);
177            boolean firstBoot = false;
178            try {
179                firstBoot = pm.isFirstBoot();
180            } catch (RemoteException e) {
181            }
182
183            ActivityManagerService.setSystemProcess();
184
185            mContentResolver = context.getContentResolver();
186
187            // The AccountManager must come before the ContentService
188            try {
189                Slog.i(TAG, "Account Manager");
190                ServiceManager.addService(Context.ACCOUNT_SERVICE,
191                        new AccountManagerService(context));
192            } catch (Throwable e) {
193                Slog.e(TAG, "Failure starting Account Manager", e);
194            }
195
196            Slog.i(TAG, "Content Manager");
197            ContentService.main(context,
198                    factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL);
199
200            Slog.i(TAG, "System Content Providers");
201            ActivityManagerService.installSystemProviders();
202
203            Slog.i(TAG, "Lights Service");
204            lights = new LightsService(context);
205
206            Slog.i(TAG, "Battery Service");
207            battery = new BatteryService(context, lights);
208            ServiceManager.addService("battery", battery);
209
210            Slog.i(TAG, "Vibrator Service");
211            vibrator = new VibratorService(context);
212            ServiceManager.addService("vibrator", vibrator);
213
214            // only initialize the power service after we have started the
215            // lights service, content providers and the battery service.
216            power.init(context, lights, ActivityManagerService.self(), battery);
217
218            Slog.i(TAG, "Alarm Manager");
219            alarm = new AlarmManagerService(context);
220            ServiceManager.addService(Context.ALARM_SERVICE, alarm);
221
222            Slog.i(TAG, "Init Watchdog");
223            Watchdog.getInstance().init(context, battery, power, alarm,
224                    ActivityManagerService.self());
225
226            Slog.i(TAG, "Window Manager");
227            wm = WindowManagerService.main(context, power,
228                    factoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL,
229                    !firstBoot, onlyCore);
230            ServiceManager.addService(Context.WINDOW_SERVICE, wm);
231            inputManager = wm.getInputManagerService();
232            ServiceManager.addService(Context.INPUT_SERVICE, inputManager);
233
234            ActivityManagerService.self().setWindowManager(wm);
235
236            // Skip Bluetooth if we have an emulator kernel
237            // TODO: Use a more reliable check to see if this product should
238            // support Bluetooth - see bug 988521
239            if (SystemProperties.get("ro.kernel.qemu").equals("1")) {
240                Slog.i(TAG, "No Bluetooh Service (emulator)");
241            } else if (factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
242                Slog.i(TAG, "No Bluetooth Service (factory test)");
243            } else {
244                //TODO(BT): Start BT services and turn on if needed.
245                int airplaneModeOn = Settings.System.getInt(mContentResolver,
246                        Settings.System.AIRPLANE_MODE_ON, 0);
247                int bluetoothOn = Settings.Secure.getInt(mContentResolver,
248                    Settings.Secure.BLUETOOTH_ON, 0);
249            }
250
251        } catch (RuntimeException e) {
252            Slog.e("System", "******************************************");
253            Slog.e("System", "************ Failure starting core service", e);
254        }
255
256        DevicePolicyManagerService devicePolicy = null;
257        StatusBarManagerService statusBar = null;
258        InputMethodManagerService imm = null;
259        AppWidgetService appWidget = null;
260        NotificationManagerService notification = null;
261        WallpaperManagerService wallpaper = null;
262        LocationManagerService location = null;
263        CountryDetectorService countryDetector = null;
264        TextServicesManagerService tsms = null;
265        LockSettingsService lockSettings = null;
266        DreamManagerService dreamy = null;
267
268        // Bring up services needed for UI.
269        if (factoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
270            try {
271                Slog.i(TAG, "Input Method Service");
272                imm = new InputMethodManagerService(context, wm);
273                ServiceManager.addService(Context.INPUT_METHOD_SERVICE, imm);
274            } catch (Throwable e) {
275                reportWtf("starting Input Manager Service", e);
276            }
277
278            try {
279                Slog.i(TAG, "Accessibility Manager");
280                ServiceManager.addService(Context.ACCESSIBILITY_SERVICE,
281                        new AccessibilityManagerService(context));
282            } catch (Throwable e) {
283                reportWtf("starting Accessibility Manager", e);
284            }
285        }
286
287        try {
288            wm.displayReady();
289        } catch (Throwable e) {
290            reportWtf("making display ready", e);
291        }
292
293        try {
294            pm.performBootDexOpt();
295        } catch (Throwable e) {
296            reportWtf("performing boot dexopt", e);
297        }
298
299        try {
300            ActivityManagerNative.getDefault().showBootMessage(
301                    context.getResources().getText(
302                            com.android.internal.R.string.android_upgrading_starting_apps),
303                            false);
304        } catch (RemoteException e) {
305        }
306
307        if (factoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
308            MountService mountService = null;
309            if (!"0".equals(SystemProperties.get("system_init.startmountservice"))) {
310                try {
311                    /*
312                     * NotificationManagerService is dependant on MountService,
313                     * (for media / usb notifications) so we must start MountService first.
314                     */
315                    Slog.i(TAG, "Mount Service");
316                    mountService = new MountService(context);
317                    ServiceManager.addService("mount", mountService);
318                } catch (Throwable e) {
319                    reportWtf("starting Mount Service", e);
320                }
321            }
322
323            try {
324                Slog.i(TAG,  "LockSettingsService");
325                lockSettings = new LockSettingsService(context);
326                ServiceManager.addService("lock_settings", lockSettings);
327            } catch (Throwable e) {
328                reportWtf("starting LockSettingsService service", e);
329            }
330
331            try {
332                Slog.i(TAG, "Device Policy");
333                devicePolicy = new DevicePolicyManagerService(context);
334                ServiceManager.addService(Context.DEVICE_POLICY_SERVICE, devicePolicy);
335            } catch (Throwable e) {
336                reportWtf("starting DevicePolicyService", e);
337            }
338
339            try {
340                Slog.i(TAG, "Status Bar");
341                statusBar = new StatusBarManagerService(context, wm);
342                ServiceManager.addService(Context.STATUS_BAR_SERVICE, statusBar);
343            } catch (Throwable e) {
344                reportWtf("starting StatusBarManagerService", e);
345            }
346
347            try {
348                Slog.i(TAG, "Clipboard Service");
349                ServiceManager.addService(Context.CLIPBOARD_SERVICE,
350                        new ClipboardService(context));
351            } catch (Throwable e) {
352                reportWtf("starting Clipboard Service", e);
353            }
354
355            try {
356                Slog.i(TAG, "NetworkManagement Service");
357                networkManagement = NetworkManagementService.create(context);
358                ServiceManager.addService(Context.NETWORKMANAGEMENT_SERVICE, networkManagement);
359            } catch (Throwable e) {
360                reportWtf("starting NetworkManagement Service", e);
361            }
362
363            try {
364                Slog.i(TAG, "Text Service Manager Service");
365                tsms = new TextServicesManagerService(context);
366                ServiceManager.addService(Context.TEXT_SERVICES_MANAGER_SERVICE, tsms);
367            } catch (Throwable e) {
368                reportWtf("starting Text Service Manager Service", e);
369            }
370
371            try {
372                Slog.i(TAG, "NetworkStats Service");
373                networkStats = new NetworkStatsService(context, networkManagement, alarm);
374                ServiceManager.addService(Context.NETWORK_STATS_SERVICE, networkStats);
375            } catch (Throwable e) {
376                reportWtf("starting NetworkStats Service", e);
377            }
378
379            try {
380                Slog.i(TAG, "NetworkPolicy Service");
381                networkPolicy = new NetworkPolicyManagerService(
382                        context, ActivityManagerService.self(), power,
383                        networkStats, networkManagement);
384                ServiceManager.addService(Context.NETWORK_POLICY_SERVICE, networkPolicy);
385            } catch (Throwable e) {
386                reportWtf("starting NetworkPolicy Service", e);
387            }
388
389           try {
390                Slog.i(TAG, "Wi-Fi P2pService");
391                wifiP2p = new WifiP2pService(context);
392                ServiceManager.addService(Context.WIFI_P2P_SERVICE, wifiP2p);
393            } catch (Throwable e) {
394                reportWtf("starting Wi-Fi P2pService", e);
395            }
396
397           try {
398                Slog.i(TAG, "Wi-Fi Service");
399                wifi = new WifiService(context);
400                ServiceManager.addService(Context.WIFI_SERVICE, wifi);
401            } catch (Throwable e) {
402                reportWtf("starting Wi-Fi Service", e);
403            }
404
405            try {
406                Slog.i(TAG, "Connectivity Service");
407                connectivity = new ConnectivityService(
408                        context, networkManagement, networkStats, networkPolicy);
409                ServiceManager.addService(Context.CONNECTIVITY_SERVICE, connectivity);
410                networkStats.bindConnectivityManager(connectivity);
411                networkPolicy.bindConnectivityManager(connectivity);
412                wifi.checkAndStartWifi();
413                wifiP2p.connectivityServiceReady();
414            } catch (Throwable e) {
415                reportWtf("starting Connectivity Service", e);
416            }
417
418            try {
419                Slog.i(TAG, "Network Service Discovery Service");
420                serviceDiscovery = NsdService.create(context);
421                ServiceManager.addService(
422                        Context.NSD_SERVICE, serviceDiscovery);
423            } catch (Throwable e) {
424                reportWtf("starting Service Discovery Service", e);
425            }
426
427            try {
428                Slog.i(TAG, "Throttle Service");
429                throttle = new ThrottleService(context);
430                ServiceManager.addService(
431                        Context.THROTTLE_SERVICE, throttle);
432            } catch (Throwable e) {
433                reportWtf("starting ThrottleService", e);
434            }
435
436            try {
437                Slog.i(TAG, "UpdateLock Service");
438                ServiceManager.addService(Context.UPDATE_LOCK_SERVICE,
439                        new UpdateLockService(context));
440            } catch (Throwable e) {
441                reportWtf("starting UpdateLockService", e);
442            }
443
444            /*
445             * MountService has a few dependencies: Notification Manager and
446             * AppWidget Provider. Make sure MountService is completely started
447             * first before continuing.
448             */
449            if (mountService != null) {
450                mountService.waitForAsecScan();
451            }
452
453            try {
454                Slog.i(TAG, "Notification Manager");
455                notification = new NotificationManagerService(context, statusBar, lights);
456                ServiceManager.addService(Context.NOTIFICATION_SERVICE, notification);
457                networkPolicy.bindNotificationManager(notification);
458            } catch (Throwable e) {
459                reportWtf("starting Notification Manager", e);
460            }
461
462            try {
463                Slog.i(TAG, "Device Storage Monitor");
464                ServiceManager.addService(DeviceStorageMonitorService.SERVICE,
465                        new DeviceStorageMonitorService(context));
466            } catch (Throwable e) {
467                reportWtf("starting DeviceStorageMonitor service", e);
468            }
469
470            try {
471                Slog.i(TAG, "Location Manager");
472                location = new LocationManagerService(context);
473                ServiceManager.addService(Context.LOCATION_SERVICE, location);
474            } catch (Throwable e) {
475                reportWtf("starting Location Manager", e);
476            }
477
478            try {
479                Slog.i(TAG, "Country Detector");
480                countryDetector = new CountryDetectorService(context);
481                ServiceManager.addService(Context.COUNTRY_DETECTOR, countryDetector);
482            } catch (Throwable e) {
483                reportWtf("starting Country Detector", e);
484            }
485
486            try {
487                Slog.i(TAG, "Search Service");
488                ServiceManager.addService(Context.SEARCH_SERVICE,
489                        new SearchManagerService(context));
490            } catch (Throwable e) {
491                reportWtf("starting Search Service", e);
492            }
493
494            try {
495                Slog.i(TAG, "DropBox Service");
496                ServiceManager.addService(Context.DROPBOX_SERVICE,
497                        new DropBoxManagerService(context, new File("/data/system/dropbox")));
498            } catch (Throwable e) {
499                reportWtf("starting DropBoxManagerService", e);
500            }
501
502            if (context.getResources().getBoolean(
503                        com.android.internal.R.bool.config_enableWallpaperService)) {
504                try {
505                    Slog.i(TAG, "Wallpaper Service");
506                    if (!headless) {
507                        wallpaper = new WallpaperManagerService(context);
508                        ServiceManager.addService(Context.WALLPAPER_SERVICE, wallpaper);
509                    }
510                } catch (Throwable e) {
511                    reportWtf("starting Wallpaper Service", e);
512                }
513            }
514
515            if (!"0".equals(SystemProperties.get("system_init.startaudioservice"))) {
516                try {
517                    Slog.i(TAG, "Audio Service");
518                    ServiceManager.addService(Context.AUDIO_SERVICE, new AudioService(context));
519                } catch (Throwable e) {
520                    reportWtf("starting Audio Service", e);
521                }
522            }
523
524            try {
525                Slog.i(TAG, "Dock Observer");
526                // Listen for dock station changes
527                dock = new DockObserver(context, power);
528            } catch (Throwable e) {
529                reportWtf("starting DockObserver", e);
530            }
531
532            try {
533                Slog.i(TAG, "Wired Accessory Observer");
534                // Listen for wired headset changes
535                new WiredAccessoryObserver(context);
536            } catch (Throwable e) {
537                reportWtf("starting WiredAccessoryObserver", e);
538            }
539
540            try {
541                Slog.i(TAG, "USB Service");
542                // Manage USB host and device support
543                usb = new UsbService(context);
544                ServiceManager.addService(Context.USB_SERVICE, usb);
545            } catch (Throwable e) {
546                reportWtf("starting UsbService", e);
547            }
548
549            try {
550                Slog.i(TAG, "Serial Service");
551                // Serial port support
552                serial = new SerialService(context);
553                ServiceManager.addService(Context.SERIAL_SERVICE, serial);
554            } catch (Throwable e) {
555                Slog.e(TAG, "Failure starting SerialService", e);
556            }
557
558            try {
559                Slog.i(TAG, "UI Mode Manager Service");
560                // Listen for UI mode changes
561                uiMode = new UiModeManagerService(context);
562            } catch (Throwable e) {
563                reportWtf("starting UiModeManagerService", e);
564            }
565
566            try {
567                Slog.i(TAG, "Backup Service");
568                ServiceManager.addService(Context.BACKUP_SERVICE,
569                        new BackupManagerService(context));
570            } catch (Throwable e) {
571                Slog.e(TAG, "Failure starting Backup Service", e);
572            }
573
574            try {
575                Slog.i(TAG, "AppWidget Service");
576                appWidget = new AppWidgetService(context);
577                ServiceManager.addService(Context.APPWIDGET_SERVICE, appWidget);
578            } catch (Throwable e) {
579                reportWtf("starting AppWidget Service", e);
580            }
581
582            try {
583                Slog.i(TAG, "Recognition Service");
584                recognition = new RecognitionManagerService(context);
585            } catch (Throwable e) {
586                reportWtf("starting Recognition Service", e);
587            }
588
589            try {
590                Slog.i(TAG, "DiskStats Service");
591                ServiceManager.addService("diskstats", new DiskStatsService(context));
592            } catch (Throwable e) {
593                reportWtf("starting DiskStats Service", e);
594            }
595
596            try {
597                // need to add this service even if SamplingProfilerIntegration.isEnabled()
598                // is false, because it is this service that detects system property change and
599                // turns on SamplingProfilerIntegration. Plus, when sampling profiler doesn't work,
600                // there is little overhead for running this service.
601                Slog.i(TAG, "SamplingProfiler Service");
602                ServiceManager.addService("samplingprofiler",
603                            new SamplingProfilerService(context));
604            } catch (Throwable e) {
605                reportWtf("starting SamplingProfiler Service", e);
606            }
607
608            try {
609                Slog.i(TAG, "NetworkTimeUpdateService");
610                networkTimeUpdater = new NetworkTimeUpdateService(context);
611            } catch (Throwable e) {
612                reportWtf("starting NetworkTimeUpdate service", e);
613            }
614
615            try {
616                Slog.i(TAG, "CommonTimeManagementService");
617                commonTimeMgmtService = new CommonTimeManagementService(context);
618                ServiceManager.addService("commontime_management", commonTimeMgmtService);
619            } catch (Throwable e) {
620                reportWtf("starting CommonTimeManagementService service", e);
621            }
622
623            try {
624                Slog.i(TAG, "CertBlacklister");
625                CertBlacklister blacklister = new CertBlacklister(context);
626            } catch (Throwable e) {
627                reportWtf("starting CertBlacklister", e);
628            }
629
630            if (context.getResources().getBoolean(
631                    com.android.internal.R.bool.config_enableDreams)) {
632                try {
633                    Slog.i(TAG, "Dreams Service");
634                    // Dreams (interactive idle-time views, a/k/a screen savers)
635                    dreamy = new DreamManagerService(context);
636                    ServiceManager.addService("dreams", dreamy);
637                } catch (Throwable e) {
638                    reportWtf("starting DreamManagerService", e);
639                }
640            }
641        }
642
643        // Before things start rolling, be sure we have decided whether
644        // we are in safe mode.
645        final boolean safeMode = wm.detectSafeMode();
646        if (safeMode) {
647            ActivityManagerService.self().enterSafeMode();
648            // Post the safe mode state in the Zygote class
649            Zygote.systemInSafeMode = true;
650            // Disable the JIT for the system_server process
651            VMRuntime.getRuntime().disableJitCompilation();
652        } else {
653            // Enable the JIT for the system_server process
654            VMRuntime.getRuntime().startJitCompilation();
655        }
656
657        // It is now time to start up the app processes...
658
659        try {
660            vibrator.systemReady();
661        } catch (Throwable e) {
662            reportWtf("making Vibrator Service ready", e);
663        }
664
665        if (devicePolicy != null) {
666            try {
667                devicePolicy.systemReady();
668            } catch (Throwable e) {
669                reportWtf("making Device Policy Service ready", e);
670            }
671        }
672
673        if (notification != null) {
674            try {
675                notification.systemReady();
676            } catch (Throwable e) {
677                reportWtf("making Notification Service ready", e);
678            }
679        }
680
681        try {
682            wm.systemReady();
683        } catch (Throwable e) {
684            reportWtf("making Window Manager Service ready", e);
685        }
686
687        if (safeMode) {
688            ActivityManagerService.self().showSafeModeOverlay();
689        }
690
691        // Update the configuration for this context by hand, because we're going
692        // to start using it before the config change done in wm.systemReady() will
693        // propagate to it.
694        Configuration config = wm.computeNewConfiguration();
695        DisplayMetrics metrics = new DisplayMetrics();
696        WindowManager w = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
697        w.getDefaultDisplay().getMetrics(metrics);
698        context.getResources().updateConfiguration(config, metrics);
699
700        power.systemReady();
701        try {
702            pm.systemReady();
703        } catch (Throwable e) {
704            reportWtf("making Package Manager Service ready", e);
705        }
706        try {
707            lockSettings.systemReady();
708        } catch (Throwable e) {
709            reportWtf("making Lock Settings Service ready", e);
710        }
711
712        // These are needed to propagate to the runnable below.
713        final Context contextF = context;
714        final BatteryService batteryF = battery;
715        final NetworkManagementService networkManagementF = networkManagement;
716        final NetworkStatsService networkStatsF = networkStats;
717        final NetworkPolicyManagerService networkPolicyF = networkPolicy;
718        final ConnectivityService connectivityF = connectivity;
719        final DockObserver dockF = dock;
720        final UsbService usbF = usb;
721        final ThrottleService throttleF = throttle;
722        final UiModeManagerService uiModeF = uiMode;
723        final AppWidgetService appWidgetF = appWidget;
724        final WallpaperManagerService wallpaperF = wallpaper;
725        final InputMethodManagerService immF = imm;
726        final RecognitionManagerService recognitionF = recognition;
727        final LocationManagerService locationF = location;
728        final CountryDetectorService countryDetectorF = countryDetector;
729        final NetworkTimeUpdateService networkTimeUpdaterF = networkTimeUpdater;
730        final CommonTimeManagementService commonTimeMgmtServiceF = commonTimeMgmtService;
731        final TextServicesManagerService textServiceManagerServiceF = tsms;
732        final StatusBarManagerService statusBarF = statusBar;
733        final DreamManagerService dreamyF = dreamy;
734        final InputManagerService inputManagerF = inputManager;
735        final BluetoothService bluetoothF = bluetooth;
736
737        // We now tell the activity manager it is okay to run third party
738        // code.  It will call back into us once it has gotten to the state
739        // where third party code can really run (but before it has actually
740        // started launching the initial applications), for us to complete our
741        // initialization.
742        ActivityManagerService.self().systemReady(new Runnable() {
743            public void run() {
744                Slog.i(TAG, "Making services ready");
745
746                if (!headless) startSystemUi(contextF);
747                try {
748                    if (batteryF != null) batteryF.systemReady();
749                } catch (Throwable e) {
750                    reportWtf("making Battery Service ready", e);
751                }
752                try {
753                    if (networkManagementF != null) networkManagementF.systemReady();
754                } catch (Throwable e) {
755                    reportWtf("making Network Managment Service ready", e);
756                }
757                try {
758                    if (networkStatsF != null) networkStatsF.systemReady();
759                } catch (Throwable e) {
760                    reportWtf("making Network Stats Service ready", e);
761                }
762                try {
763                    if (networkPolicyF != null) networkPolicyF.systemReady();
764                } catch (Throwable e) {
765                    reportWtf("making Network Policy Service ready", e);
766                }
767                try {
768                    if (connectivityF != null) connectivityF.systemReady();
769                } catch (Throwable e) {
770                    reportWtf("making Connectivity Service ready", e);
771                }
772                try {
773                    if (dockF != null) dockF.systemReady();
774                } catch (Throwable e) {
775                    reportWtf("making Dock Service ready", e);
776                }
777                try {
778                    if (usbF != null) usbF.systemReady();
779                } catch (Throwable e) {
780                    reportWtf("making USB Service ready", e);
781                }
782                try {
783                    if (uiModeF != null) uiModeF.systemReady();
784                } catch (Throwable e) {
785                    reportWtf("making UI Mode Service ready", e);
786                }
787                try {
788                    if (recognitionF != null) recognitionF.systemReady();
789                } catch (Throwable e) {
790                    reportWtf("making Recognition Service ready", e);
791                }
792                Watchdog.getInstance().start();
793
794                // It is now okay to let the various system services start their
795                // third party code...
796
797                try {
798                    if (appWidgetF != null) appWidgetF.systemReady(safeMode);
799                } catch (Throwable e) {
800                    reportWtf("making App Widget Service ready", e);
801                }
802                try {
803                    if (wallpaperF != null) wallpaperF.systemReady();
804                } catch (Throwable e) {
805                    reportWtf("making Wallpaper Service ready", e);
806                }
807                try {
808                    if (immF != null) immF.systemReady(statusBarF);
809                } catch (Throwable e) {
810                    reportWtf("making Input Method Service ready", e);
811                }
812                try {
813                    if (locationF != null) locationF.systemReady();
814                } catch (Throwable e) {
815                    reportWtf("making Location Service ready", e);
816                }
817                try {
818                    if (countryDetectorF != null) countryDetectorF.systemReady();
819                } catch (Throwable e) {
820                    reportWtf("making Country Detector Service ready", e);
821                }
822                try {
823                    if (throttleF != null) throttleF.systemReady();
824                } catch (Throwable e) {
825                    reportWtf("making Throttle Service ready", e);
826                }
827                try {
828                    if (networkTimeUpdaterF != null) networkTimeUpdaterF.systemReady();
829                } catch (Throwable e) {
830                    reportWtf("making Network Time Service ready", e);
831                }
832                try {
833                    if (commonTimeMgmtServiceF != null) commonTimeMgmtServiceF.systemReady();
834                } catch (Throwable e) {
835                    reportWtf("making Common time management service ready", e);
836                }
837                try {
838                    if (textServiceManagerServiceF != null) textServiceManagerServiceF.systemReady();
839                } catch (Throwable e) {
840                    reportWtf("making Text Services Manager Service ready", e);
841                }
842                try {
843                    if (dreamyF != null) dreamyF.systemReady();
844                } catch (Throwable e) {
845                    reportWtf("making DreamManagerService ready", e);
846                }
847                try {
848                    if (inputManagerF != null) inputManagerF.systemReady(bluetoothF);
849                } catch (Throwable e) {
850                    reportWtf("making InputManagerService ready", e);
851                }
852            }
853        });
854
855        // For debug builds, log event loop stalls to dropbox for analysis.
856        if (StrictMode.conditionallyEnableDebugLogging()) {
857            Slog.i(TAG, "Enabled StrictMode for system server main thread.");
858        }
859
860        Looper.loop();
861        Slog.d(TAG, "System ServerThread is exiting!");
862    }
863
864    static final void startSystemUi(Context context) {
865        Intent intent = new Intent();
866        intent.setComponent(new ComponentName("com.android.systemui",
867                    "com.android.systemui.SystemUIService"));
868        Slog.d(TAG, "Starting service: " + intent);
869        context.startService(intent);
870    }
871}
872
873public class SystemServer {
874    private static final String TAG = "SystemServer";
875
876    public static final int FACTORY_TEST_OFF = 0;
877    public static final int FACTORY_TEST_LOW_LEVEL = 1;
878    public static final int FACTORY_TEST_HIGH_LEVEL = 2;
879
880    static Timer timer;
881    static final long SNAPSHOT_INTERVAL = 60 * 60 * 1000; // 1hr
882
883    // The earliest supported time.  We pick one day into 1970, to
884    // give any timezone code room without going into negative time.
885    private static final long EARLIEST_SUPPORTED_TIME = 86400 * 1000;
886
887    /**
888     * This method is called from Zygote to initialize the system. This will cause the native
889     * services (SurfaceFlinger, AudioFlinger, etc..) to be started. After that it will call back
890     * up into init2() to start the Android services.
891     */
892    native public static void init1(String[] args);
893
894    public static void main(String[] args) {
895        if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
896            // If a device's clock is before 1970 (before 0), a lot of
897            // APIs crash dealing with negative numbers, notably
898            // java.io.File#setLastModified, so instead we fake it and
899            // hope that time from cell towers or NTP fixes it
900            // shortly.
901            Slog.w(TAG, "System clock is before 1970; setting to 1970.");
902            SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
903        }
904
905        if (SamplingProfilerIntegration.isEnabled()) {
906            SamplingProfilerIntegration.start();
907            timer = new Timer();
908            timer.schedule(new TimerTask() {
909                @Override
910                public void run() {
911                    SamplingProfilerIntegration.writeSnapshot("system_server", null);
912                }
913            }, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL);
914        }
915
916        // Mmmmmm... more memory!
917        dalvik.system.VMRuntime.getRuntime().clearGrowthLimit();
918
919        // The system server has to run all of the time, so it needs to be
920        // as efficient as possible with its memory usage.
921        VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
922
923        System.loadLibrary("android_servers");
924        init1(args);
925    }
926
927    public static final void init2() {
928        Slog.i(TAG, "Entered the Android system server!");
929        Thread thr = new ServerThread();
930        thr.setName("android.server.ServerThread");
931        thr.start();
932    }
933}
934