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