1/*
2 * Copyright (C) 2015 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 android.app;
18
19import com.android.internal.app.IAppOpsService;
20import com.android.internal.app.ISoundTriggerService;
21import com.android.internal.appwidget.IAppWidgetService;
22import com.android.internal.os.IDropBoxManagerService;
23
24import android.accounts.AccountManager;
25import android.accounts.IAccountManager;
26import android.app.admin.DevicePolicyManager;
27import android.app.job.IJobScheduler;
28import android.app.job.JobScheduler;
29import android.app.trust.TrustManager;
30import android.app.usage.IUsageStatsManager;
31import android.app.usage.NetworkStatsManager;
32import android.app.usage.UsageStatsManager;
33import android.appwidget.AppWidgetManager;
34import android.bluetooth.BluetoothManager;
35import android.content.ClipboardManager;
36import android.content.Context;
37import android.content.IRestrictionsManager;
38import android.content.RestrictionsManager;
39import android.content.pm.ILauncherApps;
40import android.content.pm.IShortcutService;
41import android.content.pm.LauncherApps;
42import android.content.pm.ShortcutManager;
43import android.content.res.Resources;
44import android.hardware.ConsumerIrManager;
45import android.hardware.ISerialManager;
46import android.hardware.SensorManager;
47import android.hardware.SerialManager;
48import android.hardware.SystemSensorManager;
49import android.hardware.camera2.CameraManager;
50import android.hardware.display.DisplayManager;
51import android.hardware.hdmi.HdmiControlManager;
52import android.hardware.hdmi.IHdmiControlService;
53import android.hardware.input.InputManager;
54import android.hardware.location.ContextHubManager;
55import android.hardware.usb.IUsbManager;
56import android.hardware.usb.UsbManager;
57import android.hardware.radio.RadioManager;
58import android.location.CountryDetector;
59import android.location.ICountryDetector;
60import android.location.ILocationManager;
61import android.location.LocationManager;
62import android.media.AudioManager;
63import android.media.MediaRouter;
64import android.media.midi.IMidiManager;
65import android.media.midi.MidiManager;
66import android.media.projection.MediaProjectionManager;
67import android.media.session.MediaSessionManager;
68import android.media.soundtrigger.SoundTriggerManager;
69import android.media.tv.ITvInputManager;
70import android.media.tv.TvInputManager;
71import android.net.ConnectivityManager;
72import android.net.ConnectivityThread;
73import android.net.EthernetManager;
74import android.net.IConnectivityManager;
75import android.net.IEthernetManager;
76import android.net.INetworkPolicyManager;
77import android.net.NetworkPolicyManager;
78import android.net.NetworkScoreManager;
79import android.net.nsd.INsdManager;
80import android.net.nsd.NsdManager;
81import android.net.wifi.IRttManager;
82import android.net.wifi.IWifiManager;
83import android.net.wifi.IWifiScanner;
84import android.net.wifi.RttManager;
85import android.net.wifi.WifiManager;
86import android.net.wifi.WifiScanner;
87import android.net.wifi.nan.IWifiNanManager;
88import android.net.wifi.nan.WifiNanManager;
89import android.net.wifi.p2p.IWifiP2pManager;
90import android.net.wifi.p2p.WifiP2pManager;
91import android.nfc.NfcManager;
92import android.os.BatteryManager;
93import android.os.DropBoxManager;
94import android.os.HardwarePropertiesManager;
95import android.os.IBinder;
96import android.os.IHardwarePropertiesManager;
97import android.os.IPowerManager;
98import android.os.IRecoverySystem;
99import android.os.IUserManager;
100import android.os.PowerManager;
101import android.os.Process;
102import android.os.RecoverySystem;
103import android.os.ServiceManager;
104import android.os.SystemVibrator;
105import android.os.UserHandle;
106import android.os.UserManager;
107import android.os.Vibrator;
108import android.os.health.SystemHealthManager;
109import android.os.storage.StorageManager;
110import android.print.IPrintManager;
111import android.print.PrintManager;
112import android.hardware.fingerprint.FingerprintManager;
113import android.hardware.fingerprint.IFingerprintService;
114import android.service.persistentdata.IPersistentDataBlockService;
115import android.service.persistentdata.PersistentDataBlockManager;
116import android.telecom.TelecomManager;
117import android.telephony.CarrierConfigManager;
118import android.telephony.SubscriptionManager;
119import android.telephony.TelephonyManager;
120import android.util.Log;
121import android.view.ContextThemeWrapper;
122import android.view.LayoutInflater;
123import com.android.internal.policy.PhoneLayoutInflater;
124import android.view.WindowManager;
125import android.view.WindowManagerImpl;
126import android.view.accessibility.AccessibilityManager;
127import android.view.accessibility.CaptioningManager;
128import android.view.inputmethod.InputMethodManager;
129import android.view.textservice.TextServicesManager;
130
131import java.util.HashMap;
132
133/**
134 * Manages all of the system services that can be returned by {@link Context#getSystemService}.
135 * Used by {@link ContextImpl}.
136 */
137final class SystemServiceRegistry {
138    private final static String TAG = "SystemServiceRegistry";
139
140    // Service registry information.
141    // This information is never changed once static initialization has completed.
142    private static final HashMap<Class<?>, String> SYSTEM_SERVICE_NAMES =
143            new HashMap<Class<?>, String>();
144    private static final HashMap<String, ServiceFetcher<?>> SYSTEM_SERVICE_FETCHERS =
145            new HashMap<String, ServiceFetcher<?>>();
146    private static int sServiceCacheSize;
147
148    // Not instantiable.
149    private SystemServiceRegistry() { }
150
151    static {
152        registerService(Context.ACCESSIBILITY_SERVICE, AccessibilityManager.class,
153                new CachedServiceFetcher<AccessibilityManager>() {
154            @Override
155            public AccessibilityManager createService(ContextImpl ctx) {
156                return AccessibilityManager.getInstance(ctx);
157            }});
158
159        registerService(Context.CAPTIONING_SERVICE, CaptioningManager.class,
160                new CachedServiceFetcher<CaptioningManager>() {
161            @Override
162            public CaptioningManager createService(ContextImpl ctx) {
163                return new CaptioningManager(ctx);
164            }});
165
166        registerService(Context.ACCOUNT_SERVICE, AccountManager.class,
167                new CachedServiceFetcher<AccountManager>() {
168            @Override
169            public AccountManager createService(ContextImpl ctx) {
170                IBinder b = ServiceManager.getService(Context.ACCOUNT_SERVICE);
171                IAccountManager service = IAccountManager.Stub.asInterface(b);
172                return new AccountManager(ctx, service);
173            }});
174
175        registerService(Context.ACTIVITY_SERVICE, ActivityManager.class,
176                new CachedServiceFetcher<ActivityManager>() {
177            @Override
178            public ActivityManager createService(ContextImpl ctx) {
179                return new ActivityManager(ctx.getOuterContext(), ctx.mMainThread.getHandler());
180            }});
181
182        registerService(Context.ALARM_SERVICE, AlarmManager.class,
183                new CachedServiceFetcher<AlarmManager>() {
184            @Override
185            public AlarmManager createService(ContextImpl ctx) {
186                IBinder b = ServiceManager.getService(Context.ALARM_SERVICE);
187                IAlarmManager service = IAlarmManager.Stub.asInterface(b);
188                return new AlarmManager(service, ctx);
189            }});
190
191        registerService(Context.AUDIO_SERVICE, AudioManager.class,
192                new CachedServiceFetcher<AudioManager>() {
193            @Override
194            public AudioManager createService(ContextImpl ctx) {
195                return new AudioManager(ctx);
196            }});
197
198        registerService(Context.MEDIA_ROUTER_SERVICE, MediaRouter.class,
199                new CachedServiceFetcher<MediaRouter>() {
200            @Override
201            public MediaRouter createService(ContextImpl ctx) {
202                return new MediaRouter(ctx);
203            }});
204
205        registerService(Context.BLUETOOTH_SERVICE, BluetoothManager.class,
206                new CachedServiceFetcher<BluetoothManager>() {
207            @Override
208            public BluetoothManager createService(ContextImpl ctx) {
209                return new BluetoothManager(ctx);
210            }});
211
212        registerService(Context.HDMI_CONTROL_SERVICE, HdmiControlManager.class,
213                new StaticServiceFetcher<HdmiControlManager>() {
214            @Override
215            public HdmiControlManager createService() {
216                IBinder b = ServiceManager.getService(Context.HDMI_CONTROL_SERVICE);
217                return new HdmiControlManager(IHdmiControlService.Stub.asInterface(b));
218            }});
219
220        registerService(Context.CLIPBOARD_SERVICE, ClipboardManager.class,
221                new CachedServiceFetcher<ClipboardManager>() {
222            @Override
223            public ClipboardManager createService(ContextImpl ctx) {
224                return new ClipboardManager(ctx.getOuterContext(),
225                        ctx.mMainThread.getHandler());
226            }});
227
228        // The clipboard service moved to a new package.  If someone asks for the old
229        // interface by class then we want to redirect over to the new interface instead
230        // (which extends it).
231        SYSTEM_SERVICE_NAMES.put(android.text.ClipboardManager.class, Context.CLIPBOARD_SERVICE);
232
233        registerService(Context.CONNECTIVITY_SERVICE, ConnectivityManager.class,
234                new StaticApplicationContextServiceFetcher<ConnectivityManager>() {
235            @Override
236            public ConnectivityManager createService(Context context) {
237                IBinder b = ServiceManager.getService(Context.CONNECTIVITY_SERVICE);
238                IConnectivityManager service = IConnectivityManager.Stub.asInterface(b);
239                return new ConnectivityManager(context, service);
240            }});
241
242        registerService(Context.COUNTRY_DETECTOR, CountryDetector.class,
243                new StaticServiceFetcher<CountryDetector>() {
244            @Override
245            public CountryDetector createService() {
246                IBinder b = ServiceManager.getService(Context.COUNTRY_DETECTOR);
247                return new CountryDetector(ICountryDetector.Stub.asInterface(b));
248            }});
249
250        registerService(Context.DEVICE_POLICY_SERVICE, DevicePolicyManager.class,
251                new CachedServiceFetcher<DevicePolicyManager>() {
252            @Override
253            public DevicePolicyManager createService(ContextImpl ctx) {
254                return DevicePolicyManager.create(ctx);
255            }});
256
257        registerService(Context.DOWNLOAD_SERVICE, DownloadManager.class,
258                new CachedServiceFetcher<DownloadManager>() {
259            @Override
260            public DownloadManager createService(ContextImpl ctx) {
261                return new DownloadManager(ctx);
262            }});
263
264        registerService(Context.BATTERY_SERVICE, BatteryManager.class,
265                new StaticServiceFetcher<BatteryManager>() {
266            @Override
267            public BatteryManager createService() {
268                return new BatteryManager();
269            }});
270
271        registerService(Context.NFC_SERVICE, NfcManager.class,
272                new CachedServiceFetcher<NfcManager>() {
273            @Override
274            public NfcManager createService(ContextImpl ctx) {
275                return new NfcManager(ctx);
276            }});
277
278        registerService(Context.DROPBOX_SERVICE, DropBoxManager.class,
279                new CachedServiceFetcher<DropBoxManager>() {
280            @Override
281            public DropBoxManager createService(ContextImpl ctx) {
282                IBinder b = ServiceManager.getService(Context.DROPBOX_SERVICE);
283                IDropBoxManagerService service = IDropBoxManagerService.Stub.asInterface(b);
284                if (service == null) {
285                    // Don't return a DropBoxManager that will NPE upon use.
286                    // This also avoids caching a broken DropBoxManager in
287                    // getDropBoxManager during early boot, before the
288                    // DROPBOX_SERVICE is registered.
289                    return null;
290                }
291                return new DropBoxManager(ctx, service);
292            }});
293
294        registerService(Context.INPUT_SERVICE, InputManager.class,
295                new StaticServiceFetcher<InputManager>() {
296            @Override
297            public InputManager createService() {
298                return InputManager.getInstance();
299            }});
300
301        registerService(Context.DISPLAY_SERVICE, DisplayManager.class,
302                new CachedServiceFetcher<DisplayManager>() {
303            @Override
304            public DisplayManager createService(ContextImpl ctx) {
305                return new DisplayManager(ctx.getOuterContext());
306            }});
307
308        registerService(Context.INPUT_METHOD_SERVICE, InputMethodManager.class,
309                new StaticServiceFetcher<InputMethodManager>() {
310            @Override
311            public InputMethodManager createService() {
312                return InputMethodManager.getInstance();
313            }});
314
315        registerService(Context.TEXT_SERVICES_MANAGER_SERVICE, TextServicesManager.class,
316                new StaticServiceFetcher<TextServicesManager>() {
317            @Override
318            public TextServicesManager createService() {
319                return TextServicesManager.getInstance();
320            }});
321
322        registerService(Context.KEYGUARD_SERVICE, KeyguardManager.class,
323                new StaticServiceFetcher<KeyguardManager>() {
324            @Override
325            public KeyguardManager createService() {
326                return new KeyguardManager();
327            }});
328
329        registerService(Context.LAYOUT_INFLATER_SERVICE, LayoutInflater.class,
330                new CachedServiceFetcher<LayoutInflater>() {
331            @Override
332            public LayoutInflater createService(ContextImpl ctx) {
333                return new PhoneLayoutInflater(ctx.getOuterContext());
334            }});
335
336        registerService(Context.LOCATION_SERVICE, LocationManager.class,
337                new CachedServiceFetcher<LocationManager>() {
338            @Override
339            public LocationManager createService(ContextImpl ctx) {
340                IBinder b = ServiceManager.getService(Context.LOCATION_SERVICE);
341                return new LocationManager(ctx, ILocationManager.Stub.asInterface(b));
342            }});
343
344        registerService(Context.NETWORK_POLICY_SERVICE, NetworkPolicyManager.class,
345                new CachedServiceFetcher<NetworkPolicyManager>() {
346            @Override
347            public NetworkPolicyManager createService(ContextImpl ctx) {
348                return new NetworkPolicyManager(ctx, INetworkPolicyManager.Stub.asInterface(
349                        ServiceManager.getService(Context.NETWORK_POLICY_SERVICE)));
350            }});
351
352        registerService(Context.NOTIFICATION_SERVICE, NotificationManager.class,
353                new CachedServiceFetcher<NotificationManager>() {
354            @Override
355            public NotificationManager createService(ContextImpl ctx) {
356                final Context outerContext = ctx.getOuterContext();
357                return new NotificationManager(
358                    new ContextThemeWrapper(outerContext,
359                            Resources.selectSystemTheme(0,
360                                    outerContext.getApplicationInfo().targetSdkVersion,
361                                    com.android.internal.R.style.Theme_Dialog,
362                                    com.android.internal.R.style.Theme_Holo_Dialog,
363                                    com.android.internal.R.style.Theme_DeviceDefault_Dialog,
364                                    com.android.internal.R.style.Theme_DeviceDefault_Light_Dialog)),
365                    ctx.mMainThread.getHandler());
366            }});
367
368        registerService(Context.NSD_SERVICE, NsdManager.class,
369                new CachedServiceFetcher<NsdManager>() {
370            @Override
371            public NsdManager createService(ContextImpl ctx) {
372                IBinder b = ServiceManager.getService(Context.NSD_SERVICE);
373                INsdManager service = INsdManager.Stub.asInterface(b);
374                return new NsdManager(ctx.getOuterContext(), service);
375            }});
376
377        registerService(Context.POWER_SERVICE, PowerManager.class,
378                new CachedServiceFetcher<PowerManager>() {
379            @Override
380            public PowerManager createService(ContextImpl ctx) {
381                IBinder b = ServiceManager.getService(Context.POWER_SERVICE);
382                IPowerManager service = IPowerManager.Stub.asInterface(b);
383                if (service == null) {
384                    Log.wtf(TAG, "Failed to get power manager service.");
385                }
386                return new PowerManager(ctx.getOuterContext(),
387                        service, ctx.mMainThread.getHandler());
388            }});
389
390        registerService(Context.RECOVERY_SERVICE, RecoverySystem.class,
391                new CachedServiceFetcher<RecoverySystem>() {
392            @Override
393            public RecoverySystem createService(ContextImpl ctx) {
394                IBinder b = ServiceManager.getService(Context.RECOVERY_SERVICE);
395                IRecoverySystem service = IRecoverySystem.Stub.asInterface(b);
396                if (service == null) {
397                    Log.wtf(TAG, "Failed to get recovery service.");
398                }
399                return new RecoverySystem(service);
400            }});
401
402        registerService(Context.SEARCH_SERVICE, SearchManager.class,
403                new CachedServiceFetcher<SearchManager>() {
404            @Override
405            public SearchManager createService(ContextImpl ctx) {
406                return new SearchManager(ctx.getOuterContext(),
407                        ctx.mMainThread.getHandler());
408            }});
409
410        registerService(Context.SENSOR_SERVICE, SensorManager.class,
411                new CachedServiceFetcher<SensorManager>() {
412            @Override
413            public SensorManager createService(ContextImpl ctx) {
414                return new SystemSensorManager(ctx.getOuterContext(),
415                  ctx.mMainThread.getHandler().getLooper());
416            }});
417
418        registerService(Context.STATUS_BAR_SERVICE, StatusBarManager.class,
419                new CachedServiceFetcher<StatusBarManager>() {
420            @Override
421            public StatusBarManager createService(ContextImpl ctx) {
422                return new StatusBarManager(ctx.getOuterContext());
423            }});
424
425        registerService(Context.STORAGE_SERVICE, StorageManager.class,
426                new CachedServiceFetcher<StorageManager>() {
427            @Override
428            public StorageManager createService(ContextImpl ctx) {
429                return new StorageManager(ctx, ctx.mMainThread.getHandler().getLooper());
430            }});
431
432        registerService(Context.TELEPHONY_SERVICE, TelephonyManager.class,
433                new CachedServiceFetcher<TelephonyManager>() {
434            @Override
435            public TelephonyManager createService(ContextImpl ctx) {
436                return new TelephonyManager(ctx.getOuterContext());
437            }});
438
439        registerService(Context.TELEPHONY_SUBSCRIPTION_SERVICE, SubscriptionManager.class,
440                new CachedServiceFetcher<SubscriptionManager>() {
441            @Override
442            public SubscriptionManager createService(ContextImpl ctx) {
443                return new SubscriptionManager(ctx.getOuterContext());
444            }});
445
446        registerService(Context.CARRIER_CONFIG_SERVICE, CarrierConfigManager.class,
447                new CachedServiceFetcher<CarrierConfigManager>() {
448            @Override
449            public CarrierConfigManager createService(ContextImpl ctx) {
450                return new CarrierConfigManager();
451            }});
452
453        registerService(Context.TELECOM_SERVICE, TelecomManager.class,
454                new CachedServiceFetcher<TelecomManager>() {
455            @Override
456            public TelecomManager createService(ContextImpl ctx) {
457                return new TelecomManager(ctx.getOuterContext());
458            }});
459
460        registerService(Context.UI_MODE_SERVICE, UiModeManager.class,
461                new CachedServiceFetcher<UiModeManager>() {
462            @Override
463            public UiModeManager createService(ContextImpl ctx) {
464                return new UiModeManager();
465            }});
466
467        registerService(Context.USB_SERVICE, UsbManager.class,
468                new CachedServiceFetcher<UsbManager>() {
469            @Override
470            public UsbManager createService(ContextImpl ctx) {
471                IBinder b = ServiceManager.getService(Context.USB_SERVICE);
472                return new UsbManager(ctx, IUsbManager.Stub.asInterface(b));
473            }});
474
475        registerService(Context.SERIAL_SERVICE, SerialManager.class,
476                new CachedServiceFetcher<SerialManager>() {
477            @Override
478            public SerialManager createService(ContextImpl ctx) {
479                IBinder b = ServiceManager.getService(Context.SERIAL_SERVICE);
480                return new SerialManager(ctx, ISerialManager.Stub.asInterface(b));
481            }});
482
483        registerService(Context.VIBRATOR_SERVICE, Vibrator.class,
484                new CachedServiceFetcher<Vibrator>() {
485            @Override
486            public Vibrator createService(ContextImpl ctx) {
487                return new SystemVibrator(ctx);
488            }});
489
490        registerService(Context.WALLPAPER_SERVICE, WallpaperManager.class,
491                new CachedServiceFetcher<WallpaperManager>() {
492            @Override
493            public WallpaperManager createService(ContextImpl ctx) {
494                return new WallpaperManager(ctx.getOuterContext(),
495                        ctx.mMainThread.getHandler());
496            }});
497
498        registerService(Context.WIFI_SERVICE, WifiManager.class,
499                new CachedServiceFetcher<WifiManager>() {
500            @Override
501            public WifiManager createService(ContextImpl ctx) {
502                IBinder b = ServiceManager.getService(Context.WIFI_SERVICE);
503                IWifiManager service = IWifiManager.Stub.asInterface(b);
504                return new WifiManager(ctx.getOuterContext(), service,
505                        ConnectivityThread.getInstanceLooper());
506            }});
507
508        registerService(Context.WIFI_P2P_SERVICE, WifiP2pManager.class,
509                new StaticServiceFetcher<WifiP2pManager>() {
510            @Override
511            public WifiP2pManager createService() {
512                IBinder b = ServiceManager.getService(Context.WIFI_P2P_SERVICE);
513                IWifiP2pManager service = IWifiP2pManager.Stub.asInterface(b);
514                return new WifiP2pManager(service);
515            }});
516
517        registerService(Context.WIFI_NAN_SERVICE, WifiNanManager.class,
518                new StaticServiceFetcher<WifiNanManager>() {
519            @Override
520            public WifiNanManager createService() {
521                IBinder b = ServiceManager.getService(Context.WIFI_NAN_SERVICE);
522                IWifiNanManager service = IWifiNanManager.Stub.asInterface(b);
523                if (service == null) {
524                    return null;
525                }
526                return new WifiNanManager(service);
527            }});
528
529        registerService(Context.WIFI_SCANNING_SERVICE, WifiScanner.class,
530                new CachedServiceFetcher<WifiScanner>() {
531            @Override
532            public WifiScanner createService(ContextImpl ctx) {
533                IBinder b = ServiceManager.getService(Context.WIFI_SCANNING_SERVICE);
534                IWifiScanner service = IWifiScanner.Stub.asInterface(b);
535                return new WifiScanner(ctx.getOuterContext(), service,
536                        ConnectivityThread.getInstanceLooper());
537            }});
538
539        registerService(Context.WIFI_RTT_SERVICE, RttManager.class,
540                new CachedServiceFetcher<RttManager>() {
541            @Override
542            public RttManager createService(ContextImpl ctx) {
543                IBinder b = ServiceManager.getService(Context.WIFI_RTT_SERVICE);
544                IRttManager service = IRttManager.Stub.asInterface(b);
545                return new RttManager(ctx.getOuterContext(), service,
546                        ConnectivityThread.getInstanceLooper());
547            }});
548
549        registerService(Context.ETHERNET_SERVICE, EthernetManager.class,
550                new CachedServiceFetcher<EthernetManager>() {
551            @Override
552            public EthernetManager createService(ContextImpl ctx) {
553                IBinder b = ServiceManager.getService(Context.ETHERNET_SERVICE);
554                IEthernetManager service = IEthernetManager.Stub.asInterface(b);
555                return new EthernetManager(ctx.getOuterContext(), service);
556            }});
557
558        registerService(Context.WINDOW_SERVICE, WindowManager.class,
559                new CachedServiceFetcher<WindowManager>() {
560            @Override
561            public WindowManager createService(ContextImpl ctx) {
562                return new WindowManagerImpl(ctx);
563            }});
564
565        registerService(Context.USER_SERVICE, UserManager.class,
566                new CachedServiceFetcher<UserManager>() {
567            @Override
568            public UserManager createService(ContextImpl ctx) {
569                IBinder b = ServiceManager.getService(Context.USER_SERVICE);
570                IUserManager service = IUserManager.Stub.asInterface(b);
571                return new UserManager(ctx, service);
572            }});
573
574        registerService(Context.APP_OPS_SERVICE, AppOpsManager.class,
575                new CachedServiceFetcher<AppOpsManager>() {
576            @Override
577            public AppOpsManager createService(ContextImpl ctx) {
578                IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
579                IAppOpsService service = IAppOpsService.Stub.asInterface(b);
580                return new AppOpsManager(ctx, service);
581            }});
582
583        registerService(Context.CAMERA_SERVICE, CameraManager.class,
584                new CachedServiceFetcher<CameraManager>() {
585            @Override
586            public CameraManager createService(ContextImpl ctx) {
587                return new CameraManager(ctx);
588            }});
589
590        registerService(Context.LAUNCHER_APPS_SERVICE, LauncherApps.class,
591                new CachedServiceFetcher<LauncherApps>() {
592            @Override
593            public LauncherApps createService(ContextImpl ctx) {
594                return new LauncherApps(ctx);
595            }});
596
597        registerService(Context.RESTRICTIONS_SERVICE, RestrictionsManager.class,
598                new CachedServiceFetcher<RestrictionsManager>() {
599            @Override
600            public RestrictionsManager createService(ContextImpl ctx) {
601                IBinder b = ServiceManager.getService(Context.RESTRICTIONS_SERVICE);
602                IRestrictionsManager service = IRestrictionsManager.Stub.asInterface(b);
603                return new RestrictionsManager(ctx, service);
604            }});
605
606        registerService(Context.PRINT_SERVICE, PrintManager.class,
607                new CachedServiceFetcher<PrintManager>() {
608            @Override
609            public PrintManager createService(ContextImpl ctx) {
610                IBinder iBinder = ServiceManager.getService(Context.PRINT_SERVICE);
611                IPrintManager service = IPrintManager.Stub.asInterface(iBinder);
612                return new PrintManager(ctx.getOuterContext(), service, UserHandle.myUserId(),
613                        UserHandle.getAppId(Process.myUid()));
614            }});
615
616        registerService(Context.CONSUMER_IR_SERVICE, ConsumerIrManager.class,
617                new CachedServiceFetcher<ConsumerIrManager>() {
618            @Override
619            public ConsumerIrManager createService(ContextImpl ctx) {
620                return new ConsumerIrManager(ctx);
621            }});
622
623        registerService(Context.MEDIA_SESSION_SERVICE, MediaSessionManager.class,
624                new CachedServiceFetcher<MediaSessionManager>() {
625            @Override
626            public MediaSessionManager createService(ContextImpl ctx) {
627                return new MediaSessionManager(ctx);
628            }});
629
630        registerService(Context.TRUST_SERVICE, TrustManager.class,
631                new StaticServiceFetcher<TrustManager>() {
632            @Override
633            public TrustManager createService() {
634                IBinder b = ServiceManager.getService(Context.TRUST_SERVICE);
635                return new TrustManager(b);
636            }});
637
638        registerService(Context.FINGERPRINT_SERVICE, FingerprintManager.class,
639                new CachedServiceFetcher<FingerprintManager>() {
640            @Override
641            public FingerprintManager createService(ContextImpl ctx) {
642                IBinder binder = ServiceManager.getService(Context.FINGERPRINT_SERVICE);
643                IFingerprintService service = IFingerprintService.Stub.asInterface(binder);
644                return new FingerprintManager(ctx.getOuterContext(), service);
645            }});
646
647        registerService(Context.TV_INPUT_SERVICE, TvInputManager.class,
648                new StaticServiceFetcher<TvInputManager>() {
649            @Override
650            public TvInputManager createService() {
651                IBinder iBinder = ServiceManager.getService(Context.TV_INPUT_SERVICE);
652                ITvInputManager service = ITvInputManager.Stub.asInterface(iBinder);
653                return new TvInputManager(service, UserHandle.myUserId());
654            }});
655
656        registerService(Context.NETWORK_SCORE_SERVICE, NetworkScoreManager.class,
657                new CachedServiceFetcher<NetworkScoreManager>() {
658            @Override
659            public NetworkScoreManager createService(ContextImpl ctx) {
660                return new NetworkScoreManager(ctx);
661            }});
662
663        registerService(Context.USAGE_STATS_SERVICE, UsageStatsManager.class,
664                new CachedServiceFetcher<UsageStatsManager>() {
665            @Override
666            public UsageStatsManager createService(ContextImpl ctx) {
667                IBinder iBinder = ServiceManager.getService(Context.USAGE_STATS_SERVICE);
668                IUsageStatsManager service = IUsageStatsManager.Stub.asInterface(iBinder);
669                return new UsageStatsManager(ctx.getOuterContext(), service);
670            }});
671
672        registerService(Context.NETWORK_STATS_SERVICE, NetworkStatsManager.class,
673                new CachedServiceFetcher<NetworkStatsManager>() {
674            @Override
675            public NetworkStatsManager createService(ContextImpl ctx) {
676                return new NetworkStatsManager(ctx.getOuterContext());
677            }});
678
679        registerService(Context.JOB_SCHEDULER_SERVICE, JobScheduler.class,
680                new StaticServiceFetcher<JobScheduler>() {
681            @Override
682            public JobScheduler createService() {
683                IBinder b = ServiceManager.getService(Context.JOB_SCHEDULER_SERVICE);
684                return new JobSchedulerImpl(IJobScheduler.Stub.asInterface(b));
685            }});
686
687        registerService(Context.PERSISTENT_DATA_BLOCK_SERVICE, PersistentDataBlockManager.class,
688                new StaticServiceFetcher<PersistentDataBlockManager>() {
689            @Override
690            public PersistentDataBlockManager createService() {
691                IBinder b = ServiceManager.getService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
692                IPersistentDataBlockService persistentDataBlockService =
693                        IPersistentDataBlockService.Stub.asInterface(b);
694                if (persistentDataBlockService != null) {
695                    return new PersistentDataBlockManager(persistentDataBlockService);
696                } else {
697                    // not supported
698                    return null;
699                }
700            }});
701
702        registerService(Context.MEDIA_PROJECTION_SERVICE, MediaProjectionManager.class,
703                new CachedServiceFetcher<MediaProjectionManager>() {
704            @Override
705            public MediaProjectionManager createService(ContextImpl ctx) {
706                return new MediaProjectionManager(ctx);
707            }});
708
709        registerService(Context.APPWIDGET_SERVICE, AppWidgetManager.class,
710                new CachedServiceFetcher<AppWidgetManager>() {
711            @Override
712            public AppWidgetManager createService(ContextImpl ctx) {
713                IBinder b = ServiceManager.getService(Context.APPWIDGET_SERVICE);
714                return new AppWidgetManager(ctx, IAppWidgetService.Stub.asInterface(b));
715            }});
716
717        registerService(Context.MIDI_SERVICE, MidiManager.class,
718                new CachedServiceFetcher<MidiManager>() {
719            @Override
720            public MidiManager createService(ContextImpl ctx) {
721                IBinder b = ServiceManager.getService(Context.MIDI_SERVICE);
722                if (b == null) {
723                    return null;
724                }
725                return new MidiManager(IMidiManager.Stub.asInterface(b));
726            }});
727
728        registerService(Context.RADIO_SERVICE, RadioManager.class,
729                new CachedServiceFetcher<RadioManager>() {
730            @Override
731            public RadioManager createService(ContextImpl ctx) {
732                return new RadioManager(ctx);
733            }});
734
735        registerService(Context.HARDWARE_PROPERTIES_SERVICE, HardwarePropertiesManager.class,
736                new CachedServiceFetcher<HardwarePropertiesManager>() {
737            @Override
738            public HardwarePropertiesManager createService(ContextImpl ctx) {
739                    IBinder b = ServiceManager.getService(Context.HARDWARE_PROPERTIES_SERVICE);
740                    IHardwarePropertiesManager service =
741                            IHardwarePropertiesManager.Stub.asInterface(b);
742                    if (service == null) {
743                        Log.wtf(TAG, "Failed to get hardwareproperties service.");
744                        return null;
745                    }
746                    return new HardwarePropertiesManager(ctx, service);
747            }});
748
749        registerService(Context.SOUND_TRIGGER_SERVICE, SoundTriggerManager.class,
750                new CachedServiceFetcher<SoundTriggerManager>() {
751            @Override
752            public SoundTriggerManager createService(ContextImpl ctx) {
753                IBinder b = ServiceManager.getService(Context.SOUND_TRIGGER_SERVICE);
754                return new SoundTriggerManager(ctx, ISoundTriggerService.Stub.asInterface(b));
755            }});
756
757        registerService(Context.SHORTCUT_SERVICE, ShortcutManager.class,
758                new CachedServiceFetcher<ShortcutManager>() {
759            @Override
760            public ShortcutManager createService(ContextImpl ctx) {
761                return new ShortcutManager(ctx);
762            }});
763
764        registerService(Context.SYSTEM_HEALTH_SERVICE, SystemHealthManager.class,
765                new CachedServiceFetcher<SystemHealthManager>() {
766            @Override
767            public SystemHealthManager createService(ContextImpl ctx) {
768                return new SystemHealthManager();
769            }});
770
771        registerService(Context.CONTEXTHUB_SERVICE, ContextHubManager.class,
772                new CachedServiceFetcher<ContextHubManager>() {
773            @Override
774            public ContextHubManager createService(ContextImpl ctx) {
775                return new ContextHubManager(ctx.getOuterContext(),
776                  ctx.mMainThread.getHandler().getLooper());
777            }});
778    }
779
780    /**
781     * Creates an array which is used to cache per-Context service instances.
782     */
783    public static Object[] createServiceCache() {
784        return new Object[sServiceCacheSize];
785    }
786
787    /**
788     * Gets a system service from a given context.
789     */
790    public static Object getSystemService(ContextImpl ctx, String name) {
791        ServiceFetcher<?> fetcher = SYSTEM_SERVICE_FETCHERS.get(name);
792        return fetcher != null ? fetcher.getService(ctx) : null;
793    }
794
795    /**
796     * Gets the name of the system-level service that is represented by the specified class.
797     */
798    public static String getSystemServiceName(Class<?> serviceClass) {
799        return SYSTEM_SERVICE_NAMES.get(serviceClass);
800    }
801
802    /**
803     * Statically registers a system service with the context.
804     * This method must be called during static initialization only.
805     */
806    private static <T> void registerService(String serviceName, Class<T> serviceClass,
807            ServiceFetcher<T> serviceFetcher) {
808        SYSTEM_SERVICE_NAMES.put(serviceClass, serviceName);
809        SYSTEM_SERVICE_FETCHERS.put(serviceName, serviceFetcher);
810    }
811
812    /**
813     * Base interface for classes that fetch services.
814     * These objects must only be created during static initialization.
815     */
816    static abstract interface ServiceFetcher<T> {
817        T getService(ContextImpl ctx);
818    }
819
820    /**
821     * Override this class when the system service constructor needs a
822     * ContextImpl and should be cached and retained by that context.
823     */
824    static abstract class CachedServiceFetcher<T> implements ServiceFetcher<T> {
825        private final int mCacheIndex;
826
827        public CachedServiceFetcher() {
828            mCacheIndex = sServiceCacheSize++;
829        }
830
831        @Override
832        @SuppressWarnings("unchecked")
833        public final T getService(ContextImpl ctx) {
834            final Object[] cache = ctx.mServiceCache;
835            synchronized (cache) {
836                // Fetch or create the service.
837                Object service = cache[mCacheIndex];
838                if (service == null) {
839                    service = createService(ctx);
840                    cache[mCacheIndex] = service;
841                }
842                return (T)service;
843            }
844        }
845
846        public abstract T createService(ContextImpl ctx);
847    }
848
849    /**
850     * Override this class when the system service does not need a ContextImpl
851     * and should be cached and retained process-wide.
852     */
853    static abstract class StaticServiceFetcher<T> implements ServiceFetcher<T> {
854        private T mCachedInstance;
855
856        @Override
857        public final T getService(ContextImpl unused) {
858            synchronized (StaticServiceFetcher.this) {
859                if (mCachedInstance == null) {
860                    mCachedInstance = createService();
861                }
862                return mCachedInstance;
863            }
864        }
865
866        public abstract T createService();
867    }
868
869    /**
870     * Like StaticServiceFetcher, creates only one instance of the service per application, but when
871     * creating the service for the first time, passes it the application context of the creating
872     * application.
873     *
874     * TODO: Delete this once its only user (ConnectivityManager) is known to work well in the
875     * case where multiple application components each have their own ConnectivityManager object.
876     */
877    static abstract class StaticApplicationContextServiceFetcher<T> implements ServiceFetcher<T> {
878        private T mCachedInstance;
879
880        @Override
881        public final T getService(ContextImpl ctx) {
882            synchronized (StaticApplicationContextServiceFetcher.this) {
883                if (mCachedInstance == null) {
884                    Context appContext = ctx.getApplicationContext();
885                    // If the application context is null, we're either in the system process or
886                    // it's the application context very early in app initialization. In both these
887                    // cases, the passed-in ContextImpl will not be freed, so it's safe to pass it
888                    // to the service. http://b/27532714 .
889                    mCachedInstance = createService(appContext != null ? appContext : ctx);
890                }
891                return mCachedInstance;
892            }
893        }
894
895        public abstract T createService(Context applicationContext);
896    }
897
898}
899