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