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 
17 package android.app;
18 
19 import android.accounts.AccountManager;
20 import android.accounts.IAccountManager;
21 import android.annotation.NonNull;
22 import android.annotation.Nullable;
23 import android.annotation.SystemApi;
24 import android.app.ContextImpl.ServiceInitializationState;
25 import android.app.admin.DevicePolicyManager;
26 import android.app.admin.IDevicePolicyManager;
27 import android.app.blob.BlobStoreManagerFrameworkInitializer;
28 import android.app.contentsuggestions.ContentSuggestionsManager;
29 import android.app.contentsuggestions.IContentSuggestionsManager;
30 import android.app.job.JobSchedulerFrameworkInitializer;
31 import android.app.prediction.AppPredictionManager;
32 import android.app.role.RoleControllerManager;
33 import android.app.role.RoleManager;
34 import android.app.slice.SliceManager;
35 import android.app.timedetector.TimeDetector;
36 import android.app.timedetector.TimeDetectorImpl;
37 import android.app.timezone.RulesManager;
38 import android.app.timezonedetector.TimeZoneDetector;
39 import android.app.timezonedetector.TimeZoneDetectorImpl;
40 import android.app.trust.TrustManager;
41 import android.app.usage.IStorageStatsManager;
42 import android.app.usage.IUsageStatsManager;
43 import android.app.usage.NetworkStatsManager;
44 import android.app.usage.StorageStatsManager;
45 import android.app.usage.UsageStatsManager;
46 import android.appwidget.AppWidgetManager;
47 import android.bluetooth.BluetoothManager;
48 import android.companion.CompanionDeviceManager;
49 import android.companion.ICompanionDeviceManager;
50 import android.content.ClipboardManager;
51 import android.content.ContentCaptureOptions;
52 import android.content.Context;
53 import android.content.IRestrictionsManager;
54 import android.content.RestrictionsManager;
55 import android.content.integrity.AppIntegrityManager;
56 import android.content.integrity.IAppIntegrityManager;
57 import android.content.om.IOverlayManager;
58 import android.content.om.OverlayManager;
59 import android.content.pm.ApplicationInfo;
60 import android.content.pm.CrossProfileApps;
61 import android.content.pm.DataLoaderManager;
62 import android.content.pm.ICrossProfileApps;
63 import android.content.pm.IDataLoaderManager;
64 import android.content.pm.IPackageManager;
65 import android.content.pm.IShortcutService;
66 import android.content.pm.LauncherApps;
67 import android.content.pm.PackageManager;
68 import android.content.pm.ShortcutManager;
69 import android.content.res.Resources;
70 import android.content.rollback.IRollbackManager;
71 import android.content.rollback.RollbackManager;
72 import android.debug.AdbManager;
73 import android.debug.IAdbManager;
74 import android.hardware.ConsumerIrManager;
75 import android.hardware.ISerialManager;
76 import android.hardware.SensorManager;
77 import android.hardware.SensorPrivacyManager;
78 import android.hardware.SerialManager;
79 import android.hardware.SystemSensorManager;
80 import android.hardware.biometrics.BiometricManager;
81 import android.hardware.biometrics.IAuthService;
82 import android.hardware.camera2.CameraManager;
83 import android.hardware.display.ColorDisplayManager;
84 import android.hardware.display.DisplayManager;
85 import android.hardware.face.FaceManager;
86 import android.hardware.face.IFaceService;
87 import android.hardware.fingerprint.FingerprintManager;
88 import android.hardware.fingerprint.IFingerprintService;
89 import android.hardware.hdmi.HdmiControlManager;
90 import android.hardware.hdmi.IHdmiControlService;
91 import android.hardware.input.InputManager;
92 import android.hardware.iris.IIrisService;
93 import android.hardware.iris.IrisManager;
94 import android.hardware.lights.LightsManager;
95 import android.hardware.location.ContextHubManager;
96 import android.hardware.radio.RadioManager;
97 import android.hardware.usb.IUsbManager;
98 import android.hardware.usb.UsbManager;
99 import android.location.CountryDetector;
100 import android.location.ICountryDetector;
101 import android.location.ILocationManager;
102 import android.location.LocationManager;
103 import android.media.AudioManager;
104 import android.media.MediaRouter;
105 import android.media.midi.IMidiManager;
106 import android.media.midi.MidiManager;
107 import android.media.projection.MediaProjectionManager;
108 import android.media.session.MediaSessionManager;
109 import android.media.soundtrigger.SoundTriggerManager;
110 import android.media.tv.ITvInputManager;
111 import android.media.tv.TvInputManager;
112 import android.media.tv.tunerresourcemanager.ITunerResourceManager;
113 import android.media.tv.tunerresourcemanager.TunerResourceManager;
114 import android.net.ConnectivityDiagnosticsManager;
115 import android.net.ConnectivityManager;
116 import android.net.ConnectivityThread;
117 import android.net.EthernetManager;
118 import android.net.IConnectivityManager;
119 import android.net.IEthernetManager;
120 import android.net.IIpSecService;
121 import android.net.INetworkPolicyManager;
122 import android.net.ITestNetworkManager;
123 import android.net.IpSecManager;
124 import android.net.NetworkPolicyManager;
125 import android.net.NetworkScoreManager;
126 import android.net.NetworkWatchlistManager;
127 import android.net.TestNetworkManager;
128 import android.net.TetheringManager;
129 import android.net.VpnManager;
130 import android.net.lowpan.ILowpanManager;
131 import android.net.lowpan.LowpanManager;
132 import android.net.nsd.INsdManager;
133 import android.net.nsd.NsdManager;
134 import android.net.wifi.WifiFrameworkInitializer;
135 import android.net.wifi.nl80211.WifiNl80211Manager;
136 import android.nfc.NfcManager;
137 import android.os.BatteryManager;
138 import android.os.BatteryStats;
139 import android.os.BatteryStatsManager;
140 import android.os.BugreportManager;
141 import android.os.Build;
142 import android.os.DropBoxManager;
143 import android.os.HardwarePropertiesManager;
144 import android.os.IBatteryPropertiesRegistrar;
145 import android.os.IBinder;
146 import android.os.IDumpstate;
147 import android.os.IHardwarePropertiesManager;
148 import android.os.IPowerManager;
149 import android.os.IRecoverySystem;
150 import android.os.ISystemUpdateManager;
151 import android.os.IThermalService;
152 import android.os.IUserManager;
153 import android.os.IncidentManager;
154 import android.os.PowerManager;
155 import android.os.RecoverySystem;
156 import android.os.RemoteException;
157 import android.os.ServiceManager;
158 import android.os.ServiceManager.ServiceNotFoundException;
159 import android.os.StatsFrameworkInitializer;
160 import android.os.SystemConfigManager;
161 import android.os.SystemUpdateManager;
162 import android.os.SystemVibrator;
163 import android.os.UserHandle;
164 import android.os.UserManager;
165 import android.os.Vibrator;
166 import android.os.health.SystemHealthManager;
167 import android.os.image.DynamicSystemManager;
168 import android.os.image.IDynamicSystemService;
169 import android.os.incremental.IIncrementalService;
170 import android.os.incremental.IncrementalManager;
171 import android.os.storage.StorageManager;
172 import android.permission.PermissionControllerManager;
173 import android.permission.PermissionManager;
174 import android.print.IPrintManager;
175 import android.print.PrintManager;
176 import android.security.FileIntegrityManager;
177 import android.security.IFileIntegrityService;
178 import android.service.oemlock.IOemLockService;
179 import android.service.oemlock.OemLockManager;
180 import android.service.persistentdata.IPersistentDataBlockService;
181 import android.service.persistentdata.PersistentDataBlockManager;
182 import android.service.vr.IVrManager;
183 import android.telecom.TelecomManager;
184 import android.telephony.MmsManager;
185 import android.telephony.TelephonyFrameworkInitializer;
186 import android.telephony.TelephonyRegistryManager;
187 import android.util.ArrayMap;
188 import android.util.Log;
189 import android.util.Slog;
190 import android.view.ContextThemeWrapper;
191 import android.view.LayoutInflater;
192 import android.view.WindowManager;
193 import android.view.WindowManagerImpl;
194 import android.view.accessibility.AccessibilityManager;
195 import android.view.accessibility.CaptioningManager;
196 import android.view.autofill.AutofillManager;
197 import android.view.autofill.IAutoFillManager;
198 import android.view.contentcapture.ContentCaptureManager;
199 import android.view.contentcapture.IContentCaptureManager;
200 import android.view.inputmethod.InputMethodManager;
201 import android.view.textclassifier.TextClassificationManager;
202 import android.view.textservice.TextServicesManager;
203 
204 import com.android.internal.app.IAppOpsService;
205 import com.android.internal.app.IBatteryStats;
206 import com.android.internal.app.ISoundTriggerService;
207 import com.android.internal.appwidget.IAppWidgetService;
208 import com.android.internal.net.INetworkWatchlistManager;
209 import com.android.internal.os.IDropBoxManagerService;
210 import com.android.internal.policy.PhoneLayoutInflater;
211 import com.android.internal.util.Preconditions;
212 
213 import java.util.Map;
214 import java.util.Objects;
215 
216 /**
217  * Manages all of the system services that can be returned by {@link Context#getSystemService}.
218  * Used by {@link ContextImpl}.
219  *
220  * @hide
221  */
222 @SystemApi
223 public final class SystemServiceRegistry {
224     private static final String TAG = "SystemServiceRegistry";
225 
226     /** @hide */
227     public static boolean sEnableServiceNotFoundWtf = false;
228 
229     // Service registry information.
230     // This information is never changed once static initialization has completed.
231     private static final Map<Class<?>, String> SYSTEM_SERVICE_NAMES =
232             new ArrayMap<Class<?>, String>();
233     private static final Map<String, ServiceFetcher<?>> SYSTEM_SERVICE_FETCHERS =
234             new ArrayMap<String, ServiceFetcher<?>>();
235     private static final Map<String, String> SYSTEM_SERVICE_CLASS_NAMES = new ArrayMap<>();
236 
237     private static int sServiceCacheSize;
238 
239     private static volatile boolean sInitializing;
240 
241     // Not instantiable.
SystemServiceRegistry()242     private SystemServiceRegistry() { }
243 
244     static {
245         //CHECKSTYLE:OFF IndentationCheck
registerService(Context.ACCESSIBILITY_SERVICE, AccessibilityManager.class, new CachedServiceFetcher<AccessibilityManager>() { @Override public AccessibilityManager createService(ContextImpl ctx) { return AccessibilityManager.getInstance(ctx); }})246         registerService(Context.ACCESSIBILITY_SERVICE, AccessibilityManager.class,
247                 new CachedServiceFetcher<AccessibilityManager>() {
248             @Override
249             public AccessibilityManager createService(ContextImpl ctx) {
250                 return AccessibilityManager.getInstance(ctx);
251             }});
252 
registerService(Context.CAPTIONING_SERVICE, CaptioningManager.class, new CachedServiceFetcher<CaptioningManager>() { @Override public CaptioningManager createService(ContextImpl ctx) { return new CaptioningManager(ctx); }})253         registerService(Context.CAPTIONING_SERVICE, CaptioningManager.class,
254                 new CachedServiceFetcher<CaptioningManager>() {
255             @Override
256             public CaptioningManager createService(ContextImpl ctx) {
257                 return new CaptioningManager(ctx);
258             }});
259 
registerService(Context.ACCOUNT_SERVICE, AccountManager.class, new CachedServiceFetcher<AccountManager>() { @Override public AccountManager createService(ContextImpl ctx) throws ServiceNotFoundException { IBinder b = ServiceManager.getServiceOrThrow(Context.ACCOUNT_SERVICE); IAccountManager service = IAccountManager.Stub.asInterface(b); return new AccountManager(ctx, service); }})260         registerService(Context.ACCOUNT_SERVICE, AccountManager.class,
261                 new CachedServiceFetcher<AccountManager>() {
262             @Override
263             public AccountManager createService(ContextImpl ctx) throws ServiceNotFoundException {
264                 IBinder b = ServiceManager.getServiceOrThrow(Context.ACCOUNT_SERVICE);
265                 IAccountManager service = IAccountManager.Stub.asInterface(b);
266                 return new AccountManager(ctx, service);
267             }});
268 
registerService(Context.ACTIVITY_SERVICE, ActivityManager.class, new CachedServiceFetcher<ActivityManager>() { @Override public ActivityManager createService(ContextImpl ctx) { return new ActivityManager(ctx.getOuterContext(), ctx.mMainThread.getHandler()); }})269         registerService(Context.ACTIVITY_SERVICE, ActivityManager.class,
270                 new CachedServiceFetcher<ActivityManager>() {
271             @Override
272             public ActivityManager createService(ContextImpl ctx) {
273                 return new ActivityManager(ctx.getOuterContext(), ctx.mMainThread.getHandler());
274             }});
275 
registerService(Context.ACTIVITY_TASK_SERVICE, ActivityTaskManager.class, new CachedServiceFetcher<ActivityTaskManager>() { @Override public ActivityTaskManager createService(ContextImpl ctx) { return new ActivityTaskManager( ctx.getOuterContext(), ctx.mMainThread.getHandler()); }})276         registerService(Context.ACTIVITY_TASK_SERVICE, ActivityTaskManager.class,
277                 new CachedServiceFetcher<ActivityTaskManager>() {
278             @Override
279             public ActivityTaskManager createService(ContextImpl ctx) {
280                 return new ActivityTaskManager(
281                         ctx.getOuterContext(), ctx.mMainThread.getHandler());
282             }});
283 
registerService(Context.URI_GRANTS_SERVICE, UriGrantsManager.class, new CachedServiceFetcher<UriGrantsManager>() { @Override public UriGrantsManager createService(ContextImpl ctx) { return new UriGrantsManager( ctx.getOuterContext(), ctx.mMainThread.getHandler()); }})284         registerService(Context.URI_GRANTS_SERVICE, UriGrantsManager.class,
285                 new CachedServiceFetcher<UriGrantsManager>() {
286             @Override
287             public UriGrantsManager createService(ContextImpl ctx) {
288                 return new UriGrantsManager(
289                         ctx.getOuterContext(), ctx.mMainThread.getHandler());
290             }});
291 
registerService(Context.ALARM_SERVICE, AlarmManager.class, new CachedServiceFetcher<AlarmManager>() { @Override public AlarmManager createService(ContextImpl ctx) throws ServiceNotFoundException { IBinder b = ServiceManager.getServiceOrThrow(Context.ALARM_SERVICE); IAlarmManager service = IAlarmManager.Stub.asInterface(b); return new AlarmManager(service, ctx); }})292         registerService(Context.ALARM_SERVICE, AlarmManager.class,
293                 new CachedServiceFetcher<AlarmManager>() {
294             @Override
295             public AlarmManager createService(ContextImpl ctx) throws ServiceNotFoundException {
296                 IBinder b = ServiceManager.getServiceOrThrow(Context.ALARM_SERVICE);
297                 IAlarmManager service = IAlarmManager.Stub.asInterface(b);
298                 return new AlarmManager(service, ctx);
299             }});
300 
registerService(Context.AUDIO_SERVICE, AudioManager.class, new CachedServiceFetcher<AudioManager>() { @Override public AudioManager createService(ContextImpl ctx) { return new AudioManager(ctx); }})301         registerService(Context.AUDIO_SERVICE, AudioManager.class,
302                 new CachedServiceFetcher<AudioManager>() {
303             @Override
304             public AudioManager createService(ContextImpl ctx) {
305                 return new AudioManager(ctx);
306             }});
307 
registerService(Context.MEDIA_ROUTER_SERVICE, MediaRouter.class, new CachedServiceFetcher<MediaRouter>() { @Override public MediaRouter createService(ContextImpl ctx) { return new MediaRouter(ctx); }})308         registerService(Context.MEDIA_ROUTER_SERVICE, MediaRouter.class,
309                 new CachedServiceFetcher<MediaRouter>() {
310             @Override
311             public MediaRouter createService(ContextImpl ctx) {
312                 return new MediaRouter(ctx);
313             }});
314 
registerService(Context.BLUETOOTH_SERVICE, BluetoothManager.class, new CachedServiceFetcher<BluetoothManager>() { @Override public BluetoothManager createService(ContextImpl ctx) { return new BluetoothManager(ctx); }})315         registerService(Context.BLUETOOTH_SERVICE, BluetoothManager.class,
316                 new CachedServiceFetcher<BluetoothManager>() {
317             @Override
318             public BluetoothManager createService(ContextImpl ctx) {
319                 return new BluetoothManager(ctx);
320             }});
321 
registerService(Context.HDMI_CONTROL_SERVICE, HdmiControlManager.class, new StaticServiceFetcher<HdmiControlManager>() { @Override public HdmiControlManager createService() throws ServiceNotFoundException { IBinder b = ServiceManager.getServiceOrThrow(Context.HDMI_CONTROL_SERVICE); return new HdmiControlManager(IHdmiControlService.Stub.asInterface(b)); }})322         registerService(Context.HDMI_CONTROL_SERVICE, HdmiControlManager.class,
323                 new StaticServiceFetcher<HdmiControlManager>() {
324             @Override
325             public HdmiControlManager createService() throws ServiceNotFoundException {
326                 IBinder b = ServiceManager.getServiceOrThrow(Context.HDMI_CONTROL_SERVICE);
327                 return new HdmiControlManager(IHdmiControlService.Stub.asInterface(b));
328             }});
329 
registerService(Context.TEXT_CLASSIFICATION_SERVICE, TextClassificationManager.class, new CachedServiceFetcher<TextClassificationManager>() { @Override public TextClassificationManager createService(ContextImpl ctx) { return new TextClassificationManager(ctx); }})330         registerService(Context.TEXT_CLASSIFICATION_SERVICE, TextClassificationManager.class,
331                 new CachedServiceFetcher<TextClassificationManager>() {
332             @Override
333             public TextClassificationManager createService(ContextImpl ctx) {
334                 return new TextClassificationManager(ctx);
335             }});
336 
registerService(Context.CLIPBOARD_SERVICE, ClipboardManager.class, new CachedServiceFetcher<ClipboardManager>() { @Override public ClipboardManager createService(ContextImpl ctx) throws ServiceNotFoundException { return new ClipboardManager(ctx.getOuterContext(), ctx.mMainThread.getHandler()); }})337         registerService(Context.CLIPBOARD_SERVICE, ClipboardManager.class,
338                 new CachedServiceFetcher<ClipboardManager>() {
339             @Override
340             public ClipboardManager createService(ContextImpl ctx) throws ServiceNotFoundException {
341                 return new ClipboardManager(ctx.getOuterContext(),
342                         ctx.mMainThread.getHandler());
343             }});
344 
345         // The clipboard service moved to a new package.  If someone asks for the old
346         // interface by class then we want to redirect over to the new interface instead
347         // (which extends it).
SYSTEM_SERVICE_NAMES.put(android.text.ClipboardManager.class, Context.CLIPBOARD_SERVICE)348         SYSTEM_SERVICE_NAMES.put(android.text.ClipboardManager.class, Context.CLIPBOARD_SERVICE);
349 
registerService(Context.CONNECTIVITY_SERVICE, ConnectivityManager.class, new StaticApplicationContextServiceFetcher<ConnectivityManager>() { @Override public ConnectivityManager createService(Context context) throws ServiceNotFoundException { IBinder b = ServiceManager.getServiceOrThrow(Context.CONNECTIVITY_SERVICE); IConnectivityManager service = IConnectivityManager.Stub.asInterface(b); return new ConnectivityManager(context, service); }})350         registerService(Context.CONNECTIVITY_SERVICE, ConnectivityManager.class,
351                 new StaticApplicationContextServiceFetcher<ConnectivityManager>() {
352             @Override
353             public ConnectivityManager createService(Context context) throws ServiceNotFoundException {
354                 IBinder b = ServiceManager.getServiceOrThrow(Context.CONNECTIVITY_SERVICE);
355                 IConnectivityManager service = IConnectivityManager.Stub.asInterface(b);
356                 return new ConnectivityManager(context, service);
357             }});
358 
registerService(Context.NETD_SERVICE, IBinder.class, new StaticServiceFetcher<IBinder>() { @Override public IBinder createService() throws ServiceNotFoundException { return ServiceManager.getServiceOrThrow(Context.NETD_SERVICE); } })359         registerService(Context.NETD_SERVICE, IBinder.class, new StaticServiceFetcher<IBinder>() {
360             @Override
361             public IBinder createService() throws ServiceNotFoundException {
362                 return ServiceManager.getServiceOrThrow(Context.NETD_SERVICE);
363             }
364         });
365 
registerService(Context.TETHERING_SERVICE, TetheringManager.class, new CachedServiceFetcher<TetheringManager>() { @Override public TetheringManager createService(ContextImpl ctx) { return new TetheringManager( ctx, () -> ServiceManager.getService(Context.TETHERING_SERVICE)); }})366         registerService(Context.TETHERING_SERVICE, TetheringManager.class,
367                 new CachedServiceFetcher<TetheringManager>() {
368             @Override
369             public TetheringManager createService(ContextImpl ctx) {
370                 return new TetheringManager(
371                         ctx, () -> ServiceManager.getService(Context.TETHERING_SERVICE));
372             }});
373 
374 
registerService(Context.IPSEC_SERVICE, IpSecManager.class, new CachedServiceFetcher<IpSecManager>() { @Override public IpSecManager createService(ContextImpl ctx) throws ServiceNotFoundException { IBinder b = ServiceManager.getService(Context.IPSEC_SERVICE); IIpSecService service = IIpSecService.Stub.asInterface(b); return new IpSecManager(ctx, service); }})375         registerService(Context.IPSEC_SERVICE, IpSecManager.class,
376                 new CachedServiceFetcher<IpSecManager>() {
377             @Override
378             public IpSecManager createService(ContextImpl ctx) throws ServiceNotFoundException {
379                 IBinder b = ServiceManager.getService(Context.IPSEC_SERVICE);
380                 IIpSecService service = IIpSecService.Stub.asInterface(b);
381                 return new IpSecManager(ctx, service);
382             }});
383 
registerService(Context.VPN_MANAGEMENT_SERVICE, VpnManager.class, new CachedServiceFetcher<VpnManager>() { @Override public VpnManager createService(ContextImpl ctx) throws ServiceNotFoundException { IBinder b = ServiceManager.getService(Context.CONNECTIVITY_SERVICE); IConnectivityManager service = IConnectivityManager.Stub.asInterface(b); return new VpnManager(ctx, service); }})384         registerService(Context.VPN_MANAGEMENT_SERVICE, VpnManager.class,
385                 new CachedServiceFetcher<VpnManager>() {
386             @Override
387             public VpnManager createService(ContextImpl ctx) throws ServiceNotFoundException {
388                 IBinder b = ServiceManager.getService(Context.CONNECTIVITY_SERVICE);
389                 IConnectivityManager service = IConnectivityManager.Stub.asInterface(b);
390                 return new VpnManager(ctx, service);
391             }});
392 
registerService(Context.CONNECTIVITY_DIAGNOSTICS_SERVICE, ConnectivityDiagnosticsManager.class, new CachedServiceFetcher<ConnectivityDiagnosticsManager>() { @Override public ConnectivityDiagnosticsManager createService(ContextImpl ctx) throws ServiceNotFoundException { IBinder b = ServiceManager.getServiceOrThrow(Context.CONNECTIVITY_SERVICE); IConnectivityManager service = IConnectivityManager.Stub.asInterface(b); return new ConnectivityDiagnosticsManager(ctx, service); }})393         registerService(Context.CONNECTIVITY_DIAGNOSTICS_SERVICE,
394                 ConnectivityDiagnosticsManager.class,
395                 new CachedServiceFetcher<ConnectivityDiagnosticsManager>() {
396             @Override
397             public ConnectivityDiagnosticsManager createService(ContextImpl ctx)
398                     throws ServiceNotFoundException {
399                 // ConnectivityDiagnosticsManager is backed by ConnectivityService
400                 IBinder b = ServiceManager.getServiceOrThrow(Context.CONNECTIVITY_SERVICE);
401                 IConnectivityManager service = IConnectivityManager.Stub.asInterface(b);
402                 return new ConnectivityDiagnosticsManager(ctx, service);
403             }});
404 
registerService( Context.TEST_NETWORK_SERVICE, TestNetworkManager.class, new StaticApplicationContextServiceFetcher<TestNetworkManager>() { @Override public TestNetworkManager createService(Context context) throws ServiceNotFoundException { IBinder csBinder = ServiceManager.getServiceOrThrow(Context.CONNECTIVITY_SERVICE); IConnectivityManager csMgr = IConnectivityManager.Stub.asInterface(csBinder); final IBinder tnBinder; try { tnBinder = csMgr.startOrGetTestNetworkService(); } catch (RemoteException e) { throw new ServiceNotFoundException(Context.TEST_NETWORK_SERVICE); } ITestNetworkManager tnMgr = ITestNetworkManager.Stub.asInterface(tnBinder); return new TestNetworkManager(tnMgr); } })405         registerService(
406                 Context.TEST_NETWORK_SERVICE,
407                 TestNetworkManager.class,
408                 new StaticApplicationContextServiceFetcher<TestNetworkManager>() {
409                     @Override
410                     public TestNetworkManager createService(Context context)
411                             throws ServiceNotFoundException {
412                         IBinder csBinder =
413                                 ServiceManager.getServiceOrThrow(Context.CONNECTIVITY_SERVICE);
414                         IConnectivityManager csMgr =
415                                 IConnectivityManager.Stub.asInterface(csBinder);
416 
417                         final IBinder tnBinder;
418                         try {
419                             tnBinder = csMgr.startOrGetTestNetworkService();
420                         } catch (RemoteException e) {
421                             throw new ServiceNotFoundException(Context.TEST_NETWORK_SERVICE);
422                         }
423                         ITestNetworkManager tnMgr = ITestNetworkManager.Stub.asInterface(tnBinder);
424                         return new TestNetworkManager(tnMgr);
425                     }
426                 });
427 
registerService(Context.COUNTRY_DETECTOR, CountryDetector.class, new StaticServiceFetcher<CountryDetector>() { @Override public CountryDetector createService() throws ServiceNotFoundException { IBinder b = ServiceManager.getServiceOrThrow(Context.COUNTRY_DETECTOR); return new CountryDetector(ICountryDetector.Stub.asInterface(b)); }})428         registerService(Context.COUNTRY_DETECTOR, CountryDetector.class,
429                 new StaticServiceFetcher<CountryDetector>() {
430             @Override
431             public CountryDetector createService() throws ServiceNotFoundException {
432                 IBinder b = ServiceManager.getServiceOrThrow(Context.COUNTRY_DETECTOR);
433                 return new CountryDetector(ICountryDetector.Stub.asInterface(b));
434             }});
435 
registerService(Context.DEVICE_POLICY_SERVICE, DevicePolicyManager.class, new CachedServiceFetcher<DevicePolicyManager>() { @Override public DevicePolicyManager createService(ContextImpl ctx) throws ServiceNotFoundException { IBinder b = ServiceManager.getServiceOrThrow(Context.DEVICE_POLICY_SERVICE); return new DevicePolicyManager(ctx, IDevicePolicyManager.Stub.asInterface(b)); }})436         registerService(Context.DEVICE_POLICY_SERVICE, DevicePolicyManager.class,
437                 new CachedServiceFetcher<DevicePolicyManager>() {
438             @Override
439             public DevicePolicyManager createService(ContextImpl ctx) throws ServiceNotFoundException {
440                 IBinder b = ServiceManager.getServiceOrThrow(Context.DEVICE_POLICY_SERVICE);
441                 return new DevicePolicyManager(ctx, IDevicePolicyManager.Stub.asInterface(b));
442             }});
443 
registerService(Context.DOWNLOAD_SERVICE, DownloadManager.class, new CachedServiceFetcher<DownloadManager>() { @Override public DownloadManager createService(ContextImpl ctx) { return new DownloadManager(ctx); }})444         registerService(Context.DOWNLOAD_SERVICE, DownloadManager.class,
445                 new CachedServiceFetcher<DownloadManager>() {
446             @Override
447             public DownloadManager createService(ContextImpl ctx) {
448                 return new DownloadManager(ctx);
449             }});
450 
registerService(Context.BATTERY_SERVICE, BatteryManager.class, new CachedServiceFetcher<BatteryManager>() { @Override public BatteryManager createService(ContextImpl ctx) throws ServiceNotFoundException { IBatteryStats stats = IBatteryStats.Stub.asInterface( ServiceManager.getServiceOrThrow(BatteryStats.SERVICE_NAME)); IBatteryPropertiesRegistrar registrar = IBatteryPropertiesRegistrar.Stub .asInterface(ServiceManager.getServiceOrThrow("batteryproperties")); return new BatteryManager(ctx, stats, registrar); }})451         registerService(Context.BATTERY_SERVICE, BatteryManager.class,
452                 new CachedServiceFetcher<BatteryManager>() {
453             @Override
454             public BatteryManager createService(ContextImpl ctx) throws ServiceNotFoundException {
455                 IBatteryStats stats = IBatteryStats.Stub.asInterface(
456                         ServiceManager.getServiceOrThrow(BatteryStats.SERVICE_NAME));
457                 IBatteryPropertiesRegistrar registrar = IBatteryPropertiesRegistrar.Stub
458                         .asInterface(ServiceManager.getServiceOrThrow("batteryproperties"));
459                 return new BatteryManager(ctx, stats, registrar);
460             }});
461 
registerService(Context.NFC_SERVICE, NfcManager.class, new CachedServiceFetcher<NfcManager>() { @Override public NfcManager createService(ContextImpl ctx) { return new NfcManager(ctx); }})462         registerService(Context.NFC_SERVICE, NfcManager.class,
463                 new CachedServiceFetcher<NfcManager>() {
464             @Override
465             public NfcManager createService(ContextImpl ctx) {
466                 return new NfcManager(ctx);
467             }});
468 
registerService(Context.DROPBOX_SERVICE, DropBoxManager.class, new CachedServiceFetcher<DropBoxManager>() { @Override public DropBoxManager createService(ContextImpl ctx) throws ServiceNotFoundException { IBinder b = ServiceManager.getServiceOrThrow(Context.DROPBOX_SERVICE); IDropBoxManagerService service = IDropBoxManagerService.Stub.asInterface(b); return new DropBoxManager(ctx, service); }})469         registerService(Context.DROPBOX_SERVICE, DropBoxManager.class,
470                 new CachedServiceFetcher<DropBoxManager>() {
471             @Override
472             public DropBoxManager createService(ContextImpl ctx) throws ServiceNotFoundException {
473                 IBinder b = ServiceManager.getServiceOrThrow(Context.DROPBOX_SERVICE);
474                 IDropBoxManagerService service = IDropBoxManagerService.Stub.asInterface(b);
475                 return new DropBoxManager(ctx, service);
476             }});
477 
registerService(Context.INPUT_SERVICE, InputManager.class, new StaticServiceFetcher<InputManager>() { @Override public InputManager createService() { return InputManager.getInstance(); }})478         registerService(Context.INPUT_SERVICE, InputManager.class,
479                 new StaticServiceFetcher<InputManager>() {
480             @Override
481             public InputManager createService() {
482                 return InputManager.getInstance();
483             }});
484 
registerService(Context.DISPLAY_SERVICE, DisplayManager.class, new CachedServiceFetcher<DisplayManager>() { @Override public DisplayManager createService(ContextImpl ctx) { return new DisplayManager(ctx.getOuterContext()); }})485         registerService(Context.DISPLAY_SERVICE, DisplayManager.class,
486                 new CachedServiceFetcher<DisplayManager>() {
487             @Override
488             public DisplayManager createService(ContextImpl ctx) {
489                 return new DisplayManager(ctx.getOuterContext());
490             }});
491 
registerService(Context.COLOR_DISPLAY_SERVICE, ColorDisplayManager.class, new CachedServiceFetcher<ColorDisplayManager>() { @Override public ColorDisplayManager createService(ContextImpl ctx) { return new ColorDisplayManager(); } })492         registerService(Context.COLOR_DISPLAY_SERVICE, ColorDisplayManager.class,
493                 new CachedServiceFetcher<ColorDisplayManager>() {
494                     @Override
495                     public ColorDisplayManager createService(ContextImpl ctx) {
496                         return new ColorDisplayManager();
497                     }
498                 });
499 
500         // InputMethodManager has its own cache strategy based on display id to support apps that
501         // still assume InputMethodManager is a per-process singleton and it's safe to directly
502         // access internal fields via reflection.  Hence directly use ServiceFetcher instead of
503         // StaticServiceFetcher/CachedServiceFetcher.
registerService(Context.INPUT_METHOD_SERVICE, InputMethodManager.class, new ServiceFetcher<InputMethodManager>() { @Override public InputMethodManager getService(ContextImpl ctx) { return InputMethodManager.forContext(ctx.getOuterContext()); }})504         registerService(Context.INPUT_METHOD_SERVICE, InputMethodManager.class,
505                 new ServiceFetcher<InputMethodManager>() {
506             @Override
507             public InputMethodManager getService(ContextImpl ctx) {
508                 return InputMethodManager.forContext(ctx.getOuterContext());
509             }});
510 
registerService(Context.TEXT_SERVICES_MANAGER_SERVICE, TextServicesManager.class, new CachedServiceFetcher<TextServicesManager>() { @Override public TextServicesManager createService(ContextImpl ctx) throws ServiceNotFoundException { return TextServicesManager.createInstance(ctx); }})511         registerService(Context.TEXT_SERVICES_MANAGER_SERVICE, TextServicesManager.class,
512                 new CachedServiceFetcher<TextServicesManager>() {
513             @Override
514             public TextServicesManager createService(ContextImpl ctx)
515                     throws ServiceNotFoundException {
516                 return TextServicesManager.createInstance(ctx);
517             }});
518 
registerService(Context.KEYGUARD_SERVICE, KeyguardManager.class, new CachedServiceFetcher<KeyguardManager>() { @Override public KeyguardManager createService(ContextImpl ctx) throws ServiceNotFoundException { return new KeyguardManager(ctx); }})519         registerService(Context.KEYGUARD_SERVICE, KeyguardManager.class,
520                 new CachedServiceFetcher<KeyguardManager>() {
521             @Override
522             public KeyguardManager createService(ContextImpl ctx) throws ServiceNotFoundException {
523                 return new KeyguardManager(ctx);
524             }});
525 
registerService(Context.LAYOUT_INFLATER_SERVICE, LayoutInflater.class, new CachedServiceFetcher<LayoutInflater>() { @Override public LayoutInflater createService(ContextImpl ctx) { return new PhoneLayoutInflater(ctx.getOuterContext()); }})526         registerService(Context.LAYOUT_INFLATER_SERVICE, LayoutInflater.class,
527                 new CachedServiceFetcher<LayoutInflater>() {
528             @Override
529             public LayoutInflater createService(ContextImpl ctx) {
530                 return new PhoneLayoutInflater(ctx.getOuterContext());
531             }});
532 
registerService(Context.LOCATION_SERVICE, LocationManager.class, new CachedServiceFetcher<LocationManager>() { @Override public LocationManager createService(ContextImpl ctx) throws ServiceNotFoundException { IBinder b = ServiceManager.getServiceOrThrow(Context.LOCATION_SERVICE); return new LocationManager(ctx, ILocationManager.Stub.asInterface(b)); }})533         registerService(Context.LOCATION_SERVICE, LocationManager.class,
534                 new CachedServiceFetcher<LocationManager>() {
535             @Override
536             public LocationManager createService(ContextImpl ctx) throws ServiceNotFoundException {
537                 IBinder b = ServiceManager.getServiceOrThrow(Context.LOCATION_SERVICE);
538                 return new LocationManager(ctx, ILocationManager.Stub.asInterface(b));
539             }});
540 
registerService(Context.NETWORK_POLICY_SERVICE, NetworkPolicyManager.class, new CachedServiceFetcher<NetworkPolicyManager>() { @Override public NetworkPolicyManager createService(ContextImpl ctx) throws ServiceNotFoundException { return new NetworkPolicyManager(ctx, INetworkPolicyManager.Stub.asInterface( ServiceManager.getServiceOrThrow(Context.NETWORK_POLICY_SERVICE))); }})541         registerService(Context.NETWORK_POLICY_SERVICE, NetworkPolicyManager.class,
542                 new CachedServiceFetcher<NetworkPolicyManager>() {
543             @Override
544             public NetworkPolicyManager createService(ContextImpl ctx) throws ServiceNotFoundException {
545                 return new NetworkPolicyManager(ctx, INetworkPolicyManager.Stub.asInterface(
546                         ServiceManager.getServiceOrThrow(Context.NETWORK_POLICY_SERVICE)));
547             }});
548 
registerService(Context.NOTIFICATION_SERVICE, NotificationManager.class, new CachedServiceFetcher<NotificationManager>() { @Override public NotificationManager createService(ContextImpl ctx) { final Context outerContext = ctx.getOuterContext(); return new NotificationManager( new ContextThemeWrapper(outerContext, Resources.selectSystemTheme(0, outerContext.getApplicationInfo().targetSdkVersion, com.android.internal.R.style.Theme_Dialog, com.android.internal.R.style.Theme_Holo_Dialog, com.android.internal.R.style.Theme_DeviceDefault_Dialog, com.android.internal.R.style.Theme_DeviceDefault_Light_Dialog)), ctx.mMainThread.getHandler()); }})549         registerService(Context.NOTIFICATION_SERVICE, NotificationManager.class,
550                 new CachedServiceFetcher<NotificationManager>() {
551             @Override
552             public NotificationManager createService(ContextImpl ctx) {
553                 final Context outerContext = ctx.getOuterContext();
554                 return new NotificationManager(
555                     new ContextThemeWrapper(outerContext,
556                             Resources.selectSystemTheme(0,
557                                     outerContext.getApplicationInfo().targetSdkVersion,
558                                     com.android.internal.R.style.Theme_Dialog,
559                                     com.android.internal.R.style.Theme_Holo_Dialog,
560                                     com.android.internal.R.style.Theme_DeviceDefault_Dialog,
561                                     com.android.internal.R.style.Theme_DeviceDefault_Light_Dialog)),
562                     ctx.mMainThread.getHandler());
563             }});
564 
registerService(Context.NSD_SERVICE, NsdManager.class, new CachedServiceFetcher<NsdManager>() { @Override public NsdManager createService(ContextImpl ctx) throws ServiceNotFoundException { IBinder b = ServiceManager.getServiceOrThrow(Context.NSD_SERVICE); INsdManager service = INsdManager.Stub.asInterface(b); return new NsdManager(ctx.getOuterContext(), service); }})565         registerService(Context.NSD_SERVICE, NsdManager.class,
566                 new CachedServiceFetcher<NsdManager>() {
567             @Override
568             public NsdManager createService(ContextImpl ctx) throws ServiceNotFoundException {
569                 IBinder b = ServiceManager.getServiceOrThrow(Context.NSD_SERVICE);
570                 INsdManager service = INsdManager.Stub.asInterface(b);
571                 return new NsdManager(ctx.getOuterContext(), service);
572             }});
573 
registerService(Context.POWER_SERVICE, PowerManager.class, new CachedServiceFetcher<PowerManager>() { @Override public PowerManager createService(ContextImpl ctx) throws ServiceNotFoundException { IBinder powerBinder = ServiceManager.getServiceOrThrow(Context.POWER_SERVICE); IPowerManager powerService = IPowerManager.Stub.asInterface(powerBinder); IBinder thermalBinder = ServiceManager.getServiceOrThrow(Context.THERMAL_SERVICE); IThermalService thermalService = IThermalService.Stub.asInterface(thermalBinder); return new PowerManager(ctx.getOuterContext(), powerService, thermalService, ctx.mMainThread.getHandler()); }})574         registerService(Context.POWER_SERVICE, PowerManager.class,
575                 new CachedServiceFetcher<PowerManager>() {
576             @Override
577             public PowerManager createService(ContextImpl ctx) throws ServiceNotFoundException {
578                 IBinder powerBinder = ServiceManager.getServiceOrThrow(Context.POWER_SERVICE);
579                 IPowerManager powerService = IPowerManager.Stub.asInterface(powerBinder);
580                 IBinder thermalBinder = ServiceManager.getServiceOrThrow(Context.THERMAL_SERVICE);
581                 IThermalService thermalService = IThermalService.Stub.asInterface(thermalBinder);
582                 return new PowerManager(ctx.getOuterContext(), powerService, thermalService,
583                         ctx.mMainThread.getHandler());
584             }});
585 
registerService(Context.RECOVERY_SERVICE, RecoverySystem.class, new CachedServiceFetcher<RecoverySystem>() { @Override public RecoverySystem createService(ContextImpl ctx) throws ServiceNotFoundException { IBinder b = ServiceManager.getServiceOrThrow(Context.RECOVERY_SERVICE); IRecoverySystem service = IRecoverySystem.Stub.asInterface(b); return new RecoverySystem(service); }})586         registerService(Context.RECOVERY_SERVICE, RecoverySystem.class,
587                 new CachedServiceFetcher<RecoverySystem>() {
588             @Override
589             public RecoverySystem createService(ContextImpl ctx) throws ServiceNotFoundException {
590                 IBinder b = ServiceManager.getServiceOrThrow(Context.RECOVERY_SERVICE);
591                 IRecoverySystem service = IRecoverySystem.Stub.asInterface(b);
592                 return new RecoverySystem(service);
593             }});
594 
registerService(Context.SEARCH_SERVICE, SearchManager.class, new CachedServiceFetcher<SearchManager>() { @Override public SearchManager createService(ContextImpl ctx) throws ServiceNotFoundException { return new SearchManager(ctx.getOuterContext(), ctx.mMainThread.getHandler()); }})595         registerService(Context.SEARCH_SERVICE, SearchManager.class,
596                 new CachedServiceFetcher<SearchManager>() {
597             @Override
598             public SearchManager createService(ContextImpl ctx) throws ServiceNotFoundException {
599                 return new SearchManager(ctx.getOuterContext(),
600                         ctx.mMainThread.getHandler());
601             }});
602 
registerService(Context.SENSOR_SERVICE, SensorManager.class, new CachedServiceFetcher<SensorManager>() { @Override public SensorManager createService(ContextImpl ctx) { return new SystemSensorManager(ctx.getOuterContext(), ctx.mMainThread.getHandler().getLooper()); }})603         registerService(Context.SENSOR_SERVICE, SensorManager.class,
604                 new CachedServiceFetcher<SensorManager>() {
605             @Override
606             public SensorManager createService(ContextImpl ctx) {
607                 return new SystemSensorManager(ctx.getOuterContext(),
608                   ctx.mMainThread.getHandler().getLooper());
609             }});
610 
registerService(Context.SENSOR_PRIVACY_SERVICE, SensorPrivacyManager.class, new CachedServiceFetcher<SensorPrivacyManager>() { @Override public SensorPrivacyManager createService(ContextImpl ctx) { return SensorPrivacyManager.getInstance(ctx); }})611         registerService(Context.SENSOR_PRIVACY_SERVICE, SensorPrivacyManager.class,
612                 new CachedServiceFetcher<SensorPrivacyManager>() {
613                     @Override
614                     public SensorPrivacyManager createService(ContextImpl ctx) {
615                         return SensorPrivacyManager.getInstance(ctx);
616                     }});
617 
registerService(Context.STATUS_BAR_SERVICE, StatusBarManager.class, new CachedServiceFetcher<StatusBarManager>() { @Override public StatusBarManager createService(ContextImpl ctx) { return new StatusBarManager(ctx.getOuterContext()); }})618         registerService(Context.STATUS_BAR_SERVICE, StatusBarManager.class,
619                 new CachedServiceFetcher<StatusBarManager>() {
620             @Override
621             public StatusBarManager createService(ContextImpl ctx) {
622                 return new StatusBarManager(ctx.getOuterContext());
623             }});
624 
registerService(Context.STORAGE_SERVICE, StorageManager.class, new CachedServiceFetcher<StorageManager>() { @Override public StorageManager createService(ContextImpl ctx) throws ServiceNotFoundException { return new StorageManager(ctx, ctx.mMainThread.getHandler().getLooper()); }})625         registerService(Context.STORAGE_SERVICE, StorageManager.class,
626                 new CachedServiceFetcher<StorageManager>() {
627             @Override
628             public StorageManager createService(ContextImpl ctx) throws ServiceNotFoundException {
629                 return new StorageManager(ctx, ctx.mMainThread.getHandler().getLooper());
630             }});
631 
registerService(Context.STORAGE_STATS_SERVICE, StorageStatsManager.class, new CachedServiceFetcher<StorageStatsManager>() { @Override public StorageStatsManager createService(ContextImpl ctx) throws ServiceNotFoundException { IStorageStatsManager service = IStorageStatsManager.Stub.asInterface( ServiceManager.getServiceOrThrow(Context.STORAGE_STATS_SERVICE)); return new StorageStatsManager(ctx, service); }})632         registerService(Context.STORAGE_STATS_SERVICE, StorageStatsManager.class,
633                 new CachedServiceFetcher<StorageStatsManager>() {
634             @Override
635             public StorageStatsManager createService(ContextImpl ctx) throws ServiceNotFoundException {
636                 IStorageStatsManager service = IStorageStatsManager.Stub.asInterface(
637                         ServiceManager.getServiceOrThrow(Context.STORAGE_STATS_SERVICE));
638                 return new StorageStatsManager(ctx, service);
639             }});
640 
registerService(Context.SYSTEM_UPDATE_SERVICE, SystemUpdateManager.class, new CachedServiceFetcher<SystemUpdateManager>() { @Override public SystemUpdateManager createService(ContextImpl ctx) throws ServiceNotFoundException { IBinder b = ServiceManager.getServiceOrThrow( Context.SYSTEM_UPDATE_SERVICE); ISystemUpdateManager service = ISystemUpdateManager.Stub.asInterface(b); return new SystemUpdateManager(service); }})641         registerService(Context.SYSTEM_UPDATE_SERVICE, SystemUpdateManager.class,
642                 new CachedServiceFetcher<SystemUpdateManager>() {
643                     @Override
644                     public SystemUpdateManager createService(ContextImpl ctx)
645                             throws ServiceNotFoundException {
646                         IBinder b = ServiceManager.getServiceOrThrow(
647                                 Context.SYSTEM_UPDATE_SERVICE);
648                         ISystemUpdateManager service = ISystemUpdateManager.Stub.asInterface(b);
649                         return new SystemUpdateManager(service);
650                     }});
651 
registerService(Context.SYSTEM_CONFIG_SERVICE, SystemConfigManager.class, new CachedServiceFetcher<SystemConfigManager>() { @Override public SystemConfigManager createService(ContextImpl ctx) { return new SystemConfigManager(); }})652         registerService(Context.SYSTEM_CONFIG_SERVICE, SystemConfigManager.class,
653                 new CachedServiceFetcher<SystemConfigManager>() {
654                     @Override
655                     public SystemConfigManager createService(ContextImpl ctx) {
656                         return new SystemConfigManager();
657                     }});
658 
registerService(Context.TELEPHONY_REGISTRY_SERVICE, TelephonyRegistryManager.class, new CachedServiceFetcher<TelephonyRegistryManager>() { @Override public TelephonyRegistryManager createService(ContextImpl ctx) { return new TelephonyRegistryManager(ctx); }})659         registerService(Context.TELEPHONY_REGISTRY_SERVICE, TelephonyRegistryManager.class,
660             new CachedServiceFetcher<TelephonyRegistryManager>() {
661                 @Override
662                 public TelephonyRegistryManager createService(ContextImpl ctx) {
663                     return new TelephonyRegistryManager(ctx);
664                 }});
665 
registerService(Context.TELECOM_SERVICE, TelecomManager.class, new CachedServiceFetcher<TelecomManager>() { @Override public TelecomManager createService(ContextImpl ctx) { return new TelecomManager(ctx.getOuterContext()); }})666         registerService(Context.TELECOM_SERVICE, TelecomManager.class,
667                 new CachedServiceFetcher<TelecomManager>() {
668             @Override
669             public TelecomManager createService(ContextImpl ctx) {
670                 return new TelecomManager(ctx.getOuterContext());
671             }});
672 
registerService(Context.MMS_SERVICE, MmsManager.class, new CachedServiceFetcher<MmsManager>() { @Override public MmsManager createService(ContextImpl ctx) { return new MmsManager(ctx.getOuterContext()); }})673         registerService(Context.MMS_SERVICE, MmsManager.class,
674                 new CachedServiceFetcher<MmsManager>() {
675                     @Override
676                     public MmsManager createService(ContextImpl ctx) {
677                         return new MmsManager(ctx.getOuterContext());
678                     }});
679 
registerService(Context.UI_MODE_SERVICE, UiModeManager.class, new CachedServiceFetcher<UiModeManager>() { @Override public UiModeManager createService(ContextImpl ctx) throws ServiceNotFoundException { return new UiModeManager(ctx.getOuterContext()); }})680         registerService(Context.UI_MODE_SERVICE, UiModeManager.class,
681                 new CachedServiceFetcher<UiModeManager>() {
682             @Override
683             public UiModeManager createService(ContextImpl ctx) throws ServiceNotFoundException {
684                 return new UiModeManager(ctx.getOuterContext());
685             }});
686 
registerService(Context.USB_SERVICE, UsbManager.class, new CachedServiceFetcher<UsbManager>() { @Override public UsbManager createService(ContextImpl ctx) throws ServiceNotFoundException { IBinder b = ServiceManager.getServiceOrThrow(Context.USB_SERVICE); return new UsbManager(ctx, IUsbManager.Stub.asInterface(b)); }})687         registerService(Context.USB_SERVICE, UsbManager.class,
688                 new CachedServiceFetcher<UsbManager>() {
689             @Override
690             public UsbManager createService(ContextImpl ctx) throws ServiceNotFoundException {
691                 IBinder b = ServiceManager.getServiceOrThrow(Context.USB_SERVICE);
692                 return new UsbManager(ctx, IUsbManager.Stub.asInterface(b));
693             }});
694 
registerService(Context.ADB_SERVICE, AdbManager.class, new CachedServiceFetcher<AdbManager>() { @Override public AdbManager createService(ContextImpl ctx) throws ServiceNotFoundException { IBinder b = ServiceManager.getServiceOrThrow(Context.ADB_SERVICE); return new AdbManager(ctx, IAdbManager.Stub.asInterface(b)); }})695         registerService(Context.ADB_SERVICE, AdbManager.class,
696                 new CachedServiceFetcher<AdbManager>() {
697                     @Override
698                     public AdbManager createService(ContextImpl ctx)
699                                 throws ServiceNotFoundException {
700                         IBinder b = ServiceManager.getServiceOrThrow(Context.ADB_SERVICE);
701                         return new AdbManager(ctx, IAdbManager.Stub.asInterface(b));
702                     }});
703 
registerService(Context.SERIAL_SERVICE, SerialManager.class, new CachedServiceFetcher<SerialManager>() { @Override public SerialManager createService(ContextImpl ctx) throws ServiceNotFoundException { IBinder b = ServiceManager.getServiceOrThrow(Context.SERIAL_SERVICE); return new SerialManager(ctx, ISerialManager.Stub.asInterface(b)); }})704         registerService(Context.SERIAL_SERVICE, SerialManager.class,
705                 new CachedServiceFetcher<SerialManager>() {
706             @Override
707             public SerialManager createService(ContextImpl ctx) throws ServiceNotFoundException {
708                 IBinder b = ServiceManager.getServiceOrThrow(Context.SERIAL_SERVICE);
709                 return new SerialManager(ctx, ISerialManager.Stub.asInterface(b));
710             }});
711 
registerService(Context.VIBRATOR_SERVICE, Vibrator.class, new CachedServiceFetcher<Vibrator>() { @Override public Vibrator createService(ContextImpl ctx) { return new SystemVibrator(ctx); }})712         registerService(Context.VIBRATOR_SERVICE, Vibrator.class,
713                 new CachedServiceFetcher<Vibrator>() {
714             @Override
715             public Vibrator createService(ContextImpl ctx) {
716                 return new SystemVibrator(ctx);
717             }});
718 
registerService(Context.WALLPAPER_SERVICE, WallpaperManager.class, new CachedServiceFetcher<WallpaperManager>() { @Override public WallpaperManager createService(ContextImpl ctx) throws ServiceNotFoundException { final IBinder b = ServiceManager.getService(Context.WALLPAPER_SERVICE); if (b == null) { ApplicationInfo appInfo = ctx.getApplicationInfo(); if (appInfo.targetSdkVersion >= Build.VERSION_CODES.P && appInfo.isInstantApp()) { throw new ServiceNotFoundException(Context.WALLPAPER_SERVICE); } final boolean enabled = Resources.getSystem() .getBoolean(com.android.internal.R.bool.config_enableWallpaperService); if (!enabled) { return DisabledWallpaperManager.getInstance(); } Log.e(TAG, "No wallpaper service"); } IWallpaperManager service = IWallpaperManager.Stub.asInterface(b); return new WallpaperManager(service, ctx.getOuterContext(), ctx.mMainThread.getHandler()); }})719         registerService(Context.WALLPAPER_SERVICE, WallpaperManager.class,
720                 new CachedServiceFetcher<WallpaperManager>() {
721             @Override
722             public WallpaperManager createService(ContextImpl ctx)
723                     throws ServiceNotFoundException {
724                 final IBinder b = ServiceManager.getService(Context.WALLPAPER_SERVICE);
725                 if (b == null) {
726                     ApplicationInfo appInfo = ctx.getApplicationInfo();
727                     if (appInfo.targetSdkVersion >= Build.VERSION_CODES.P
728                             && appInfo.isInstantApp()) {
729                         // Instant app
730                         throw new ServiceNotFoundException(Context.WALLPAPER_SERVICE);
731                     }
732                     final boolean enabled = Resources.getSystem()
733                             .getBoolean(com.android.internal.R.bool.config_enableWallpaperService);
734                     if (!enabled) {
735                         // Device doesn't support wallpaper, return a limited manager
736                         return DisabledWallpaperManager.getInstance();
737                     }
738                     // Bad state - WallpaperManager methods will throw exception
739                     Log.e(TAG, "No wallpaper service");
740                 }
741                 IWallpaperManager service = IWallpaperManager.Stub.asInterface(b);
742                 return new WallpaperManager(service, ctx.getOuterContext(),
743                         ctx.mMainThread.getHandler());
744             }});
745 
registerService(Context.LOWPAN_SERVICE, LowpanManager.class, new CachedServiceFetcher<LowpanManager>() { @Override public LowpanManager createService(ContextImpl ctx) throws ServiceNotFoundException { IBinder b = ServiceManager.getServiceOrThrow(Context.LOWPAN_SERVICE); ILowpanManager service = ILowpanManager.Stub.asInterface(b); return new LowpanManager(ctx.getOuterContext(), service, ConnectivityThread.getInstanceLooper()); }})746         registerService(Context.LOWPAN_SERVICE, LowpanManager.class,
747                 new CachedServiceFetcher<LowpanManager>() {
748             @Override
749             public LowpanManager createService(ContextImpl ctx) throws ServiceNotFoundException {
750                 IBinder b = ServiceManager.getServiceOrThrow(Context.LOWPAN_SERVICE);
751                 ILowpanManager service = ILowpanManager.Stub.asInterface(b);
752                 return new LowpanManager(ctx.getOuterContext(), service,
753                         ConnectivityThread.getInstanceLooper());
754             }});
755 
registerService(Context.ETHERNET_SERVICE, EthernetManager.class, new CachedServiceFetcher<EthernetManager>() { @Override public EthernetManager createService(ContextImpl ctx) throws ServiceNotFoundException { IBinder b = ServiceManager.getServiceOrThrow(Context.ETHERNET_SERVICE); IEthernetManager service = IEthernetManager.Stub.asInterface(b); return new EthernetManager(ctx.getOuterContext(), service); }})756         registerService(Context.ETHERNET_SERVICE, EthernetManager.class,
757                 new CachedServiceFetcher<EthernetManager>() {
758             @Override
759             public EthernetManager createService(ContextImpl ctx) throws ServiceNotFoundException {
760                 IBinder b = ServiceManager.getServiceOrThrow(Context.ETHERNET_SERVICE);
761                 IEthernetManager service = IEthernetManager.Stub.asInterface(b);
762                 return new EthernetManager(ctx.getOuterContext(), service);
763             }});
764 
registerService(Context.WIFI_NL80211_SERVICE, WifiNl80211Manager.class, new CachedServiceFetcher<WifiNl80211Manager>() { @Override public WifiNl80211Manager createService(ContextImpl ctx) { return new WifiNl80211Manager(ctx.getOuterContext()); } })765         registerService(Context.WIFI_NL80211_SERVICE, WifiNl80211Manager.class,
766                 new CachedServiceFetcher<WifiNl80211Manager>() {
767                     @Override
768                     public WifiNl80211Manager createService(ContextImpl ctx) {
769                         return new WifiNl80211Manager(ctx.getOuterContext());
770                     }
771                 });
772 
registerService(Context.WINDOW_SERVICE, WindowManager.class, new CachedServiceFetcher<WindowManager>() { @Override public WindowManager createService(ContextImpl ctx) { return new WindowManagerImpl(ctx); }})773         registerService(Context.WINDOW_SERVICE, WindowManager.class,
774                 new CachedServiceFetcher<WindowManager>() {
775             @Override
776             public WindowManager createService(ContextImpl ctx) {
777                 return new WindowManagerImpl(ctx);
778             }});
779 
registerService(Context.USER_SERVICE, UserManager.class, new CachedServiceFetcher<UserManager>() { @Override public UserManager createService(ContextImpl ctx) throws ServiceNotFoundException { IBinder b = ServiceManager.getServiceOrThrow(Context.USER_SERVICE); IUserManager service = IUserManager.Stub.asInterface(b); return new UserManager(ctx, service); }})780         registerService(Context.USER_SERVICE, UserManager.class,
781                 new CachedServiceFetcher<UserManager>() {
782             @Override
783             public UserManager createService(ContextImpl ctx) throws ServiceNotFoundException {
784                 IBinder b = ServiceManager.getServiceOrThrow(Context.USER_SERVICE);
785                 IUserManager service = IUserManager.Stub.asInterface(b);
786                 return new UserManager(ctx, service);
787             }});
788 
registerService(Context.APP_OPS_SERVICE, AppOpsManager.class, new CachedServiceFetcher<AppOpsManager>() { @Override public AppOpsManager createService(ContextImpl ctx) throws ServiceNotFoundException { IBinder b = ServiceManager.getServiceOrThrow(Context.APP_OPS_SERVICE); IAppOpsService service = IAppOpsService.Stub.asInterface(b); return new AppOpsManager(ctx, service); }})789         registerService(Context.APP_OPS_SERVICE, AppOpsManager.class,
790                 new CachedServiceFetcher<AppOpsManager>() {
791             @Override
792             public AppOpsManager createService(ContextImpl ctx) throws ServiceNotFoundException {
793                 IBinder b = ServiceManager.getServiceOrThrow(Context.APP_OPS_SERVICE);
794                 IAppOpsService service = IAppOpsService.Stub.asInterface(b);
795                 return new AppOpsManager(ctx, service);
796             }});
797 
registerService(Context.CAMERA_SERVICE, CameraManager.class, new CachedServiceFetcher<CameraManager>() { @Override public CameraManager createService(ContextImpl ctx) { return new CameraManager(ctx); }})798         registerService(Context.CAMERA_SERVICE, CameraManager.class,
799                 new CachedServiceFetcher<CameraManager>() {
800             @Override
801             public CameraManager createService(ContextImpl ctx) {
802                 return new CameraManager(ctx);
803             }});
804 
registerService(Context.LAUNCHER_APPS_SERVICE, LauncherApps.class, new CachedServiceFetcher<LauncherApps>() { @Override public LauncherApps createService(ContextImpl ctx) { return new LauncherApps(ctx); }})805         registerService(Context.LAUNCHER_APPS_SERVICE, LauncherApps.class,
806                 new CachedServiceFetcher<LauncherApps>() {
807             @Override
808             public LauncherApps createService(ContextImpl ctx) {
809                 return new LauncherApps(ctx);
810             }});
811 
registerService(Context.RESTRICTIONS_SERVICE, RestrictionsManager.class, new CachedServiceFetcher<RestrictionsManager>() { @Override public RestrictionsManager createService(ContextImpl ctx) throws ServiceNotFoundException { IBinder b = ServiceManager.getServiceOrThrow(Context.RESTRICTIONS_SERVICE); IRestrictionsManager service = IRestrictionsManager.Stub.asInterface(b); return new RestrictionsManager(ctx, service); }})812         registerService(Context.RESTRICTIONS_SERVICE, RestrictionsManager.class,
813                 new CachedServiceFetcher<RestrictionsManager>() {
814             @Override
815             public RestrictionsManager createService(ContextImpl ctx) throws ServiceNotFoundException {
816                 IBinder b = ServiceManager.getServiceOrThrow(Context.RESTRICTIONS_SERVICE);
817                 IRestrictionsManager service = IRestrictionsManager.Stub.asInterface(b);
818                 return new RestrictionsManager(ctx, service);
819             }});
820 
registerService(Context.PRINT_SERVICE, PrintManager.class, new CachedServiceFetcher<PrintManager>() { @Override public PrintManager createService(ContextImpl ctx) throws ServiceNotFoundException { IPrintManager service = null; if (ctx.getPackageManager().hasSystemFeature(PackageManager.FEATURE_PRINTING)) { service = IPrintManager.Stub.asInterface(ServiceManager .getServiceOrThrow(Context.PRINT_SERVICE)); } final int userId = ctx.getUserId(); final int appId = UserHandle.getAppId(ctx.getApplicationInfo().uid); return new PrintManager(ctx.getOuterContext(), service, userId, appId); }})821         registerService(Context.PRINT_SERVICE, PrintManager.class,
822                 new CachedServiceFetcher<PrintManager>() {
823             @Override
824             public PrintManager createService(ContextImpl ctx) throws ServiceNotFoundException {
825                 IPrintManager service = null;
826                 // If the feature not present, don't try to look up every time
827                 if (ctx.getPackageManager().hasSystemFeature(PackageManager.FEATURE_PRINTING)) {
828                     service = IPrintManager.Stub.asInterface(ServiceManager
829                             .getServiceOrThrow(Context.PRINT_SERVICE));
830                 }
831                 final int userId = ctx.getUserId();
832                 final int appId = UserHandle.getAppId(ctx.getApplicationInfo().uid);
833                 return new PrintManager(ctx.getOuterContext(), service, userId, appId);
834             }});
835 
registerService(Context.COMPANION_DEVICE_SERVICE, CompanionDeviceManager.class, new CachedServiceFetcher<CompanionDeviceManager>() { @Override public CompanionDeviceManager createService(ContextImpl ctx) throws ServiceNotFoundException { ICompanionDeviceManager service = null; if (ctx.getPackageManager().hasSystemFeature( PackageManager.FEATURE_COMPANION_DEVICE_SETUP)) { service = ICompanionDeviceManager.Stub.asInterface( ServiceManager.getServiceOrThrow(Context.COMPANION_DEVICE_SERVICE)); } return new CompanionDeviceManager(service, ctx.getOuterContext()); }})836         registerService(Context.COMPANION_DEVICE_SERVICE, CompanionDeviceManager.class,
837                 new CachedServiceFetcher<CompanionDeviceManager>() {
838             @Override
839             public CompanionDeviceManager createService(ContextImpl ctx)
840                     throws ServiceNotFoundException {
841                 ICompanionDeviceManager service = null;
842                 // If the feature not present, don't try to look up every time
843                 if (ctx.getPackageManager().hasSystemFeature(
844                         PackageManager.FEATURE_COMPANION_DEVICE_SETUP)) {
845                     service = ICompanionDeviceManager.Stub.asInterface(
846                             ServiceManager.getServiceOrThrow(Context.COMPANION_DEVICE_SERVICE));
847                 }
848                 return new CompanionDeviceManager(service, ctx.getOuterContext());
849             }});
850 
registerService(Context.CONSUMER_IR_SERVICE, ConsumerIrManager.class, new CachedServiceFetcher<ConsumerIrManager>() { @Override public ConsumerIrManager createService(ContextImpl ctx) throws ServiceNotFoundException { return new ConsumerIrManager(ctx); }})851         registerService(Context.CONSUMER_IR_SERVICE, ConsumerIrManager.class,
852                 new CachedServiceFetcher<ConsumerIrManager>() {
853             @Override
854             public ConsumerIrManager createService(ContextImpl ctx) throws ServiceNotFoundException {
855                 return new ConsumerIrManager(ctx);
856             }});
857 
registerService(Context.MEDIA_SESSION_SERVICE, MediaSessionManager.class, new CachedServiceFetcher<MediaSessionManager>() { @Override public MediaSessionManager createService(ContextImpl ctx) { return new MediaSessionManager(ctx); }})858         registerService(Context.MEDIA_SESSION_SERVICE, MediaSessionManager.class,
859                 new CachedServiceFetcher<MediaSessionManager>() {
860             @Override
861             public MediaSessionManager createService(ContextImpl ctx) {
862                 return new MediaSessionManager(ctx);
863             }});
864 
registerService(Context.TRUST_SERVICE, TrustManager.class, new StaticServiceFetcher<TrustManager>() { @Override public TrustManager createService() throws ServiceNotFoundException { IBinder b = ServiceManager.getServiceOrThrow(Context.TRUST_SERVICE); return new TrustManager(b); }})865         registerService(Context.TRUST_SERVICE, TrustManager.class,
866                 new StaticServiceFetcher<TrustManager>() {
867             @Override
868             public TrustManager createService() throws ServiceNotFoundException {
869                 IBinder b = ServiceManager.getServiceOrThrow(Context.TRUST_SERVICE);
870                 return new TrustManager(b);
871             }});
872 
registerService(Context.FINGERPRINT_SERVICE, FingerprintManager.class, new CachedServiceFetcher<FingerprintManager>() { @Override public FingerprintManager createService(ContextImpl ctx) throws ServiceNotFoundException { final IBinder binder; if (ctx.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.O) { binder = ServiceManager.getServiceOrThrow(Context.FINGERPRINT_SERVICE); } else { binder = ServiceManager.getService(Context.FINGERPRINT_SERVICE); } IFingerprintService service = IFingerprintService.Stub.asInterface(binder); return new FingerprintManager(ctx.getOuterContext(), service); }})873         registerService(Context.FINGERPRINT_SERVICE, FingerprintManager.class,
874                 new CachedServiceFetcher<FingerprintManager>() {
875             @Override
876             public FingerprintManager createService(ContextImpl ctx) throws ServiceNotFoundException {
877                 final IBinder binder;
878                 if (ctx.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.O) {
879                     binder = ServiceManager.getServiceOrThrow(Context.FINGERPRINT_SERVICE);
880                 } else {
881                     binder = ServiceManager.getService(Context.FINGERPRINT_SERVICE);
882                 }
883                 IFingerprintService service = IFingerprintService.Stub.asInterface(binder);
884                 return new FingerprintManager(ctx.getOuterContext(), service);
885             }});
886 
registerService(Context.FACE_SERVICE, FaceManager.class, new CachedServiceFetcher<FaceManager>() { @Override public FaceManager createService(ContextImpl ctx) throws ServiceNotFoundException { final IBinder binder; if (ctx.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.O) { binder = ServiceManager.getServiceOrThrow(Context.FACE_SERVICE); } else { binder = ServiceManager.getService(Context.FACE_SERVICE); } IFaceService service = IFaceService.Stub.asInterface(binder); return new FaceManager(ctx.getOuterContext(), service); } })887         registerService(Context.FACE_SERVICE, FaceManager.class,
888                 new CachedServiceFetcher<FaceManager>() {
889                     @Override
890                     public FaceManager createService(ContextImpl ctx)
891                             throws ServiceNotFoundException {
892                         final IBinder binder;
893                         if (ctx.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.O) {
894                             binder = ServiceManager.getServiceOrThrow(Context.FACE_SERVICE);
895                         } else {
896                             binder = ServiceManager.getService(Context.FACE_SERVICE);
897                         }
898                         IFaceService service = IFaceService.Stub.asInterface(binder);
899                         return new FaceManager(ctx.getOuterContext(), service);
900                     }
901                 });
902 
registerService(Context.IRIS_SERVICE, IrisManager.class, new CachedServiceFetcher<IrisManager>() { @Override public IrisManager createService(ContextImpl ctx) throws ServiceNotFoundException { final IBinder binder = ServiceManager.getServiceOrThrow(Context.IRIS_SERVICE); IIrisService service = IIrisService.Stub.asInterface(binder); return new IrisManager(ctx.getOuterContext(), service); } })903         registerService(Context.IRIS_SERVICE, IrisManager.class,
904                 new CachedServiceFetcher<IrisManager>() {
905                     @Override
906                     public IrisManager createService(ContextImpl ctx)
907                         throws ServiceNotFoundException {
908                         final IBinder binder =
909                                 ServiceManager.getServiceOrThrow(Context.IRIS_SERVICE);
910                         IIrisService service = IIrisService.Stub.asInterface(binder);
911                         return new IrisManager(ctx.getOuterContext(), service);
912                     }
913                 });
914 
registerService(Context.BIOMETRIC_SERVICE, BiometricManager.class, new CachedServiceFetcher<BiometricManager>() { @Override public BiometricManager createService(ContextImpl ctx) throws ServiceNotFoundException { final IBinder binder = ServiceManager.getServiceOrThrow(Context.AUTH_SERVICE); final IAuthService service = IAuthService.Stub.asInterface(binder); return new BiometricManager(ctx.getOuterContext(), service); } })915         registerService(Context.BIOMETRIC_SERVICE, BiometricManager.class,
916                 new CachedServiceFetcher<BiometricManager>() {
917                     @Override
918                     public BiometricManager createService(ContextImpl ctx)
919                             throws ServiceNotFoundException {
920                         final IBinder binder =
921                                 ServiceManager.getServiceOrThrow(Context.AUTH_SERVICE);
922                         final IAuthService service =
923                                 IAuthService.Stub.asInterface(binder);
924                         return new BiometricManager(ctx.getOuterContext(), service);
925                     }
926                 });
927 
registerService(Context.TV_INPUT_SERVICE, TvInputManager.class, new CachedServiceFetcher<TvInputManager>() { @Override public TvInputManager createService(ContextImpl ctx) throws ServiceNotFoundException { IBinder iBinder = ServiceManager.getServiceOrThrow(Context.TV_INPUT_SERVICE); ITvInputManager service = ITvInputManager.Stub.asInterface(iBinder); return new TvInputManager(service, ctx.getUserId()); }})928         registerService(Context.TV_INPUT_SERVICE, TvInputManager.class,
929                 new CachedServiceFetcher<TvInputManager>() {
930             @Override
931             public TvInputManager createService(ContextImpl ctx) throws ServiceNotFoundException {
932                 IBinder iBinder = ServiceManager.getServiceOrThrow(Context.TV_INPUT_SERVICE);
933                 ITvInputManager service = ITvInputManager.Stub.asInterface(iBinder);
934                 return new TvInputManager(service, ctx.getUserId());
935             }});
936 
registerService(Context.TV_TUNER_RESOURCE_MGR_SERVICE, TunerResourceManager.class, new CachedServiceFetcher<TunerResourceManager>() { @Override public TunerResourceManager createService(ContextImpl ctx) throws ServiceNotFoundException { IBinder iBinder = ServiceManager.getServiceOrThrow(Context.TV_TUNER_RESOURCE_MGR_SERVICE); ITunerResourceManager service = ITunerResourceManager.Stub.asInterface(iBinder); return new TunerResourceManager(service, ctx.getUserId()); }})937         registerService(Context.TV_TUNER_RESOURCE_MGR_SERVICE, TunerResourceManager.class,
938                 new CachedServiceFetcher<TunerResourceManager>() {
939             @Override
940             public TunerResourceManager createService(ContextImpl ctx)
941                     throws ServiceNotFoundException {
942                 IBinder iBinder =
943                         ServiceManager.getServiceOrThrow(Context.TV_TUNER_RESOURCE_MGR_SERVICE);
944                 ITunerResourceManager service = ITunerResourceManager.Stub.asInterface(iBinder);
945                 return new TunerResourceManager(service, ctx.getUserId());
946             }});
947 
registerService(Context.NETWORK_SCORE_SERVICE, NetworkScoreManager.class, new CachedServiceFetcher<NetworkScoreManager>() { @Override public NetworkScoreManager createService(ContextImpl ctx) throws ServiceNotFoundException { return new NetworkScoreManager(ctx); }})948         registerService(Context.NETWORK_SCORE_SERVICE, NetworkScoreManager.class,
949                 new CachedServiceFetcher<NetworkScoreManager>() {
950             @Override
951             public NetworkScoreManager createService(ContextImpl ctx) throws ServiceNotFoundException {
952                 return new NetworkScoreManager(ctx);
953             }});
954 
registerService(Context.USAGE_STATS_SERVICE, UsageStatsManager.class, new CachedServiceFetcher<UsageStatsManager>() { @Override public UsageStatsManager createService(ContextImpl ctx) throws ServiceNotFoundException { IBinder iBinder = ServiceManager.getServiceOrThrow(Context.USAGE_STATS_SERVICE); IUsageStatsManager service = IUsageStatsManager.Stub.asInterface(iBinder); return new UsageStatsManager(ctx.getOuterContext(), service); }})955         registerService(Context.USAGE_STATS_SERVICE, UsageStatsManager.class,
956                 new CachedServiceFetcher<UsageStatsManager>() {
957             @Override
958             public UsageStatsManager createService(ContextImpl ctx) throws ServiceNotFoundException {
959                 IBinder iBinder = ServiceManager.getServiceOrThrow(Context.USAGE_STATS_SERVICE);
960                 IUsageStatsManager service = IUsageStatsManager.Stub.asInterface(iBinder);
961                 return new UsageStatsManager(ctx.getOuterContext(), service);
962             }});
963 
registerService(Context.NETWORK_STATS_SERVICE, NetworkStatsManager.class, new CachedServiceFetcher<NetworkStatsManager>() { @Override public NetworkStatsManager createService(ContextImpl ctx) throws ServiceNotFoundException { return new NetworkStatsManager(ctx.getOuterContext()); }})964         registerService(Context.NETWORK_STATS_SERVICE, NetworkStatsManager.class,
965                 new CachedServiceFetcher<NetworkStatsManager>() {
966             @Override
967             public NetworkStatsManager createService(ContextImpl ctx) throws ServiceNotFoundException {
968                 return new NetworkStatsManager(ctx.getOuterContext());
969             }});
970 
registerService(Context.PERSISTENT_DATA_BLOCK_SERVICE, PersistentDataBlockManager.class, new StaticServiceFetcher<PersistentDataBlockManager>() { @Override public PersistentDataBlockManager createService() throws ServiceNotFoundException { IBinder b = ServiceManager.getServiceOrThrow(Context.PERSISTENT_DATA_BLOCK_SERVICE); IPersistentDataBlockService persistentDataBlockService = IPersistentDataBlockService.Stub.asInterface(b); if (persistentDataBlockService != null) { return new PersistentDataBlockManager(persistentDataBlockService); } else { return null; } }})971         registerService(Context.PERSISTENT_DATA_BLOCK_SERVICE, PersistentDataBlockManager.class,
972                 new StaticServiceFetcher<PersistentDataBlockManager>() {
973             @Override
974             public PersistentDataBlockManager createService() throws ServiceNotFoundException {
975                 IBinder b = ServiceManager.getServiceOrThrow(Context.PERSISTENT_DATA_BLOCK_SERVICE);
976                 IPersistentDataBlockService persistentDataBlockService =
977                         IPersistentDataBlockService.Stub.asInterface(b);
978                 if (persistentDataBlockService != null) {
979                     return new PersistentDataBlockManager(persistentDataBlockService);
980                 } else {
981                     // not supported
982                     return null;
983                 }
984             }});
985 
registerService(Context.OEM_LOCK_SERVICE, OemLockManager.class, new StaticServiceFetcher<OemLockManager>() { @Override public OemLockManager createService() throws ServiceNotFoundException { IBinder b = ServiceManager.getServiceOrThrow(Context.OEM_LOCK_SERVICE); IOemLockService oemLockService = IOemLockService.Stub.asInterface(b); if (oemLockService != null) { return new OemLockManager(oemLockService); } else { return null; } }})986         registerService(Context.OEM_LOCK_SERVICE, OemLockManager.class,
987                 new StaticServiceFetcher<OemLockManager>() {
988             @Override
989             public OemLockManager createService() throws ServiceNotFoundException {
990                 IBinder b = ServiceManager.getServiceOrThrow(Context.OEM_LOCK_SERVICE);
991                 IOemLockService oemLockService = IOemLockService.Stub.asInterface(b);
992                 if (oemLockService != null) {
993                     return new OemLockManager(oemLockService);
994                 } else {
995                     // not supported
996                     return null;
997                 }
998             }});
999 
registerService(Context.MEDIA_PROJECTION_SERVICE, MediaProjectionManager.class, new CachedServiceFetcher<MediaProjectionManager>() { @Override public MediaProjectionManager createService(ContextImpl ctx) { return new MediaProjectionManager(ctx); }})1000         registerService(Context.MEDIA_PROJECTION_SERVICE, MediaProjectionManager.class,
1001                 new CachedServiceFetcher<MediaProjectionManager>() {
1002             @Override
1003             public MediaProjectionManager createService(ContextImpl ctx) {
1004                 return new MediaProjectionManager(ctx);
1005             }});
1006 
registerService(Context.APPWIDGET_SERVICE, AppWidgetManager.class, new CachedServiceFetcher<AppWidgetManager>() { @Override public AppWidgetManager createService(ContextImpl ctx) throws ServiceNotFoundException { IBinder b = ServiceManager.getServiceOrThrow(Context.APPWIDGET_SERVICE); return new AppWidgetManager(ctx, IAppWidgetService.Stub.asInterface(b)); }})1007         registerService(Context.APPWIDGET_SERVICE, AppWidgetManager.class,
1008                 new CachedServiceFetcher<AppWidgetManager>() {
1009             @Override
1010             public AppWidgetManager createService(ContextImpl ctx) throws ServiceNotFoundException {
1011                 IBinder b = ServiceManager.getServiceOrThrow(Context.APPWIDGET_SERVICE);
1012                 return new AppWidgetManager(ctx, IAppWidgetService.Stub.asInterface(b));
1013             }});
1014 
registerService(Context.MIDI_SERVICE, MidiManager.class, new CachedServiceFetcher<MidiManager>() { @Override public MidiManager createService(ContextImpl ctx) throws ServiceNotFoundException { IBinder b = ServiceManager.getServiceOrThrow(Context.MIDI_SERVICE); return new MidiManager(IMidiManager.Stub.asInterface(b)); }})1015         registerService(Context.MIDI_SERVICE, MidiManager.class,
1016                 new CachedServiceFetcher<MidiManager>() {
1017             @Override
1018             public MidiManager createService(ContextImpl ctx) throws ServiceNotFoundException {
1019                 IBinder b = ServiceManager.getServiceOrThrow(Context.MIDI_SERVICE);
1020                 return new MidiManager(IMidiManager.Stub.asInterface(b));
1021             }});
1022 
registerService(Context.RADIO_SERVICE, RadioManager.class, new CachedServiceFetcher<RadioManager>() { @Override public RadioManager createService(ContextImpl ctx) throws ServiceNotFoundException { return new RadioManager(ctx); }})1023         registerService(Context.RADIO_SERVICE, RadioManager.class,
1024                 new CachedServiceFetcher<RadioManager>() {
1025             @Override
1026             public RadioManager createService(ContextImpl ctx) throws ServiceNotFoundException {
1027                 return new RadioManager(ctx);
1028             }});
1029 
registerService(Context.HARDWARE_PROPERTIES_SERVICE, HardwarePropertiesManager.class, new CachedServiceFetcher<HardwarePropertiesManager>() { @Override public HardwarePropertiesManager createService(ContextImpl ctx) throws ServiceNotFoundException { IBinder b = ServiceManager.getServiceOrThrow(Context.HARDWARE_PROPERTIES_SERVICE); IHardwarePropertiesManager service = IHardwarePropertiesManager.Stub.asInterface(b); return new HardwarePropertiesManager(ctx, service); }})1030         registerService(Context.HARDWARE_PROPERTIES_SERVICE, HardwarePropertiesManager.class,
1031                 new CachedServiceFetcher<HardwarePropertiesManager>() {
1032             @Override
1033             public HardwarePropertiesManager createService(ContextImpl ctx) throws ServiceNotFoundException {
1034                 IBinder b = ServiceManager.getServiceOrThrow(Context.HARDWARE_PROPERTIES_SERVICE);
1035                 IHardwarePropertiesManager service =
1036                         IHardwarePropertiesManager.Stub.asInterface(b);
1037                 return new HardwarePropertiesManager(ctx, service);
1038             }});
1039 
registerService(Context.SOUND_TRIGGER_SERVICE, SoundTriggerManager.class, new CachedServiceFetcher<SoundTriggerManager>() { @Override public SoundTriggerManager createService(ContextImpl ctx) throws ServiceNotFoundException { IBinder b = ServiceManager.getServiceOrThrow(Context.SOUND_TRIGGER_SERVICE); return new SoundTriggerManager(ctx, ISoundTriggerService.Stub.asInterface(b)); }})1040         registerService(Context.SOUND_TRIGGER_SERVICE, SoundTriggerManager.class,
1041                 new CachedServiceFetcher<SoundTriggerManager>() {
1042             @Override
1043             public SoundTriggerManager createService(ContextImpl ctx) throws ServiceNotFoundException {
1044                 IBinder b = ServiceManager.getServiceOrThrow(Context.SOUND_TRIGGER_SERVICE);
1045                 return new SoundTriggerManager(ctx, ISoundTriggerService.Stub.asInterface(b));
1046             }});
1047 
registerService(Context.SHORTCUT_SERVICE, ShortcutManager.class, new CachedServiceFetcher<ShortcutManager>() { @Override public ShortcutManager createService(ContextImpl ctx) throws ServiceNotFoundException { IBinder b = ServiceManager.getServiceOrThrow(Context.SHORTCUT_SERVICE); return new ShortcutManager(ctx, IShortcutService.Stub.asInterface(b)); }})1048         registerService(Context.SHORTCUT_SERVICE, ShortcutManager.class,
1049                 new CachedServiceFetcher<ShortcutManager>() {
1050             @Override
1051             public ShortcutManager createService(ContextImpl ctx) throws ServiceNotFoundException {
1052                 IBinder b = ServiceManager.getServiceOrThrow(Context.SHORTCUT_SERVICE);
1053                 return new ShortcutManager(ctx, IShortcutService.Stub.asInterface(b));
1054             }});
1055 
registerService(Context.OVERLAY_SERVICE, OverlayManager.class, new CachedServiceFetcher<OverlayManager>() { @Override public OverlayManager createService(ContextImpl ctx) throws ServiceNotFoundException { IBinder b = ServiceManager.getServiceOrThrow(Context.OVERLAY_SERVICE); return new OverlayManager(ctx, IOverlayManager.Stub.asInterface(b)); }})1056         registerService(Context.OVERLAY_SERVICE, OverlayManager.class,
1057                 new CachedServiceFetcher<OverlayManager>() {
1058             @Override
1059             public OverlayManager createService(ContextImpl ctx) throws ServiceNotFoundException {
1060                 IBinder b = ServiceManager.getServiceOrThrow(Context.OVERLAY_SERVICE);
1061                 return new OverlayManager(ctx, IOverlayManager.Stub.asInterface(b));
1062             }});
1063 
registerService(Context.NETWORK_WATCHLIST_SERVICE, NetworkWatchlistManager.class, new CachedServiceFetcher<NetworkWatchlistManager>() { @Override public NetworkWatchlistManager createService(ContextImpl ctx) throws ServiceNotFoundException { IBinder b = ServiceManager.getServiceOrThrow(Context.NETWORK_WATCHLIST_SERVICE); return new NetworkWatchlistManager(ctx, INetworkWatchlistManager.Stub.asInterface(b)); }})1064         registerService(Context.NETWORK_WATCHLIST_SERVICE, NetworkWatchlistManager.class,
1065                 new CachedServiceFetcher<NetworkWatchlistManager>() {
1066                     @Override
1067                     public NetworkWatchlistManager createService(ContextImpl ctx)
1068                             throws ServiceNotFoundException {
1069                         IBinder b =
1070                                 ServiceManager.getServiceOrThrow(Context.NETWORK_WATCHLIST_SERVICE);
1071                         return new NetworkWatchlistManager(ctx,
1072                                 INetworkWatchlistManager.Stub.asInterface(b));
1073                     }});
1074 
registerService(Context.SYSTEM_HEALTH_SERVICE, SystemHealthManager.class, new CachedServiceFetcher<SystemHealthManager>() { @Override public SystemHealthManager createService(ContextImpl ctx) throws ServiceNotFoundException { IBinder b = ServiceManager.getServiceOrThrow(BatteryStats.SERVICE_NAME); return new SystemHealthManager(IBatteryStats.Stub.asInterface(b)); }})1075         registerService(Context.SYSTEM_HEALTH_SERVICE, SystemHealthManager.class,
1076                 new CachedServiceFetcher<SystemHealthManager>() {
1077             @Override
1078             public SystemHealthManager createService(ContextImpl ctx) throws ServiceNotFoundException {
1079                 IBinder b = ServiceManager.getServiceOrThrow(BatteryStats.SERVICE_NAME);
1080                 return new SystemHealthManager(IBatteryStats.Stub.asInterface(b));
1081             }});
1082 
registerService(Context.CONTEXTHUB_SERVICE, ContextHubManager.class, new CachedServiceFetcher<ContextHubManager>() { @Override public ContextHubManager createService(ContextImpl ctx) throws ServiceNotFoundException { return new ContextHubManager(ctx.getOuterContext(), ctx.mMainThread.getHandler().getLooper()); }})1083         registerService(Context.CONTEXTHUB_SERVICE, ContextHubManager.class,
1084                 new CachedServiceFetcher<ContextHubManager>() {
1085             @Override
1086             public ContextHubManager createService(ContextImpl ctx) throws ServiceNotFoundException {
1087                 return new ContextHubManager(ctx.getOuterContext(),
1088                   ctx.mMainThread.getHandler().getLooper());
1089             }});
1090 
registerService(Context.INCIDENT_SERVICE, IncidentManager.class, new CachedServiceFetcher<IncidentManager>() { @Override public IncidentManager createService(ContextImpl ctx) throws ServiceNotFoundException { return new IncidentManager(ctx); }})1091         registerService(Context.INCIDENT_SERVICE, IncidentManager.class,
1092                 new CachedServiceFetcher<IncidentManager>() {
1093             @Override
1094             public IncidentManager createService(ContextImpl ctx) throws ServiceNotFoundException {
1095                 return new IncidentManager(ctx);
1096             }});
1097 
registerService(Context.BUGREPORT_SERVICE, BugreportManager.class, new CachedServiceFetcher<BugreportManager>() { @Override public BugreportManager createService(ContextImpl ctx) throws ServiceNotFoundException { IBinder b = ServiceManager.getServiceOrThrow(Context.BUGREPORT_SERVICE); return new BugreportManager(ctx.getOuterContext(), IDumpstate.Stub.asInterface(b)); }})1098         registerService(Context.BUGREPORT_SERVICE, BugreportManager.class,
1099                 new CachedServiceFetcher<BugreportManager>() {
1100                     @Override
1101                     public BugreportManager createService(ContextImpl ctx)
1102                             throws ServiceNotFoundException {
1103                         IBinder b = ServiceManager.getServiceOrThrow(Context.BUGREPORT_SERVICE);
1104                         return new BugreportManager(ctx.getOuterContext(),
1105                                 IDumpstate.Stub.asInterface(b));
1106                     }});
1107 
registerService(Context.AUTOFILL_MANAGER_SERVICE, AutofillManager.class, new CachedServiceFetcher<AutofillManager>() { @Override public AutofillManager createService(ContextImpl ctx) throws ServiceNotFoundException { IBinder b = ServiceManager.getService(Context.AUTOFILL_MANAGER_SERVICE); IAutoFillManager service = IAutoFillManager.Stub.asInterface(b); return new AutofillManager(ctx.getOuterContext(), service); }})1108         registerService(Context.AUTOFILL_MANAGER_SERVICE, AutofillManager.class,
1109                 new CachedServiceFetcher<AutofillManager>() {
1110             @Override
1111             public AutofillManager createService(ContextImpl ctx) throws ServiceNotFoundException {
1112                 // Get the services without throwing as this is an optional feature
1113                 IBinder b = ServiceManager.getService(Context.AUTOFILL_MANAGER_SERVICE);
1114                 IAutoFillManager service = IAutoFillManager.Stub.asInterface(b);
1115                 return new AutofillManager(ctx.getOuterContext(), service);
1116             }});
1117 
registerService(Context.CONTENT_CAPTURE_MANAGER_SERVICE, ContentCaptureManager.class, new CachedServiceFetcher<ContentCaptureManager>() { @Override public ContentCaptureManager createService(ContextImpl ctx) throws ServiceNotFoundException { Context outerContext = ctx.getOuterContext(); ContentCaptureOptions options = outerContext.getContentCaptureOptions(); if (options != null && (options.lite || options.isWhitelisted(outerContext))) { IBinder b = ServiceManager .getService(Context.CONTENT_CAPTURE_MANAGER_SERVICE); IContentCaptureManager service = IContentCaptureManager.Stub.asInterface(b); if (service != null) { return new ContentCaptureManager(outerContext, service, options); } } return null; }})1118         registerService(Context.CONTENT_CAPTURE_MANAGER_SERVICE, ContentCaptureManager.class,
1119                 new CachedServiceFetcher<ContentCaptureManager>() {
1120             @Override
1121             public ContentCaptureManager createService(ContextImpl ctx)
1122                     throws ServiceNotFoundException {
1123                 // Get the services without throwing as this is an optional feature
1124                 Context outerContext = ctx.getOuterContext();
1125                 ContentCaptureOptions options = outerContext.getContentCaptureOptions();
1126                 // Options is null when the service didn't whitelist the activity or package
1127                 if (options != null && (options.lite || options.isWhitelisted(outerContext))) {
1128                     IBinder b = ServiceManager
1129                             .getService(Context.CONTENT_CAPTURE_MANAGER_SERVICE);
1130                     IContentCaptureManager service = IContentCaptureManager.Stub.asInterface(b);
1131                     // Service is null when not provided by OEM or disabled by kill-switch.
1132                     if (service != null) {
1133                         return new ContentCaptureManager(outerContext, service, options);
1134                     }
1135                 }
1136                 // When feature is disabled or app / package not whitelisted, we return a null
1137                 // manager to apps so the performance impact is practically zero
1138                 return null;
1139             }});
1140 
registerService(Context.APP_PREDICTION_SERVICE, AppPredictionManager.class, new CachedServiceFetcher<AppPredictionManager>() { @Override public AppPredictionManager createService(ContextImpl ctx) throws ServiceNotFoundException { IBinder b = ServiceManager.getService(Context.APP_PREDICTION_SERVICE); return b == null ? null : new AppPredictionManager(ctx); } })1141         registerService(Context.APP_PREDICTION_SERVICE, AppPredictionManager.class,
1142                 new CachedServiceFetcher<AppPredictionManager>() {
1143             @Override
1144             public AppPredictionManager createService(ContextImpl ctx)
1145                     throws ServiceNotFoundException {
1146                 IBinder b = ServiceManager.getService(Context.APP_PREDICTION_SERVICE);
1147                 return b == null ? null : new AppPredictionManager(ctx);
1148             }
1149         });
1150 
registerService(Context.CONTENT_SUGGESTIONS_SERVICE, ContentSuggestionsManager.class, new CachedServiceFetcher<ContentSuggestionsManager>() { @Override public ContentSuggestionsManager createService(ContextImpl ctx) { IBinder b = ServiceManager.getService( Context.CONTENT_SUGGESTIONS_SERVICE); IContentSuggestionsManager service = IContentSuggestionsManager.Stub.asInterface(b); return new ContentSuggestionsManager(ctx.getUserId(), service); } })1151         registerService(Context.CONTENT_SUGGESTIONS_SERVICE,
1152                 ContentSuggestionsManager.class,
1153                 new CachedServiceFetcher<ContentSuggestionsManager>() {
1154                     @Override
1155                     public ContentSuggestionsManager createService(ContextImpl ctx) {
1156                         // No throw as this is an optional service
1157                         IBinder b = ServiceManager.getService(
1158                                 Context.CONTENT_SUGGESTIONS_SERVICE);
1159                         IContentSuggestionsManager service =
1160                                 IContentSuggestionsManager.Stub.asInterface(b);
1161                         return new ContentSuggestionsManager(ctx.getUserId(), service);
1162                     }
1163                 });
1164 
registerService(Context.VR_SERVICE, VrManager.class, new CachedServiceFetcher<VrManager>() { @Override public VrManager createService(ContextImpl ctx) throws ServiceNotFoundException { IBinder b = ServiceManager.getServiceOrThrow(Context.VR_SERVICE); return new VrManager(IVrManager.Stub.asInterface(b)); } })1165         registerService(Context.VR_SERVICE, VrManager.class, new CachedServiceFetcher<VrManager>() {
1166             @Override
1167             public VrManager createService(ContextImpl ctx) throws ServiceNotFoundException {
1168                 IBinder b = ServiceManager.getServiceOrThrow(Context.VR_SERVICE);
1169                 return new VrManager(IVrManager.Stub.asInterface(b));
1170             }
1171         });
1172 
registerService(Context.TIME_ZONE_RULES_MANAGER_SERVICE, RulesManager.class, new CachedServiceFetcher<RulesManager>() { @Override public RulesManager createService(ContextImpl ctx) { return new RulesManager(ctx.getOuterContext()); }})1173         registerService(Context.TIME_ZONE_RULES_MANAGER_SERVICE, RulesManager.class,
1174                 new CachedServiceFetcher<RulesManager>() {
1175             @Override
1176             public RulesManager createService(ContextImpl ctx) {
1177                 return new RulesManager(ctx.getOuterContext());
1178             }});
1179 
registerService(Context.CROSS_PROFILE_APPS_SERVICE, CrossProfileApps.class, new CachedServiceFetcher<CrossProfileApps>() { @Override public CrossProfileApps createService(ContextImpl ctx) throws ServiceNotFoundException { IBinder b = ServiceManager.getServiceOrThrow( Context.CROSS_PROFILE_APPS_SERVICE); return new CrossProfileApps(ctx.getOuterContext(), ICrossProfileApps.Stub.asInterface(b)); } })1180         registerService(Context.CROSS_PROFILE_APPS_SERVICE, CrossProfileApps.class,
1181                 new CachedServiceFetcher<CrossProfileApps>() {
1182                     @Override
1183                     public CrossProfileApps createService(ContextImpl ctx)
1184                             throws ServiceNotFoundException {
1185                         IBinder b = ServiceManager.getServiceOrThrow(
1186                                 Context.CROSS_PROFILE_APPS_SERVICE);
1187                         return new CrossProfileApps(ctx.getOuterContext(),
1188                                 ICrossProfileApps.Stub.asInterface(b));
1189                     }
1190                 });
1191 
registerService(Context.SLICE_SERVICE, SliceManager.class, new CachedServiceFetcher<SliceManager>() { @Override public SliceManager createService(ContextImpl ctx) throws ServiceNotFoundException { return new SliceManager(ctx.getOuterContext(), ctx.mMainThread.getHandler()); } })1192         registerService(Context.SLICE_SERVICE, SliceManager.class,
1193                 new CachedServiceFetcher<SliceManager>() {
1194                     @Override
1195                     public SliceManager createService(ContextImpl ctx)
1196                             throws ServiceNotFoundException {
1197                         return new SliceManager(ctx.getOuterContext(),
1198                                 ctx.mMainThread.getHandler());
1199                     }
1200             });
1201 
registerService(Context.TIME_DETECTOR_SERVICE, TimeDetector.class, new CachedServiceFetcher<TimeDetector>() { @Override public TimeDetector createService(ContextImpl ctx) throws ServiceNotFoundException { return new TimeDetectorImpl(); }})1202         registerService(Context.TIME_DETECTOR_SERVICE, TimeDetector.class,
1203                 new CachedServiceFetcher<TimeDetector>() {
1204                     @Override
1205                     public TimeDetector createService(ContextImpl ctx)
1206                             throws ServiceNotFoundException {
1207                         return new TimeDetectorImpl();
1208                     }});
1209 
registerService(Context.TIME_ZONE_DETECTOR_SERVICE, TimeZoneDetector.class, new CachedServiceFetcher<TimeZoneDetector>() { @Override public TimeZoneDetector createService(ContextImpl ctx) throws ServiceNotFoundException { return new TimeZoneDetectorImpl(); }})1210         registerService(Context.TIME_ZONE_DETECTOR_SERVICE, TimeZoneDetector.class,
1211                 new CachedServiceFetcher<TimeZoneDetector>() {
1212                     @Override
1213                     public TimeZoneDetector createService(ContextImpl ctx)
1214                             throws ServiceNotFoundException {
1215                         return new TimeZoneDetectorImpl();
1216                     }});
1217 
registerService(Context.PERMISSION_SERVICE, PermissionManager.class, new CachedServiceFetcher<PermissionManager>() { @Override public PermissionManager createService(ContextImpl ctx) throws ServiceNotFoundException { IPackageManager packageManager = AppGlobals.getPackageManager(); return new PermissionManager(ctx.getOuterContext(), packageManager); }})1218         registerService(Context.PERMISSION_SERVICE, PermissionManager.class,
1219                 new CachedServiceFetcher<PermissionManager>() {
1220                     @Override
1221                     public PermissionManager createService(ContextImpl ctx)
1222                             throws ServiceNotFoundException {
1223                         IPackageManager packageManager = AppGlobals.getPackageManager();
1224                         return new PermissionManager(ctx.getOuterContext(), packageManager);
1225                     }});
1226 
registerService(Context.PERMISSION_CONTROLLER_SERVICE, PermissionControllerManager.class, new CachedServiceFetcher<PermissionControllerManager>() { @Override public PermissionControllerManager createService(ContextImpl ctx) { return new PermissionControllerManager(ctx.getOuterContext(), ctx.getMainThreadHandler()); }})1227         registerService(Context.PERMISSION_CONTROLLER_SERVICE, PermissionControllerManager.class,
1228                 new CachedServiceFetcher<PermissionControllerManager>() {
1229                     @Override
1230                     public PermissionControllerManager createService(ContextImpl ctx) {
1231                         return new PermissionControllerManager(ctx.getOuterContext(),
1232                                 ctx.getMainThreadHandler());
1233                     }});
1234 
registerService(Context.ROLE_SERVICE, RoleManager.class, new CachedServiceFetcher<RoleManager>() { @Override public RoleManager createService(ContextImpl ctx) throws ServiceNotFoundException { return new RoleManager(ctx.getOuterContext()); }})1235         registerService(Context.ROLE_SERVICE, RoleManager.class,
1236                 new CachedServiceFetcher<RoleManager>() {
1237                     @Override
1238                     public RoleManager createService(ContextImpl ctx)
1239                             throws ServiceNotFoundException {
1240                         return new RoleManager(ctx.getOuterContext());
1241                     }});
1242 
registerService(Context.ROLE_CONTROLLER_SERVICE, RoleControllerManager.class, new CachedServiceFetcher<RoleControllerManager>() { @Override public RoleControllerManager createService(ContextImpl ctx) throws ServiceNotFoundException { return new RoleControllerManager(ctx.getOuterContext()); }})1243         registerService(Context.ROLE_CONTROLLER_SERVICE, RoleControllerManager.class,
1244                 new CachedServiceFetcher<RoleControllerManager>() {
1245                     @Override
1246                     public RoleControllerManager createService(ContextImpl ctx)
1247                             throws ServiceNotFoundException {
1248                         return new RoleControllerManager(ctx.getOuterContext());
1249                     }});
1250 
registerService(Context.ROLLBACK_SERVICE, RollbackManager.class, new CachedServiceFetcher<RollbackManager>() { @Override public RollbackManager createService(ContextImpl ctx) throws ServiceNotFoundException { IBinder b = ServiceManager.getServiceOrThrow(Context.ROLLBACK_SERVICE); return new RollbackManager(ctx.getOuterContext(), IRollbackManager.Stub.asInterface(b)); }})1251         registerService(Context.ROLLBACK_SERVICE, RollbackManager.class,
1252                 new CachedServiceFetcher<RollbackManager>() {
1253                     @Override
1254                     public RollbackManager createService(ContextImpl ctx)
1255                             throws ServiceNotFoundException {
1256                         IBinder b = ServiceManager.getServiceOrThrow(Context.ROLLBACK_SERVICE);
1257                         return new RollbackManager(ctx.getOuterContext(),
1258                                 IRollbackManager.Stub.asInterface(b));
1259                     }});
1260 
registerService(Context.DYNAMIC_SYSTEM_SERVICE, DynamicSystemManager.class, new CachedServiceFetcher<DynamicSystemManager>() { @Override public DynamicSystemManager createService(ContextImpl ctx) throws ServiceNotFoundException { IBinder b = ServiceManager.getServiceOrThrow( Context.DYNAMIC_SYSTEM_SERVICE); return new DynamicSystemManager( IDynamicSystemService.Stub.asInterface(b)); }})1261         registerService(Context.DYNAMIC_SYSTEM_SERVICE, DynamicSystemManager.class,
1262                 new CachedServiceFetcher<DynamicSystemManager>() {
1263                     @Override
1264                     public DynamicSystemManager createService(ContextImpl ctx)
1265                             throws ServiceNotFoundException {
1266                         IBinder b = ServiceManager.getServiceOrThrow(
1267                                 Context.DYNAMIC_SYSTEM_SERVICE);
1268                         return new DynamicSystemManager(
1269                                 IDynamicSystemService.Stub.asInterface(b));
1270                     }});
1271 
registerService(Context.BATTERY_STATS_SERVICE, BatteryStatsManager.class, new CachedServiceFetcher<BatteryStatsManager>() { @Override public BatteryStatsManager createService(ContextImpl ctx) throws ServiceNotFoundException { IBinder b = ServiceManager.getServiceOrThrow( Context.BATTERY_STATS_SERVICE); return new BatteryStatsManager( IBatteryStats.Stub.asInterface(b)); }})1272         registerService(Context.BATTERY_STATS_SERVICE, BatteryStatsManager.class,
1273                 new CachedServiceFetcher<BatteryStatsManager>() {
1274                     @Override
1275                     public BatteryStatsManager createService(ContextImpl ctx)
1276                             throws ServiceNotFoundException {
1277                         IBinder b = ServiceManager.getServiceOrThrow(
1278                                 Context.BATTERY_STATS_SERVICE);
1279                         return new BatteryStatsManager(
1280                                 IBatteryStats.Stub.asInterface(b));
1281                     }});
registerService(Context.DATA_LOADER_MANAGER_SERVICE, DataLoaderManager.class, new CachedServiceFetcher<DataLoaderManager>() { @Override public DataLoaderManager createService(ContextImpl ctx) throws ServiceNotFoundException { IBinder b = ServiceManager.getServiceOrThrow( Context.DATA_LOADER_MANAGER_SERVICE); return new DataLoaderManager(IDataLoaderManager.Stub.asInterface(b)); }})1282         registerService(Context.DATA_LOADER_MANAGER_SERVICE, DataLoaderManager.class,
1283                 new CachedServiceFetcher<DataLoaderManager>() {
1284                     @Override
1285                     public DataLoaderManager createService(ContextImpl ctx)
1286                             throws ServiceNotFoundException {
1287                         IBinder b = ServiceManager.getServiceOrThrow(
1288                                 Context.DATA_LOADER_MANAGER_SERVICE);
1289                         return new DataLoaderManager(IDataLoaderManager.Stub.asInterface(b));
1290                     }});
registerService(Context.LIGHTS_SERVICE, LightsManager.class, new CachedServiceFetcher<LightsManager>() { @Override public LightsManager createService(ContextImpl ctx) throws ServiceNotFoundException { return new LightsManager(ctx); }})1291         registerService(Context.LIGHTS_SERVICE, LightsManager.class,
1292             new CachedServiceFetcher<LightsManager>() {
1293                 @Override
1294                 public LightsManager createService(ContextImpl ctx)
1295                     throws ServiceNotFoundException {
1296                     return new LightsManager(ctx);
1297                 }});
registerService(Context.INCREMENTAL_SERVICE, IncrementalManager.class, new CachedServiceFetcher<IncrementalManager>() { @Override public IncrementalManager createService(ContextImpl ctx) { IBinder b = ServiceManager.getService(Context.INCREMENTAL_SERVICE); if (b == null) { return null; } return new IncrementalManager( IIncrementalService.Stub.asInterface(b)); }})1298         registerService(Context.INCREMENTAL_SERVICE, IncrementalManager.class,
1299                 new CachedServiceFetcher<IncrementalManager>() {
1300                     @Override
1301                     public IncrementalManager createService(ContextImpl ctx) {
1302                         IBinder b = ServiceManager.getService(Context.INCREMENTAL_SERVICE);
1303                         if (b == null) {
1304                             return null;
1305                         }
1306                         return new IncrementalManager(
1307                                 IIncrementalService.Stub.asInterface(b));
1308                     }});
1309 
registerService(Context.FILE_INTEGRITY_SERVICE, FileIntegrityManager.class, new CachedServiceFetcher<FileIntegrityManager>() { @Override public FileIntegrityManager createService(ContextImpl ctx) throws ServiceNotFoundException { IBinder b = ServiceManager.getServiceOrThrow( Context.FILE_INTEGRITY_SERVICE); return new FileIntegrityManager(ctx.getOuterContext(), IFileIntegrityService.Stub.asInterface(b)); }})1310         registerService(Context.FILE_INTEGRITY_SERVICE, FileIntegrityManager.class,
1311                 new CachedServiceFetcher<FileIntegrityManager>() {
1312                     @Override
1313                     public FileIntegrityManager createService(ContextImpl ctx)
1314                             throws ServiceNotFoundException {
1315                         IBinder b = ServiceManager.getServiceOrThrow(
1316                                 Context.FILE_INTEGRITY_SERVICE);
1317                         return new FileIntegrityManager(ctx.getOuterContext(),
1318                                 IFileIntegrityService.Stub.asInterface(b));
1319                     }});
1320         //CHECKSTYLE:ON IndentationCheck
registerService(Context.APP_INTEGRITY_SERVICE, AppIntegrityManager.class, new CachedServiceFetcher<AppIntegrityManager>() { @Override public AppIntegrityManager createService(ContextImpl ctx) throws ServiceNotFoundException { IBinder b = ServiceManager.getServiceOrThrow(Context.APP_INTEGRITY_SERVICE); return new AppIntegrityManager(IAppIntegrityManager.Stub.asInterface(b)); }})1321         registerService(Context.APP_INTEGRITY_SERVICE, AppIntegrityManager.class,
1322                 new CachedServiceFetcher<AppIntegrityManager>() {
1323                     @Override
1324                     public AppIntegrityManager createService(ContextImpl ctx)
1325                             throws ServiceNotFoundException {
1326                         IBinder b = ServiceManager.getServiceOrThrow(Context.APP_INTEGRITY_SERVICE);
1327                         return new AppIntegrityManager(IAppIntegrityManager.Stub.asInterface(b));
1328                     }});
registerService(Context.DREAM_SERVICE, DreamManager.class, new CachedServiceFetcher<DreamManager>() { @Override public DreamManager createService(ContextImpl ctx) throws ServiceNotFoundException { return new DreamManager(ctx); }})1329         registerService(Context.DREAM_SERVICE, DreamManager.class,
1330                 new CachedServiceFetcher<DreamManager>() {
1331                     @Override
1332                     public DreamManager createService(ContextImpl ctx)
1333                             throws ServiceNotFoundException {
1334                         return new DreamManager(ctx);
1335                     }});
1336 
1337         sInitializing = true;
1338         try {
1339             // Note: the following functions need to be @SystemApis, once they become mainline
1340             // modules.
JobSchedulerFrameworkInitializer.registerServiceWrappers()1341             JobSchedulerFrameworkInitializer.registerServiceWrappers();
BlobStoreManagerFrameworkInitializer.initialize()1342             BlobStoreManagerFrameworkInitializer.initialize();
TelephonyFrameworkInitializer.registerServiceWrappers()1343             TelephonyFrameworkInitializer.registerServiceWrappers();
WifiFrameworkInitializer.registerServiceWrappers()1344             WifiFrameworkInitializer.registerServiceWrappers();
StatsFrameworkInitializer.registerServiceWrappers()1345             StatsFrameworkInitializer.registerServiceWrappers();
1346         } finally {
1347             // If any of the above code throws, we're in a pretty bad shape and the process
1348             // will likely crash, but we'll reset it just in case there's an exception handler...
1349             sInitializing = false;
1350         }
1351     }
1352 
1353     /** Throws {@link IllegalStateException} if not during a static initialization. */
ensureInitializing(String methodName)1354     private static void ensureInitializing(String methodName) {
1355         Preconditions.checkState(sInitializing, "Internal error: " + methodName
1356                 + " can only be called during class initialization.");
1357     }
1358     /**
1359      * Creates an array which is used to cache per-Context service instances.
1360      * @hide
1361      */
createServiceCache()1362     public static Object[] createServiceCache() {
1363         return new Object[sServiceCacheSize];
1364     }
1365 
1366     /**
1367      * Gets a system service from a given context.
1368      * @hide
1369      */
getSystemService(ContextImpl ctx, String name)1370     public static Object getSystemService(ContextImpl ctx, String name) {
1371         if (name == null) {
1372             return null;
1373         }
1374         final ServiceFetcher<?> fetcher = SYSTEM_SERVICE_FETCHERS.get(name);
1375         if (fetcher == null) {
1376             if (sEnableServiceNotFoundWtf) {
1377                 Slog.wtf(TAG, "Unknown manager requested: " + name);
1378             }
1379             return null;
1380         }
1381 
1382         final Object ret = fetcher.getService(ctx);
1383         if (sEnableServiceNotFoundWtf && ret == null) {
1384             // Some services do return null in certain situations, so don't do WTF for them.
1385             switch (name) {
1386                 case Context.CONTENT_CAPTURE_MANAGER_SERVICE:
1387                 case Context.APP_PREDICTION_SERVICE:
1388                 case Context.INCREMENTAL_SERVICE:
1389                     return null;
1390             }
1391             Slog.wtf(TAG, "Manager wrapper not available: " + name);
1392             return null;
1393         }
1394         return ret;
1395     }
1396 
1397     /**
1398      * Gets the name of the system-level service that is represented by the specified class.
1399      * @hide
1400      */
getSystemServiceName(Class<?> serviceClass)1401     public static String getSystemServiceName(Class<?> serviceClass) {
1402         if (serviceClass == null) {
1403             return null;
1404         }
1405         final String serviceName = SYSTEM_SERVICE_NAMES.get(serviceClass);
1406         if (sEnableServiceNotFoundWtf && serviceName == null) {
1407             // This should be a caller bug.
1408             Slog.wtf(TAG, "Unknown manager requested: " + serviceClass.getCanonicalName());
1409         }
1410         return serviceName;
1411     }
1412 
1413     /**
1414      * Statically registers a system service with the context.
1415      * This method must be called during static initialization only.
1416      */
registerService(@onNull String serviceName, @NonNull Class<T> serviceClass, @NonNull ServiceFetcher<T> serviceFetcher)1417     private static <T> void registerService(@NonNull String serviceName,
1418             @NonNull Class<T> serviceClass, @NonNull ServiceFetcher<T> serviceFetcher) {
1419         SYSTEM_SERVICE_NAMES.put(serviceClass, serviceName);
1420         SYSTEM_SERVICE_FETCHERS.put(serviceName, serviceFetcher);
1421         SYSTEM_SERVICE_CLASS_NAMES.put(serviceName, serviceClass.getSimpleName());
1422     }
1423 
1424     /**
1425      * Returns system service class name by system service name. This method is mostly an inverse of
1426      * {@link #getSystemServiceName(Class)}
1427      *
1428      * @return system service class name. {@code null} if service name is invalid.
1429      * @hide
1430      */
1431     @Nullable
getSystemServiceClassName(@onNull String name)1432     public static String getSystemServiceClassName(@NonNull String name) {
1433         return SYSTEM_SERVICE_CLASS_NAMES.get(name);
1434     }
1435 
1436     /**
1437      * Callback interface used as a parameter to {@link #registerStaticService(
1438      * String, Class, StaticServiceProducerWithoutBinder)}, which generates a service wrapper
1439      * instance that's not tied to any context and does not take a service binder object in the
1440      * constructor.
1441      *
1442      * @param <TServiceClass> type of the service wrapper class.
1443      *
1444      * @hide
1445      */
1446     @SystemApi
1447     public interface StaticServiceProducerWithoutBinder<TServiceClass> {
1448         /**
1449          * Return a new service wrapper of type {@code TServiceClass}.
1450          */
1451         @NonNull
createService()1452         TServiceClass createService();
1453     }
1454 
1455     /**
1456      * Callback interface used as a parameter to {@link #registerStaticService(
1457      * String, Class, StaticServiceProducerWithBinder)}, which generates a service wrapper instance
1458      * that's not tied to any context and takes a service binder object in the constructor.
1459      *
1460      * @param <TServiceClass> type of the service wrapper class.
1461      *
1462      * @hide
1463      */
1464     @SystemApi
1465     public interface StaticServiceProducerWithBinder<TServiceClass> {
1466         /**
1467          * Return a new service wrapper of type {@code TServiceClass} backed by a given
1468          * service binder object.
1469          */
1470         @NonNull
createService(@onNull IBinder serviceBinder)1471         TServiceClass createService(@NonNull IBinder serviceBinder);
1472     }
1473 
1474     /**
1475      * Callback interface used as a parameter to {@link #registerContextAwareService(
1476      * String, Class, ContextAwareServiceProducerWithoutBinder)},
1477      * which generates a service wrapper instance
1478      * that's tied to a specific context and does not take a service binder object in the
1479      * constructor.
1480      *
1481      * @param <TServiceClass> type of the service wrapper class.
1482      *
1483      * @hide
1484      */
1485     @SystemApi
1486     public interface ContextAwareServiceProducerWithoutBinder<TServiceClass> {
1487         /**
1488          * Return a new service wrapper of type {@code TServiceClass} tied to a given
1489          * {@code context}.
1490          */
1491         @NonNull
1492         //TODO Do we need to pass the "base context" too?
createService(@onNull Context context)1493         TServiceClass createService(@NonNull Context context);
1494     }
1495 
1496     /**
1497      * Callback interface used as a parameter to {@link #registerContextAwareService(
1498      * String, Class, ContextAwareServiceProducerWithBinder)},
1499      * which generates a service wrapper instance
1500      * that's tied to a specific context and takes a service binder object in the constructor.
1501      *
1502      * @param <TServiceClass> type of the service wrapper class.
1503      *
1504      * @hide
1505      */
1506     @SystemApi
1507     public interface ContextAwareServiceProducerWithBinder<TServiceClass> {
1508         /**
1509          * Return a new service wrapper of type {@code TServiceClass} backed by a given
1510          * service binder object that's tied to a given {@code context}.
1511          */
1512         @NonNull
1513         //TODO Do we need to pass the "base context" too?
createService(@onNull Context context, @NonNull IBinder serviceBinder)1514         TServiceClass createService(@NonNull Context context, @NonNull IBinder serviceBinder);
1515     }
1516 
1517     /**
1518      * Used by apex modules to register a "service wrapper" that is not tied to any {@link Context}.
1519      *
1520      * <p>This can only be called from the methods called by the static initializer of
1521      * {@link SystemServiceRegistry}. (Otherwise it throws a {@link IllegalStateException}.)
1522      *
1523      * @param serviceName the name of the binder object, such as
1524      *     {@link Context#JOB_SCHEDULER_SERVICE}.
1525      * @param serviceWrapperClass the wrapper class, such as the class of
1526      *     {@link android.app.job.JobScheduler}.
1527      * @param serviceProducer Callback that takes the service binder object with the name
1528      *     {@code serviceName} and returns an actual service wrapper instance.
1529      *
1530      * @hide
1531      */
1532     @SystemApi
registerStaticService( @onNull String serviceName, @NonNull Class<TServiceClass> serviceWrapperClass, @NonNull StaticServiceProducerWithBinder<TServiceClass> serviceProducer)1533     public static <TServiceClass> void registerStaticService(
1534             @NonNull String serviceName, @NonNull Class<TServiceClass> serviceWrapperClass,
1535             @NonNull StaticServiceProducerWithBinder<TServiceClass> serviceProducer) {
1536         ensureInitializing("registerStaticService");
1537         Preconditions.checkStringNotEmpty(serviceName);
1538         Objects.requireNonNull(serviceWrapperClass);
1539         Objects.requireNonNull(serviceProducer);
1540 
1541         registerService(serviceName, serviceWrapperClass,
1542                 new StaticServiceFetcher<TServiceClass>() {
1543                     @Override
1544                     public TServiceClass createService() throws ServiceNotFoundException {
1545                         return serviceProducer.createService(
1546                                 ServiceManager.getServiceOrThrow(serviceName));
1547                     }});
1548     }
1549 
1550     /**
1551      * Similar to {@link #registerStaticService(String, Class, StaticServiceProducerWithBinder)},
1552      * but used for a "service wrapper" that doesn't take a service binder in its constructor.
1553      *
1554      * @hide
1555      */
1556     @SystemApi
registerStaticService( @onNull String serviceName, @NonNull Class<TServiceClass> serviceWrapperClass, @NonNull StaticServiceProducerWithoutBinder<TServiceClass> serviceProducer)1557     public static <TServiceClass> void registerStaticService(
1558             @NonNull String serviceName, @NonNull Class<TServiceClass> serviceWrapperClass,
1559             @NonNull StaticServiceProducerWithoutBinder<TServiceClass> serviceProducer) {
1560         ensureInitializing("registerStaticService");
1561         Preconditions.checkStringNotEmpty(serviceName);
1562         Objects.requireNonNull(serviceWrapperClass);
1563         Objects.requireNonNull(serviceProducer);
1564 
1565         registerService(serviceName, serviceWrapperClass,
1566                 new StaticServiceFetcher<TServiceClass>() {
1567                     @Override
1568                     public TServiceClass createService() {
1569                         return serviceProducer.createService();
1570                     }});
1571     }
1572 
1573     /**
1574      * Used by apex modules to register a "service wrapper" that is tied to a specific
1575      * {@link Context}.
1576      *
1577      * <p>This can only be called from the methods called by the static initializer of
1578      * {@link SystemServiceRegistry}. (Otherwise it throws a {@link IllegalStateException}.)
1579      *
1580      * @param serviceName the name of the binder object, such as
1581      *     {@link Context#JOB_SCHEDULER_SERVICE}.
1582      * @param serviceWrapperClass the wrapper class, such as the class of
1583      *     {@link android.app.job.JobScheduler}.
1584      * @param serviceProducer lambda that takes the service binder object with the name
1585      *     {@code serviceName}, a {@link Context} and returns an actual service wrapper instance.
1586      *
1587      * @hide
1588      */
1589     @SystemApi
registerContextAwareService( @onNull String serviceName, @NonNull Class<TServiceClass> serviceWrapperClass, @NonNull ContextAwareServiceProducerWithBinder<TServiceClass> serviceProducer)1590     public static <TServiceClass> void registerContextAwareService(
1591             @NonNull String serviceName, @NonNull Class<TServiceClass> serviceWrapperClass,
1592             @NonNull ContextAwareServiceProducerWithBinder<TServiceClass> serviceProducer) {
1593         ensureInitializing("registerContextAwareService");
1594         Preconditions.checkStringNotEmpty(serviceName);
1595         Objects.requireNonNull(serviceWrapperClass);
1596         Objects.requireNonNull(serviceProducer);
1597 
1598         registerService(serviceName, serviceWrapperClass,
1599                 new CachedServiceFetcher<TServiceClass>() {
1600                     @Override
1601                     public TServiceClass createService(ContextImpl ctx)
1602                             throws ServiceNotFoundException {
1603                         return serviceProducer.createService(
1604                                 ctx.getOuterContext(),
1605                                 ServiceManager.getServiceOrThrow(serviceName));
1606                     }});
1607     }
1608 
1609 
1610     /**
1611      * Similar to {@link #registerContextAwareService(String, Class,
1612      * ContextAwareServiceProducerWithBinder)},
1613      * but used for a "service wrapper" that doesn't take a service binder in its constructor.
1614      *
1615      * @hide
1616      */
1617     @SystemApi
registerContextAwareService( @onNull String serviceName, @NonNull Class<TServiceClass> serviceWrapperClass, @NonNull ContextAwareServiceProducerWithoutBinder<TServiceClass> serviceProducer)1618     public static <TServiceClass> void registerContextAwareService(
1619             @NonNull String serviceName, @NonNull Class<TServiceClass> serviceWrapperClass,
1620             @NonNull ContextAwareServiceProducerWithoutBinder<TServiceClass> serviceProducer) {
1621         ensureInitializing("registerContextAwareService");
1622         Preconditions.checkStringNotEmpty(serviceName);
1623         Objects.requireNonNull(serviceWrapperClass);
1624         Objects.requireNonNull(serviceProducer);
1625 
1626         registerService(serviceName, serviceWrapperClass,
1627                 new CachedServiceFetcher<TServiceClass>() {
1628                     @Override
1629                     public TServiceClass createService(ContextImpl ctx) {
1630                         return serviceProducer.createService(ctx.getOuterContext());
1631                     }});
1632     }
1633 
1634     /**
1635      * Base interface for classes that fetch services.
1636      * These objects must only be created during static initialization.
1637      */
1638     static abstract interface ServiceFetcher<T> {
getService(ContextImpl ctx)1639         T getService(ContextImpl ctx);
1640     }
1641 
1642     /**
1643      * Override this class when the system service constructor needs a
1644      * ContextImpl and should be cached and retained by that context.
1645      */
1646     static abstract class CachedServiceFetcher<T> implements ServiceFetcher<T> {
1647         private final int mCacheIndex;
1648 
CachedServiceFetcher()1649         CachedServiceFetcher() {
1650             // Note this class must be instantiated only by the static initializer of the
1651             // outer class (SystemServiceRegistry), which already does the synchronization,
1652             // so bare access to sServiceCacheSize is okay here.
1653             mCacheIndex = sServiceCacheSize++;
1654         }
1655 
1656         @Override
1657         @SuppressWarnings("unchecked")
getService(ContextImpl ctx)1658         public final T getService(ContextImpl ctx) {
1659             final Object[] cache = ctx.mServiceCache;
1660             final int[] gates = ctx.mServiceInitializationStateArray;
1661             boolean interrupted = false;
1662 
1663             T ret = null;
1664 
1665             for (;;) {
1666                 boolean doInitialize = false;
1667                 synchronized (cache) {
1668                     // Return it if we already have a cached instance.
1669                     T service = (T) cache[mCacheIndex];
1670                     if (service != null || gates[mCacheIndex] == ContextImpl.STATE_NOT_FOUND) {
1671                         ret = service;
1672                         break; // exit the for (;;)
1673                     }
1674 
1675                     // If we get here, there's no cached instance.
1676 
1677                     // Grr... if gate is STATE_READY, then this means we initialized the service
1678                     // once but someone cleared it.
1679                     // We start over from STATE_UNINITIALIZED.
1680                     if (gates[mCacheIndex] == ContextImpl.STATE_READY) {
1681                         gates[mCacheIndex] = ContextImpl.STATE_UNINITIALIZED;
1682                     }
1683 
1684                     // It's possible for multiple threads to get here at the same time, so
1685                     // use the "gate" to make sure only the first thread will call createService().
1686 
1687                     // At this point, the gate must be either UNINITIALIZED or INITIALIZING.
1688                     if (gates[mCacheIndex] == ContextImpl.STATE_UNINITIALIZED) {
1689                         doInitialize = true;
1690                         gates[mCacheIndex] = ContextImpl.STATE_INITIALIZING;
1691                     }
1692                 }
1693 
1694                 if (doInitialize) {
1695                     // Only the first thread gets here.
1696 
1697                     T service = null;
1698                     @ServiceInitializationState int newState = ContextImpl.STATE_NOT_FOUND;
1699                     try {
1700                         // This thread is the first one to get here. Instantiate the service
1701                         // *without* the cache lock held.
1702                         service = createService(ctx);
1703                         newState = ContextImpl.STATE_READY;
1704 
1705                     } catch (ServiceNotFoundException e) {
1706                         onServiceNotFound(e);
1707 
1708                     } finally {
1709                         synchronized (cache) {
1710                             cache[mCacheIndex] = service;
1711                             gates[mCacheIndex] = newState;
1712                             cache.notifyAll();
1713                         }
1714                     }
1715                     ret = service;
1716                     break; // exit the for (;;)
1717                 }
1718                 // The other threads will wait for the first thread to call notifyAll(),
1719                 // and go back to the top and retry.
1720                 synchronized (cache) {
1721                     // Repeat until the state becomes STATE_READY or STATE_NOT_FOUND.
1722                     // We can't respond to interrupts here; just like we can't in the "doInitialize"
1723                     // path, so we remember the interrupt state here and re-interrupt later.
1724                     while (gates[mCacheIndex] < ContextImpl.STATE_READY) {
1725                         try {
1726                             // Clear the interrupt state.
1727                             interrupted |= Thread.interrupted();
1728                             cache.wait();
1729                         } catch (InterruptedException e) {
1730                             // This shouldn't normally happen, but if someone interrupts the
1731                             // thread, it will.
1732                             Slog.w(TAG, "getService() interrupted");
1733                             interrupted = true;
1734                         }
1735                     }
1736                 }
1737             }
1738             if (interrupted) {
1739                 Thread.currentThread().interrupt();
1740             }
1741             return ret;
1742         }
1743 
createService(ContextImpl ctx)1744         public abstract T createService(ContextImpl ctx) throws ServiceNotFoundException;
1745     }
1746 
1747     /**
1748      * Override this class when the system service does not need a ContextImpl
1749      * and should be cached and retained process-wide.
1750      */
1751     static abstract class StaticServiceFetcher<T> implements ServiceFetcher<T> {
1752         private T mCachedInstance;
1753 
1754         @Override
getService(ContextImpl ctx)1755         public final T getService(ContextImpl ctx) {
1756             synchronized (StaticServiceFetcher.this) {
1757                 if (mCachedInstance == null) {
1758                     try {
1759                         mCachedInstance = createService();
1760                     } catch (ServiceNotFoundException e) {
1761                         onServiceNotFound(e);
1762                     }
1763                 }
1764                 return mCachedInstance;
1765             }
1766         }
1767 
createService()1768         public abstract T createService() throws ServiceNotFoundException;
1769     }
1770 
1771     /**
1772      * Like StaticServiceFetcher, creates only one instance of the service per application, but when
1773      * creating the service for the first time, passes it the application context of the creating
1774      * application.
1775      *
1776      * TODO: Delete this once its only user (ConnectivityManager) is known to work well in the
1777      * case where multiple application components each have their own ConnectivityManager object.
1778      */
1779     static abstract class StaticApplicationContextServiceFetcher<T> implements ServiceFetcher<T> {
1780         private T mCachedInstance;
1781 
1782         @Override
getService(ContextImpl ctx)1783         public final T getService(ContextImpl ctx) {
1784             synchronized (StaticApplicationContextServiceFetcher.this) {
1785                 if (mCachedInstance == null) {
1786                     Context appContext = ctx.getApplicationContext();
1787                     // If the application context is null, we're either in the system process or
1788                     // it's the application context very early in app initialization. In both these
1789                     // cases, the passed-in ContextImpl will not be freed, so it's safe to pass it
1790                     // to the service. http://b/27532714 .
1791                     try {
1792                         mCachedInstance = createService(appContext != null ? appContext : ctx);
1793                     } catch (ServiceNotFoundException e) {
1794                         onServiceNotFound(e);
1795                     }
1796                 }
1797                 return mCachedInstance;
1798             }
1799         }
1800 
createService(Context applicationContext)1801         public abstract T createService(Context applicationContext) throws ServiceNotFoundException;
1802     }
1803 
1804     /** @hide */
onServiceNotFound(ServiceNotFoundException e)1805     public static void onServiceNotFound(ServiceNotFoundException e) {
1806         // We're mostly interested in tracking down long-lived core system
1807         // components that might stumble if they obtain bad references; just
1808         // emit a tidy log message for normal apps
1809         if (android.os.Process.myUid() < android.os.Process.FIRST_APPLICATION_UID) {
1810             Log.wtf(TAG, e.getMessage(), e);
1811         } else {
1812             Log.w(TAG, e.getMessage());
1813         }
1814     }
1815 }
1816