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