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