SystemServer.java revision 160edb3645f8b7012bab70ae6e6e8c4a5733082b
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 com.android.server.am.ActivityManagerService;
20import com.android.internal.os.BinderInternal;
21import com.android.internal.os.SamplingProfilerIntegration;
22
23import dalvik.system.VMRuntime;
24import dalvik.system.Zygote;
25
26import android.app.ActivityManagerNative;
27import android.bluetooth.BluetoothAdapter;
28import android.content.ComponentName;
29import android.content.ContentResolver;
30import android.content.ContentService;
31import android.content.Context;
32import android.content.Intent;
33import android.content.pm.IPackageManager;
34import android.database.ContentObserver;
35import android.database.Cursor;
36import android.media.AudioService;
37import android.os.*;
38import android.provider.Contacts.People;
39import android.provider.Settings;
40import android.server.BluetoothA2dpService;
41import android.server.BluetoothService;
42import android.server.search.SearchManagerService;
43import android.util.EventLog;
44import android.util.Slog;
45import android.accounts.AccountManagerService;
46
47import java.io.File;
48import java.util.Timer;
49import java.util.TimerTask;
50
51class ServerThread extends Thread {
52    private static final String TAG = "SystemServer";
53    private final static boolean INCLUDE_DEMO = false;
54
55    private static final int LOG_BOOT_PROGRESS_SYSTEM_RUN = 3010;
56
57    private ContentResolver mContentResolver;
58
59    private class AdbSettingsObserver extends ContentObserver {
60        public AdbSettingsObserver() {
61            super(null);
62        }
63        @Override
64        public void onChange(boolean selfChange) {
65            boolean enableAdb = (Settings.Secure.getInt(mContentResolver,
66                Settings.Secure.ADB_ENABLED, 0) > 0);
67            // setting this secure property will start or stop adbd
68           SystemProperties.set("persist.service.adb.enable", enableAdb ? "1" : "0");
69        }
70    }
71
72    @Override
73    public void run() {
74        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN,
75            SystemClock.uptimeMillis());
76
77        Looper.prepare();
78
79        android.os.Process.setThreadPriority(
80                android.os.Process.THREAD_PRIORITY_FOREGROUND);
81
82        BinderInternal.disableBackgroundScheduling(true);
83        android.os.Process.setCanSelfBackground(false);
84
85        String factoryTestStr = SystemProperties.get("ro.factorytest");
86        int factoryTest = "".equals(factoryTestStr) ? SystemServer.FACTORY_TEST_OFF
87                : Integer.parseInt(factoryTestStr);
88
89        LightsService lights = null;
90        PowerManagerService power = null;
91        BatteryService battery = null;
92        ConnectivityService connectivity = null;
93        IPackageManager pm = null;
94        Context context = null;
95        WindowManagerService wm = null;
96        BluetoothService bluetooth = null;
97        BluetoothA2dpService bluetoothA2dp = null;
98        HeadsetObserver headset = null;
99        DockObserver dock = null;
100        UsbObserver usb = null;
101        UiModeManagerService uiMode = null;
102        RecognitionManagerService recognition = null;
103        ThrottleService throttle = null;
104
105        // Critical services...
106        try {
107            Slog.i(TAG, "Entropy Service");
108            ServiceManager.addService("entropy", new EntropyService());
109
110            Slog.i(TAG, "Power Manager");
111            power = new PowerManagerService();
112            ServiceManager.addService(Context.POWER_SERVICE, power);
113
114            Slog.i(TAG, "Activity Manager");
115            context = ActivityManagerService.main(factoryTest);
116
117            Slog.i(TAG, "Telephony Registry");
118            ServiceManager.addService("telephony.registry", new TelephonyRegistry(context));
119
120            AttributeCache.init(context);
121
122            Slog.i(TAG, "Package Manager");
123            pm = PackageManagerService.main(context,
124                    factoryTest != SystemServer.FACTORY_TEST_OFF);
125
126            ActivityManagerService.setSystemProcess();
127
128            mContentResolver = context.getContentResolver();
129
130            // The AccountManager must come before the ContentService
131            try {
132                Slog.i(TAG, "Account Manager");
133                ServiceManager.addService(Context.ACCOUNT_SERVICE,
134                        new AccountManagerService(context));
135            } catch (Throwable e) {
136                Slog.e(TAG, "Failure starting Account Manager", e);
137            }
138
139            Slog.i(TAG, "Content Manager");
140            ContentService.main(context,
141                    factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL);
142
143            Slog.i(TAG, "System Content Providers");
144            ActivityManagerService.installSystemProviders();
145
146            Slog.i(TAG, "Battery Service");
147            battery = new BatteryService(context);
148            ServiceManager.addService("battery", battery);
149
150            Slog.i(TAG, "Lights Service");
151            lights = new LightsService(context);
152
153            Slog.i(TAG, "Vibrator Service");
154            ServiceManager.addService("vibrator", new VibratorService(context));
155
156            // only initialize the power service after we have started the
157            // lights service, content providers and the battery service.
158            power.init(context, lights, ActivityManagerService.getDefault(), battery);
159
160            Slog.i(TAG, "Alarm Manager");
161            AlarmManagerService alarm = new AlarmManagerService(context);
162            ServiceManager.addService(Context.ALARM_SERVICE, alarm);
163
164            Slog.i(TAG, "Init Watchdog");
165            Watchdog.getInstance().init(context, battery, power, alarm,
166                    ActivityManagerService.self());
167
168            // Sensor Service is needed by Window Manager, so this goes first
169            Slog.i(TAG, "Sensor Service");
170            ServiceManager.addService(Context.SENSOR_SERVICE, new SensorService(context));
171
172            Slog.i(TAG, "Window Manager");
173            wm = WindowManagerService.main(context, power,
174                    factoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL);
175            ServiceManager.addService(Context.WINDOW_SERVICE, wm);
176
177            ((ActivityManagerService)ServiceManager.getService("activity"))
178                    .setWindowManager(wm);
179
180            // Skip Bluetooth if we have an emulator kernel
181            // TODO: Use a more reliable check to see if this product should
182            // support Bluetooth - see bug 988521
183            if (SystemProperties.get("ro.kernel.qemu").equals("1")) {
184                Slog.i(TAG, "Registering null Bluetooth Service (emulator)");
185                ServiceManager.addService(BluetoothAdapter.BLUETOOTH_SERVICE, null);
186            } else if (factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
187                Slog.i(TAG, "Registering null Bluetooth Service (factory test)");
188                ServiceManager.addService(BluetoothAdapter.BLUETOOTH_SERVICE, null);
189            } else {
190                Slog.i(TAG, "Bluetooth Service");
191                bluetooth = new BluetoothService(context);
192                ServiceManager.addService(BluetoothAdapter.BLUETOOTH_SERVICE, bluetooth);
193                bluetooth.initAfterRegistration();
194                bluetoothA2dp = new BluetoothA2dpService(context, bluetooth);
195                ServiceManager.addService(BluetoothA2dpService.BLUETOOTH_A2DP_SERVICE,
196                                          bluetoothA2dp);
197
198                int bluetoothOn = Settings.Secure.getInt(mContentResolver,
199                    Settings.Secure.BLUETOOTH_ON, 0);
200                if (bluetoothOn > 0) {
201                    bluetooth.enable();
202                }
203            }
204
205        } catch (RuntimeException e) {
206            Slog.e("System", "Failure starting core service", e);
207        }
208
209        DevicePolicyManagerService devicePolicy = null;
210        StatusBarManagerService statusBar = null;
211        InputMethodManagerService imm = null;
212        AppWidgetService appWidget = null;
213        NotificationManagerService notification = null;
214        WallpaperManagerService wallpaper = null;
215        LocationManagerService location = null;
216
217        if (factoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
218            try {
219                Slog.i(TAG, "Device Policy");
220                devicePolicy = new DevicePolicyManagerService(context);
221                ServiceManager.addService(Context.DEVICE_POLICY_SERVICE, devicePolicy);
222            } catch (Throwable e) {
223                Slog.e(TAG, "Failure starting DevicePolicyService", e);
224            }
225
226            try {
227                Slog.i(TAG, "Status Bar");
228                statusBar = new StatusBarManagerService(context);
229                ServiceManager.addService(Context.STATUS_BAR_SERVICE, statusBar);
230            } catch (Throwable e) {
231                Slog.e(TAG, "Failure starting StatusBarManagerService", e);
232            }
233
234            try {
235                Slog.i(TAG, "Clipboard Service");
236                ServiceManager.addService(Context.CLIPBOARD_SERVICE,
237                        new ClipboardService(context));
238            } catch (Throwable e) {
239                Slog.e(TAG, "Failure starting Clipboard Service", e);
240            }
241
242            try {
243                Slog.i(TAG, "Input Method Service");
244                imm = new InputMethodManagerService(context, statusBar);
245                ServiceManager.addService(Context.INPUT_METHOD_SERVICE, imm);
246            } catch (Throwable e) {
247                Slog.e(TAG, "Failure starting Input Manager Service", e);
248            }
249
250            try {
251                Slog.i(TAG, "NetStat Service");
252                ServiceManager.addService("netstat", new NetStatService(context));
253            } catch (Throwable e) {
254                Slog.e(TAG, "Failure starting NetStat Service", e);
255            }
256
257            try {
258                Slog.i(TAG, "NetworkManagement Service");
259                ServiceManager.addService(
260                        Context.NETWORKMANAGEMENT_SERVICE, new NetworkManagementService(context));
261            } catch (Throwable e) {
262                Slog.e(TAG, "Failure starting NetworkManagement Service", e);
263            }
264
265            try {
266                Slog.i(TAG, "Connectivity Service");
267                connectivity = ConnectivityService.getInstance(context);
268                ServiceManager.addService(Context.CONNECTIVITY_SERVICE, connectivity);
269            } catch (Throwable e) {
270                Slog.e(TAG, "Failure starting Connectivity Service", e);
271            }
272
273            try {
274                Slog.i(TAG, "Throttle Service");
275                throttle = new ThrottleService(context);
276                ServiceManager.addService(
277                        Context.THROTTLE_SERVICE, throttle);
278            } catch (Throwable e) {
279                Slog.e(TAG, "Failure starting ThrottleService", 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              Slog.e(TAG, "Failure starting Accessibility Manager", e);
288            }
289
290            try {
291                /*
292                 * NotificationManagerService is dependant on MountService,
293                 * (for media / usb notifications) so we must start MountService first.
294                 */
295                Slog.i(TAG, "Mount Service");
296                ServiceManager.addService("mount", new MountService(context));
297            } catch (Throwable e) {
298                Slog.e(TAG, "Failure starting Mount Service", e);
299            }
300
301            try {
302                Slog.i(TAG, "Notification Manager");
303                notification = new NotificationManagerService(context, statusBar, lights);
304                ServiceManager.addService(Context.NOTIFICATION_SERVICE, notification);
305            } catch (Throwable e) {
306                Slog.e(TAG, "Failure starting Notification Manager", e);
307            }
308
309            try {
310                Slog.i(TAG, "Device Storage Monitor");
311                ServiceManager.addService(DeviceStorageMonitorService.SERVICE,
312                        new DeviceStorageMonitorService(context));
313            } catch (Throwable e) {
314                Slog.e(TAG, "Failure starting DeviceStorageMonitor service", e);
315            }
316
317            try {
318                Slog.i(TAG, "Location Manager");
319                location = new LocationManagerService(context);
320                ServiceManager.addService(Context.LOCATION_SERVICE, location);
321            } catch (Throwable e) {
322                Slog.e(TAG, "Failure starting Location Manager", e);
323            }
324
325            try {
326                Slog.i(TAG, "Search Service");
327                ServiceManager.addService(Context.SEARCH_SERVICE,
328                        new SearchManagerService(context));
329            } catch (Throwable e) {
330                Slog.e(TAG, "Failure starting Search Service", e);
331            }
332
333            if (INCLUDE_DEMO) {
334                Slog.i(TAG, "Installing demo data...");
335                (new DemoThread(context)).start();
336            }
337
338            try {
339                Slog.i(TAG, "DropBox Service");
340                ServiceManager.addService(Context.DROPBOX_SERVICE,
341                        new DropBoxManagerService(context, new File("/data/system/dropbox")));
342            } catch (Throwable e) {
343                Slog.e(TAG, "Failure starting DropBoxManagerService", e);
344            }
345
346            try {
347                Slog.i(TAG, "Wallpaper Service");
348                wallpaper = new WallpaperManagerService(context);
349                ServiceManager.addService(Context.WALLPAPER_SERVICE, wallpaper);
350            } catch (Throwable e) {
351                Slog.e(TAG, "Failure starting Wallpaper Service", e);
352            }
353
354            try {
355                Slog.i(TAG, "Audio Service");
356                ServiceManager.addService(Context.AUDIO_SERVICE, new AudioService(context));
357            } catch (Throwable e) {
358                Slog.e(TAG, "Failure starting Audio Service", e);
359            }
360
361            try {
362                Slog.i(TAG, "Headset Observer");
363                // Listen for wired headset changes
364                headset = new HeadsetObserver(context);
365            } catch (Throwable e) {
366                Slog.e(TAG, "Failure starting HeadsetObserver", e);
367            }
368
369            try {
370                Slog.i(TAG, "Dock Observer");
371                // Listen for dock station changes
372                dock = new DockObserver(context, power);
373            } catch (Throwable e) {
374                Slog.e(TAG, "Failure starting DockObserver", e);
375            }
376
377            try {
378                Slog.i(TAG, "USB Observer");
379                // Listen for USB changes
380                usb = new UsbObserver(context);
381            } catch (Throwable e) {
382                Slog.e(TAG, "Failure starting UsbObserver", e);
383            }
384
385            try {
386                Slog.i(TAG, "UI Mode Manager Service");
387                // Listen for UI mode changes
388                uiMode = new UiModeManagerService(context);
389            } catch (Throwable e) {
390                Slog.e(TAG, "Failure starting UiModeManagerService", e);
391            }
392
393            try {
394                Slog.i(TAG, "Backup Service");
395                ServiceManager.addService(Context.BACKUP_SERVICE,
396                        new BackupManagerService(context));
397            } catch (Throwable e) {
398                Slog.e(TAG, "Failure starting Backup Service", e);
399            }
400
401            try {
402                Slog.i(TAG, "AppWidget Service");
403                appWidget = new AppWidgetService(context);
404                ServiceManager.addService(Context.APPWIDGET_SERVICE, appWidget);
405            } catch (Throwable e) {
406                Slog.e(TAG, "Failure starting AppWidget Service", e);
407            }
408
409            try {
410                Slog.i(TAG, "Recognition Service");
411                recognition = new RecognitionManagerService(context);
412            } catch (Throwable e) {
413                Slog.e(TAG, "Failure starting Recognition Service", e);
414            }
415
416            try {
417                Slog.i(TAG, "DiskStats Service");
418                ServiceManager.addService("diskstats", new DiskStatsService(context));
419            } catch (Throwable e) {
420                Slog.e(TAG, "Failure starting DiskStats Service", e);
421            }
422        }
423
424        // make sure the ADB_ENABLED setting value matches the secure property value
425        Settings.Secure.putInt(mContentResolver, Settings.Secure.ADB_ENABLED,
426                "1".equals(SystemProperties.get("persist.service.adb.enable")) ? 1 : 0);
427
428        // register observer to listen for settings changes
429        mContentResolver.registerContentObserver(Settings.Secure.getUriFor(Settings.Secure.ADB_ENABLED),
430                false, new AdbSettingsObserver());
431
432        // Before things start rolling, be sure we have decided whether
433        // we are in safe mode.
434        final boolean safeMode = wm.detectSafeMode();
435        if (safeMode) {
436            try {
437                ActivityManagerNative.getDefault().enterSafeMode();
438                // Post the safe mode state in the Zygote class
439                Zygote.systemInSafeMode = true;
440                // Disable the JIT for the system_server process
441                VMRuntime.getRuntime().disableJitCompilation();
442            } catch (RemoteException e) {
443            }
444        } else {
445            // Enable the JIT for the system_server process
446            VMRuntime.getRuntime().startJitCompilation();
447        }
448
449        // It is now time to start up the app processes...
450
451        if (devicePolicy != null) {
452            devicePolicy.systemReady();
453        }
454
455        if (notification != null) {
456            notification.systemReady();
457        }
458
459        if (statusBar != null) {
460            statusBar.systemReady();
461        }
462        wm.systemReady();
463        power.systemReady();
464        try {
465            pm.systemReady();
466        } catch (RemoteException e) {
467        }
468
469        // These are needed to propagate to the runnable below.
470        final StatusBarManagerService statusBarF = statusBar;
471        final BatteryService batteryF = battery;
472        final ConnectivityService connectivityF = connectivity;
473        final DockObserver dockF = dock;
474        final UsbObserver usbF = usb;
475        final ThrottleService throttleF = throttle;
476        final UiModeManagerService uiModeF = uiMode;
477        final AppWidgetService appWidgetF = appWidget;
478        final WallpaperManagerService wallpaperF = wallpaper;
479        final InputMethodManagerService immF = imm;
480        final RecognitionManagerService recognitionF = recognition;
481        final LocationManagerService locationF = location;
482
483        // We now tell the activity manager it is okay to run third party
484        // code.  It will call back into us once it has gotten to the state
485        // where third party code can really run (but before it has actually
486        // started launching the initial applications), for us to complete our
487        // initialization.
488        ((ActivityManagerService)ActivityManagerNative.getDefault())
489                .systemReady(new Runnable() {
490            public void run() {
491                Slog.i(TAG, "Making services ready");
492
493                if (statusBarF != null) statusBarF.systemReady2();
494                if (batteryF != null) batteryF.systemReady();
495                if (connectivityF != null) connectivityF.systemReady();
496                if (dockF != null) dockF.systemReady();
497                if (usbF != null) usbF.systemReady();
498                if (uiModeF != null) uiModeF.systemReady();
499                if (recognitionF != null) recognitionF.systemReady();
500                Watchdog.getInstance().start();
501
502                // It is now okay to let the various system services start their
503                // third party code...
504
505                if (appWidgetF != null) appWidgetF.systemReady(safeMode);
506                if (wallpaperF != null) wallpaperF.systemReady();
507                if (immF != null) immF.systemReady();
508                if (locationF != null) locationF.systemReady();
509                if (throttleF != null) throttleF.systemReady();
510            }
511        });
512
513        Looper.loop();
514        Slog.d(TAG, "System ServerThread is exiting!");
515    }
516}
517
518class DemoThread extends Thread
519{
520    DemoThread(Context context)
521    {
522        mContext = context;
523    }
524
525    @Override
526    public void run()
527    {
528        try {
529            Cursor c = mContext.getContentResolver().query(People.CONTENT_URI, null, null, null, null);
530            boolean hasData = c != null && c.moveToFirst();
531            if (c != null) {
532                c.deactivate();
533            }
534            if (!hasData) {
535                DemoDataSet dataset = new DemoDataSet();
536                dataset.add(mContext);
537            }
538        } catch (Throwable e) {
539            Slog.e("SystemServer", "Failure installing demo data", e);
540        }
541
542    }
543
544    Context mContext;
545}
546
547public class SystemServer
548{
549    private static final String TAG = "SystemServer";
550
551    public static final int FACTORY_TEST_OFF = 0;
552    public static final int FACTORY_TEST_LOW_LEVEL = 1;
553    public static final int FACTORY_TEST_HIGH_LEVEL = 2;
554
555    static Timer timer;
556    static final long SNAPSHOT_INTERVAL = 60 * 60 * 1000; // 1hr
557
558    /**
559     * This method is called from Zygote to initialize the system. This will cause the native
560     * services (SurfaceFlinger, AudioFlinger, etc..) to be started. After that it will call back
561     * up into init2() to start the Android services.
562     */
563    native public static void init1(String[] args);
564
565    public static void main(String[] args) {
566        if (SamplingProfilerIntegration.isEnabled()) {
567            SamplingProfilerIntegration.start();
568            timer = new Timer();
569            timer.schedule(new TimerTask() {
570                @Override
571                public void run() {
572                    SamplingProfilerIntegration.writeSnapshot("system_server");
573                }
574            }, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL);
575        }
576
577        // The system server has to run all of the time, so it needs to be
578        // as efficient as possible with its memory usage.
579        VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
580
581        System.loadLibrary("android_servers");
582        init1(args);
583    }
584
585    public static final void init2() {
586        Slog.i(TAG, "Entered the Android system server!");
587        Thread thr = new ServerThread();
588        thr.setName("android.server.ServerThread");
589        thr.start();
590    }
591}
592