SystemServer.java revision 7d024d372431effc87168afdc7cbe387680c4935
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        NsdService serviceDiscovery= null;
124        IPackageManager pm = null;
125        Context context = null;
126        WindowManagerService wm = null;
127        BluetoothService bluetooth = null;
128        BluetoothA2dpService bluetoothA2dp = null;
129        DockObserver dock = null;
130        UsbService usb = null;
131        SerialService serial = null;
132        UiModeManagerService uiMode = null;
133        RecognitionManagerService recognition = null;
134        ThrottleService throttle = null;
135        NetworkTimeUpdateService networkTimeUpdater = null;
136        CommonTimeManagementService commonTimeMgmtService = null;
137
138        // Critical services...
139        try {
140            Slog.i(TAG, "Entropy Mixer");
141            ServiceManager.addService("entropy", new EntropyMixer());
142
143            Slog.i(TAG, "Power Manager");
144            power = new PowerManagerService();
145            ServiceManager.addService(Context.POWER_SERVICE, power);
146
147            Slog.i(TAG, "Activity Manager");
148            context = ActivityManagerService.main(factoryTest);
149
150            Slog.i(TAG, "Telephony Registry");
151            ServiceManager.addService("telephony.registry", new TelephonyRegistry(context));
152
153            AttributeCache.init(context);
154
155            Slog.i(TAG, "Package Manager");
156            // Only run "core" apps if we're encrypting the device.
157            String cryptState = SystemProperties.get("vold.decrypt");
158            boolean onlyCore = false;
159            if (ENCRYPTING_STATE.equals(cryptState)) {
160                Slog.w(TAG, "Detected encryption in progress - only parsing core apps");
161                onlyCore = true;
162            } else if (ENCRYPTED_STATE.equals(cryptState)) {
163                Slog.w(TAG, "Device encrypted - only parsing core apps");
164                onlyCore = true;
165            }
166
167            pm = PackageManagerService.main(context,
168                    factoryTest != SystemServer.FACTORY_TEST_OFF,
169                    onlyCore);
170            boolean firstBoot = false;
171            try {
172                firstBoot = pm.isFirstBoot();
173            } catch (RemoteException e) {
174            }
175
176            ActivityManagerService.setSystemProcess();
177
178            mContentResolver = context.getContentResolver();
179
180            // The AccountManager must come before the ContentService
181            try {
182                Slog.i(TAG, "Account Manager");
183                ServiceManager.addService(Context.ACCOUNT_SERVICE,
184                        new AccountManagerService(context));
185            } catch (Throwable e) {
186                Slog.e(TAG, "Failure starting Account Manager", e);
187            }
188
189            Slog.i(TAG, "Content Manager");
190            ContentService.main(context,
191                    factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL);
192
193            Slog.i(TAG, "System Content Providers");
194            ActivityManagerService.installSystemProviders();
195
196            Slog.i(TAG, "Lights Service");
197            lights = new LightsService(context);
198
199            Slog.i(TAG, "Battery Service");
200            battery = new BatteryService(context, lights);
201            ServiceManager.addService("battery", battery);
202
203            Slog.i(TAG, "Vibrator Service");
204            ServiceManager.addService("vibrator", new VibratorService(context));
205
206            // only initialize the power service after we have started the
207            // lights service, content providers and the battery service.
208            power.init(context, lights, ActivityManagerService.self(), battery);
209
210            Slog.i(TAG, "Alarm Manager");
211            alarm = new AlarmManagerService(context);
212            ServiceManager.addService(Context.ALARM_SERVICE, alarm);
213
214            Slog.i(TAG, "Init Watchdog");
215            Watchdog.getInstance().init(context, battery, power, alarm,
216                    ActivityManagerService.self());
217
218            Slog.i(TAG, "Window Manager");
219            wm = WindowManagerService.main(context, power,
220                    factoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL,
221                    !firstBoot);
222            ServiceManager.addService(Context.WINDOW_SERVICE, wm);
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, "Network Service Discovery Service");
399                serviceDiscovery = NsdService.create(context);
400                ServiceManager.addService(
401                        Context.NSD_SERVICE, serviceDiscovery);
402            } catch (Throwable e) {
403                reportWtf("starting Service Discovery Service", e);
404            }
405
406            try {
407                Slog.i(TAG, "Throttle Service");
408                throttle = new ThrottleService(context);
409                ServiceManager.addService(
410                        Context.THROTTLE_SERVICE, throttle);
411            } catch (Throwable e) {
412                reportWtf("starting ThrottleService", e);
413            }
414
415            try {
416                Slog.i(TAG, "UpdateLock Service");
417                ServiceManager.addService(Context.UPDATE_LOCK_SERVICE,
418                        new UpdateLockService(context));
419            } catch (Throwable e) {
420                reportWtf("starting UpdateLockService", e);
421            }
422
423            if (!"0".equals(SystemProperties.get("system_init.startmountservice"))) {
424                try {
425                    /*
426                     * NotificationManagerService is dependant on MountService,
427                     * (for media / usb notifications) so we must start MountService first.
428                     */
429                    Slog.i(TAG, "Mount Service");
430                    ServiceManager.addService("mount", new MountService(context));
431                } catch (Throwable e) {
432                    reportWtf("starting Mount Service", e);
433                }
434            }
435
436            try {
437                Slog.i(TAG, "Notification Manager");
438                notification = new NotificationManagerService(context, statusBar, lights);
439                ServiceManager.addService(Context.NOTIFICATION_SERVICE, notification);
440                networkPolicy.bindNotificationManager(notification);
441            } catch (Throwable e) {
442                reportWtf("starting Notification Manager", e);
443            }
444
445            try {
446                Slog.i(TAG, "Device Storage Monitor");
447                ServiceManager.addService(DeviceStorageMonitorService.SERVICE,
448                        new DeviceStorageMonitorService(context));
449            } catch (Throwable e) {
450                reportWtf("starting DeviceStorageMonitor service", e);
451            }
452
453            try {
454                Slog.i(TAG, "Location Manager");
455                location = new LocationManagerService(context);
456                ServiceManager.addService(Context.LOCATION_SERVICE, location);
457            } catch (Throwable e) {
458                reportWtf("starting Location Manager", e);
459            }
460
461            try {
462                Slog.i(TAG, "Country Detector");
463                countryDetector = new CountryDetectorService(context);
464                ServiceManager.addService(Context.COUNTRY_DETECTOR, countryDetector);
465            } catch (Throwable e) {
466                reportWtf("starting Country Detector", e);
467            }
468
469            try {
470                Slog.i(TAG, "Search Service");
471                ServiceManager.addService(Context.SEARCH_SERVICE,
472                        new SearchManagerService(context));
473            } catch (Throwable e) {
474                reportWtf("starting Search Service", e);
475            }
476
477            try {
478                Slog.i(TAG, "DropBox Service");
479                ServiceManager.addService(Context.DROPBOX_SERVICE,
480                        new DropBoxManagerService(context, new File("/data/system/dropbox")));
481            } catch (Throwable e) {
482                reportWtf("starting DropBoxManagerService", e);
483            }
484
485            if (context.getResources().getBoolean(
486                        com.android.internal.R.bool.config_enableWallpaperService)) {
487                try {
488                    Slog.i(TAG, "Wallpaper Service");
489                    if (!headless) {
490                        wallpaper = new WallpaperManagerService(context);
491                        ServiceManager.addService(Context.WALLPAPER_SERVICE, wallpaper);
492                    }
493                } catch (Throwable e) {
494                    reportWtf("starting Wallpaper Service", e);
495                }
496            }
497
498            if (!"0".equals(SystemProperties.get("system_init.startaudioservice"))) {
499                try {
500                    Slog.i(TAG, "Audio Service");
501                    ServiceManager.addService(Context.AUDIO_SERVICE, new AudioService(context));
502                } catch (Throwable e) {
503                    reportWtf("starting Audio Service", e);
504                }
505            }
506
507            try {
508                Slog.i(TAG, "Dock Observer");
509                // Listen for dock station changes
510                dock = new DockObserver(context, power);
511            } catch (Throwable e) {
512                reportWtf("starting DockObserver", e);
513            }
514
515            try {
516                Slog.i(TAG, "Wired Accessory Observer");
517                // Listen for wired headset changes
518                new WiredAccessoryObserver(context);
519            } catch (Throwable e) {
520                reportWtf("starting WiredAccessoryObserver", e);
521            }
522
523            try {
524                Slog.i(TAG, "USB Service");
525                // Manage USB host and device support
526                usb = new UsbService(context);
527                ServiceManager.addService(Context.USB_SERVICE, usb);
528            } catch (Throwable e) {
529                reportWtf("starting UsbService", e);
530            }
531
532            try {
533                Slog.i(TAG, "Serial Service");
534                // Serial port support
535                serial = new SerialService(context);
536                ServiceManager.addService(Context.SERIAL_SERVICE, serial);
537            } catch (Throwable e) {
538                Slog.e(TAG, "Failure starting SerialService", e);
539            }
540
541            try {
542                Slog.i(TAG, "UI Mode Manager Service");
543                // Listen for UI mode changes
544                uiMode = new UiModeManagerService(context);
545            } catch (Throwable e) {
546                reportWtf("starting UiModeManagerService", e);
547            }
548
549            try {
550                Slog.i(TAG, "Backup Service");
551                ServiceManager.addService(Context.BACKUP_SERVICE,
552                        new BackupManagerService(context));
553            } catch (Throwable e) {
554                Slog.e(TAG, "Failure starting Backup Service", e);
555            }
556
557            try {
558                Slog.i(TAG, "AppWidget Service");
559                appWidget = new AppWidgetService(context);
560                ServiceManager.addService(Context.APPWIDGET_SERVICE, appWidget);
561            } catch (Throwable e) {
562                reportWtf("starting AppWidget Service", e);
563            }
564
565            try {
566                Slog.i(TAG, "Recognition Service");
567                recognition = new RecognitionManagerService(context);
568            } catch (Throwable e) {
569                reportWtf("starting Recognition Service", e);
570            }
571
572            try {
573                Slog.i(TAG, "DiskStats Service");
574                ServiceManager.addService("diskstats", new DiskStatsService(context));
575            } catch (Throwable e) {
576                reportWtf("starting DiskStats Service", e);
577            }
578
579            try {
580                // need to add this service even if SamplingProfilerIntegration.isEnabled()
581                // is false, because it is this service that detects system property change and
582                // turns on SamplingProfilerIntegration. Plus, when sampling profiler doesn't work,
583                // there is little overhead for running this service.
584                Slog.i(TAG, "SamplingProfiler Service");
585                ServiceManager.addService("samplingprofiler",
586                            new SamplingProfilerService(context));
587            } catch (Throwable e) {
588                reportWtf("starting SamplingProfiler Service", e);
589            }
590
591            try {
592                Slog.i(TAG, "NetworkTimeUpdateService");
593                networkTimeUpdater = new NetworkTimeUpdateService(context);
594            } catch (Throwable e) {
595                reportWtf("starting NetworkTimeUpdate service", e);
596            }
597
598            try {
599                Slog.i(TAG, "CommonTimeManagementService");
600                commonTimeMgmtService = new CommonTimeManagementService(context);
601                ServiceManager.addService("commontime_management", commonTimeMgmtService);
602            } catch (Throwable e) {
603                reportWtf("starting CommonTimeManagementService service", e);
604            }
605        }
606
607        // Before things start rolling, be sure we have decided whether
608        // we are in safe mode.
609        final boolean safeMode = wm.detectSafeMode();
610        if (safeMode) {
611            ActivityManagerService.self().enterSafeMode();
612            // Post the safe mode state in the Zygote class
613            Zygote.systemInSafeMode = true;
614            // Disable the JIT for the system_server process
615            VMRuntime.getRuntime().disableJitCompilation();
616        } else {
617            // Enable the JIT for the system_server process
618            VMRuntime.getRuntime().startJitCompilation();
619        }
620
621        // It is now time to start up the app processes...
622
623        if (devicePolicy != null) {
624            try {
625                devicePolicy.systemReady();
626            } catch (Throwable e) {
627                reportWtf("making Device Policy Service ready", e);
628            }
629        }
630
631        if (notification != null) {
632            try {
633                notification.systemReady();
634            } catch (Throwable e) {
635                reportWtf("making Notification Service ready", e);
636            }
637        }
638
639        try {
640            wm.systemReady();
641        } catch (Throwable e) {
642            reportWtf("making Window Manager Service ready", e);
643        }
644
645        if (safeMode) {
646            ActivityManagerService.self().showSafeModeOverlay();
647        }
648
649        // Update the configuration for this context by hand, because we're going
650        // to start using it before the config change done in wm.systemReady() will
651        // propagate to it.
652        Configuration config = wm.computeNewConfiguration();
653        DisplayMetrics metrics = new DisplayMetrics();
654        WindowManager w = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
655        w.getDefaultDisplay().getMetrics(metrics);
656        context.getResources().updateConfiguration(config, metrics);
657
658        power.systemReady();
659        try {
660            pm.systemReady();
661        } catch (Throwable e) {
662            reportWtf("making Package Manager Service ready", e);
663        }
664
665        // These are needed to propagate to the runnable below.
666        final Context contextF = context;
667        final BatteryService batteryF = battery;
668        final NetworkManagementService networkManagementF = networkManagement;
669        final NetworkStatsService networkStatsF = networkStats;
670        final NetworkPolicyManagerService networkPolicyF = networkPolicy;
671        final ConnectivityService connectivityF = connectivity;
672        final DockObserver dockF = dock;
673        final UsbService usbF = usb;
674        final ThrottleService throttleF = throttle;
675        final UiModeManagerService uiModeF = uiMode;
676        final AppWidgetService appWidgetF = appWidget;
677        final WallpaperManagerService wallpaperF = wallpaper;
678        final InputMethodManagerService immF = imm;
679        final RecognitionManagerService recognitionF = recognition;
680        final LocationManagerService locationF = location;
681        final CountryDetectorService countryDetectorF = countryDetector;
682        final NetworkTimeUpdateService networkTimeUpdaterF = networkTimeUpdater;
683        final CommonTimeManagementService commonTimeMgmtServiceF = commonTimeMgmtService;
684        final TextServicesManagerService textServiceManagerServiceF = tsms;
685        final StatusBarManagerService statusBarF = statusBar;
686
687        // We now tell the activity manager it is okay to run third party
688        // code.  It will call back into us once it has gotten to the state
689        // where third party code can really run (but before it has actually
690        // started launching the initial applications), for us to complete our
691        // initialization.
692        ActivityManagerService.self().systemReady(new Runnable() {
693            public void run() {
694                Slog.i(TAG, "Making services ready");
695
696                if (!headless) startSystemUi(contextF);
697                try {
698                    if (batteryF != null) batteryF.systemReady();
699                } catch (Throwable e) {
700                    reportWtf("making Battery Service ready", e);
701                }
702                try {
703                    if (networkManagementF != null) networkManagementF.systemReady();
704                } catch (Throwable e) {
705                    reportWtf("making Network Managment Service ready", e);
706                }
707                try {
708                    if (networkStatsF != null) networkStatsF.systemReady();
709                } catch (Throwable e) {
710                    reportWtf("making Network Stats Service ready", e);
711                }
712                try {
713                    if (networkPolicyF != null) networkPolicyF.systemReady();
714                } catch (Throwable e) {
715                    reportWtf("making Network Policy Service ready", e);
716                }
717                try {
718                    if (connectivityF != null) connectivityF.systemReady();
719                } catch (Throwable e) {
720                    reportWtf("making Connectivity Service ready", e);
721                }
722                try {
723                    if (dockF != null) dockF.systemReady();
724                } catch (Throwable e) {
725                    reportWtf("making Dock Service ready", e);
726                }
727                try {
728                    if (usbF != null) usbF.systemReady();
729                } catch (Throwable e) {
730                    reportWtf("making USB Service ready", e);
731                }
732                try {
733                    if (uiModeF != null) uiModeF.systemReady();
734                } catch (Throwable e) {
735                    reportWtf("making UI Mode Service ready", e);
736                }
737                try {
738                    if (recognitionF != null) recognitionF.systemReady();
739                } catch (Throwable e) {
740                    reportWtf("making Recognition Service ready", e);
741                }
742                Watchdog.getInstance().start();
743
744                // It is now okay to let the various system services start their
745                // third party code...
746
747                try {
748                    if (appWidgetF != null) appWidgetF.systemReady(safeMode);
749                } catch (Throwable e) {
750                    reportWtf("making App Widget Service ready", e);
751                }
752                try {
753                    if (wallpaperF != null) wallpaperF.systemReady();
754                } catch (Throwable e) {
755                    reportWtf("making Wallpaper Service ready", e);
756                }
757                try {
758                    if (immF != null) immF.systemReady(statusBarF);
759                } catch (Throwable e) {
760                    reportWtf("making Input Method Service ready", e);
761                }
762                try {
763                    if (locationF != null) locationF.systemReady();
764                } catch (Throwable e) {
765                    reportWtf("making Location Service ready", e);
766                }
767                try {
768                    if (countryDetectorF != null) countryDetectorF.systemReady();
769                } catch (Throwable e) {
770                    reportWtf("making Country Detector Service ready", e);
771                }
772                try {
773                    if (throttleF != null) throttleF.systemReady();
774                } catch (Throwable e) {
775                    reportWtf("making Throttle Service ready", e);
776                }
777                try {
778                    if (networkTimeUpdaterF != null) networkTimeUpdaterF.systemReady();
779                } catch (Throwable e) {
780                    reportWtf("making Network Time Service ready", e);
781                }
782                try {
783                    if (commonTimeMgmtServiceF != null) commonTimeMgmtServiceF.systemReady();
784                } catch (Throwable e) {
785                    reportWtf("making Common time management service ready", e);
786                }
787                try {
788                    if (textServiceManagerServiceF != null) textServiceManagerServiceF.systemReady();
789                } catch (Throwable e) {
790                    reportWtf("making Text Services Manager Service ready", e);
791                }
792            }
793        });
794
795        // For debug builds, log event loop stalls to dropbox for analysis.
796        if (StrictMode.conditionallyEnableDebugLogging()) {
797            Slog.i(TAG, "Enabled StrictMode for system server main thread.");
798        }
799
800        Looper.loop();
801        Slog.d(TAG, "System ServerThread is exiting!");
802    }
803
804    static final void startSystemUi(Context context) {
805        Intent intent = new Intent();
806        intent.setComponent(new ComponentName("com.android.systemui",
807                    "com.android.systemui.SystemUIService"));
808        Slog.d(TAG, "Starting service: " + intent);
809        context.startService(intent);
810    }
811}
812
813public class SystemServer {
814    private static final String TAG = "SystemServer";
815
816    public static final int FACTORY_TEST_OFF = 0;
817    public static final int FACTORY_TEST_LOW_LEVEL = 1;
818    public static final int FACTORY_TEST_HIGH_LEVEL = 2;
819
820    static Timer timer;
821    static final long SNAPSHOT_INTERVAL = 60 * 60 * 1000; // 1hr
822
823    // The earliest supported time.  We pick one day into 1970, to
824    // give any timezone code room without going into negative time.
825    private static final long EARLIEST_SUPPORTED_TIME = 86400 * 1000;
826
827    /**
828     * This method is called from Zygote to initialize the system. This will cause the native
829     * services (SurfaceFlinger, AudioFlinger, etc..) to be started. After that it will call back
830     * up into init2() to start the Android services.
831     */
832    native public static void init1(String[] args);
833
834    public static void main(String[] args) {
835        if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
836            // If a device's clock is before 1970 (before 0), a lot of
837            // APIs crash dealing with negative numbers, notably
838            // java.io.File#setLastModified, so instead we fake it and
839            // hope that time from cell towers or NTP fixes it
840            // shortly.
841            Slog.w(TAG, "System clock is before 1970; setting to 1970.");
842            SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
843        }
844
845        if (SamplingProfilerIntegration.isEnabled()) {
846            SamplingProfilerIntegration.start();
847            timer = new Timer();
848            timer.schedule(new TimerTask() {
849                @Override
850                public void run() {
851                    SamplingProfilerIntegration.writeSnapshot("system_server", null);
852                }
853            }, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL);
854        }
855
856        // Mmmmmm... more memory!
857        dalvik.system.VMRuntime.getRuntime().clearGrowthLimit();
858
859        // The system server has to run all of the time, so it needs to be
860        // as efficient as possible with its memory usage.
861        VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
862
863        System.loadLibrary("android_servers");
864        init1(args);
865    }
866
867    public static final void init2() {
868        Slog.i(TAG, "Entered the Android system server!");
869        Thread thr = new ServerThread();
870        thr.setName("android.server.ServerThread");
871        thr.start();
872    }
873}
874