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