单例模式以及在android中的使用

一、原理

程序中某个对象可能比较消耗内存或者创建多个对象实例会引起运行错乱,此时就要求程序中只有一个该对象的实例,也就是单例模式的由来。为了防止开发者创建多个实例,一般会将单例类的构造器设为私有(private),这样你在其它地方去new单例类会失败;然后创建一个该单例类的静态方法去初始化实例对象并返回实例对象,当然实例对象也要是private static的,这样就必须通过静态方法获取该类的实例对象了。考虑到创建对象的过程并不是原子的,也要兼顾多线程安全问题。

二、分类

有多种构建单例的方式,它们都有优缺点和适用场景,下面来列举一下:

2.1 懒汉式

public class LazySingleton {
    private static LazySingleton  mInstance; //实例变量设置私有,防止直接通过类名访问

    private LazySingleton() { //默认构造函数私有,防止类外直接new创建对象
    }

    public static synchronized LazySingleton getInstance() { //静态同步方法作为唯一的实例对象获取方式
        if (mInstance==null) {
            mInstance = new LazySingleton();
        }
        return mInstance;
    }
}

线程安全的懒汉式单例模式的同步锁可以很好的解决多线程问题,并且在访问静态方法时才去创建对象,做到了按需分配,可以在一定程度上节省资源消耗;其实仅在对象第一次初始化时需要保证同步,后面每次访问都去同步就会导致不必要的性能消耗了。

2.2 饿汉式

public class HungrySingleton {
    private static HungrySingleton mInstance = new HungrySingleton();//程序启动时立即创建单例

    private HungrySingleton() {//构造函数私有
    }

    public static HungrySingleton getInstance() {//唯一的访问入口
        return mInstance;
    }
}

由于饿汉式单例模式在程序启动时就去初始化单例变量,等到后面程序其它地方调用静态方法时,单例对象已经初始化完成,所以不存在多线程问题。但是,一上来就去创建对象会消耗系统资源。

2.3 改进的DCL

public class DclSingleton {
    private volatile static DclSingleton  mInstance; //实例变量设置私有,防止直接通过类名访问,volatile禁止指令重排序以及及时通知多线程

    private DclSingleton() { //默认构造函数私有,防止类外直接new创建对象
    }

    public static DclSingleton getInstance() { //唯一的访问入口,访问时才创建对象
        if (mInstance == null) {
            synchronized (DclSingleton.class){
                if (mInstance == null) { //双重检查
                    mInstance = new DclSingleton();
                }
            }
        }
        return mInstance;
    }
}

DCL单例模式可以按需创建对象,第一层判空是为了避免不必要的同步,第二层为空才去创建实例。同时volatile关键字的使用可以保证单例变量的可见性以及禁止指令排序(需要注意的是jdk1.5以后volatile关键字才有这个效果)。

2.4 静态内部类

public class InnerSingleton {
    private InnerSingleton() { //默认构造函数私有,防止类外直接new创建对象
    }
    public static InnerSingleton getInstance() {
        return SingletonHolder.mInstance;
    }
    private static class SingletonHolder {
        private static final InnerSingleton mInstance =  new InnerSingleton();
    }
}

首次加载InnerSingleton类的时候不会加载静态内部类,也就不会初始化mInstance,只有在调用getInstance()方法才会加载SingletonHolder类并初始化mInstance,由于类的初始化期间,JVM会自动获取锁,所以这里不用手动加锁也能保证线程安全。

2.5 枚举

public enum EnumSingleton {
    INSTANCE;
    public void doTest() {

    }
}

默认枚举实例的创建是线程安全的,并且在反序列化时也可以保证是同一个对象。

2.6 容器

public class SingletonManager {
    private static Map<String,Object> objMap = new HashMap<>();

    private SingletonManager() {
    }

    public static void registerService(String key,Object instance) {
        if (!objMap.containsKey(key)) {
            objMap.put(key,instance);
        }
    }

    public static Object getService(String key) {
        return objMap.get(key);
    }
}

该方式类似注册表,将多个单例对象注册到统一的管理类里面,在使用的时候根据key从集合中去取出对应的对象实例,典型代表是android中的getSystemService。

三、android中单例模式的使用

3.1 getSystemService

在2.6中提到了容器单例模式,比较常见的系统服务都是通过这种方式注册,然后应用层通过getSystemService去获取。
新建一个MainActivity中调用下面跟踪一下下面代码

getSystemService(Context.ACCESSIBILITY_SERVICE)

3.1.1 Activiyty.getSystemService

上面代码会调用父类Activiyty.java的getSystemService方法,该方法里面判断不是WINDOW_SERVICE以及SEARCH_SERVICE就去调用父类的getSystemService方法,我们知道Activiyty.java继承ContextThemeWrapper.java,那么就是调用ContextThemeWrapper的getSystemService方法.

//Activiyty.java
@Override
public Object getSystemService(@ServiceName @NonNull String name) {
    if (getBaseContext() == null) {
        throw new IllegalStateException(
                "System services not available to Activities before onCreate()");
    }

    if (WINDOW_SERVICE.equals(name)) {
        return mWindowManager;
    } else if (SEARCH_SERVICE.equals(name)) {
        ensureSearchManager();
        return mSearchManager;
    }
    return super.getSystemService(name);
}

3.1.2 ContextThemeWrapper.getSystemService
ContextThemeWrapper的getSystemService方法发现不是LAYOUT_INFLATER_SERVICE的话就会调用getBaseContext()的getSystemService方法。从startService过程 以及从startActivity说起 可以得知getBaseContext()的实现是ContextImpl.java。

//ContextThemeWrapper.java
public Object getSystemService(String name) {
    if (LAYOUT_INFLATER_SERVICE.equals(name)) {
        if (mInflater == null) {
            mInflater = LayoutInflater.from(getBaseContext()).cloneInContext(this);
        }
        return mInflater;
    }
    return getBaseContext().getSystemService(name);
}

3.1.3 ContextImpl.getSystemService
ContextImpl.getSystemService调用了SystemServiceRegistry的getSystemService方法

//ContextImpl.java
public Object getSystemService(String name) {
    if (vmIncorrectContextUseEnabled()) {
        // We may override this API from outer context.
        final boolean isUiContext = isUiContext() || isOuterUiContext();
        // Check incorrect Context usage.
        if (isUiComponent(name) && !isUiContext) {
            final String errorMessage = "Tried to access visual service "
                    + SystemServiceRegistry.getSystemServiceClassName(name)
                    + " from a non-visual Context:" + getOuterContext();
            final String message = "Visual services, such as WindowManager, WallpaperService "
                    + "or LayoutInflater should be accessed from Activity or other visual "
                    + "Context. Use an Activity or a Context created with "
                    + "Context#createWindowContext(int, Bundle), which are adjusted to "
                    + "the configuration and visual bounds of an area on screen.";
            final Exception exception = new IllegalAccessException(errorMessage);
            StrictMode.onIncorrectContextUsed(message, exception);
            Log.e(TAG, errorMessage + " " + message, exception);
        }
    }
    return SystemServiceRegistry.getSystemService(this, name);
}

3.1.4 SystemServiceRegistry.getSystemService
SystemServiceRegistry.getSystemService从SYSTEM_SERVICE_FETCHERS 集合中根据传入的key的名称取出ServiceFetcher,然后从ServiceFetcher取出服务,那么SYSTEM_SERVICE_FETCHERS是什么时候注册的呢?

//SystemServiceRegistry.java
private static final Map<String, ServiceFetcher<?>> SYSTEM_SERVICE_FETCHERS =
        new ArrayMap<String, ServiceFetcher<?>>();
public static Object getSystemService(ContextImpl ctx, String name) {
    if (name == null) {
        return null;
    }
    final ServiceFetcher<?> fetcher = SYSTEM_SERVICE_FETCHERS.get(name); //从集合中取出key对应的fetcher 
    if (fetcher == null) {
        if (sEnableServiceNotFoundWtf) {
            Slog.wtf(TAG, "Unknown manager requested: " + name);
        }
        return null;
    }

    final Object ret = fetcher.getService(ctx); //取出服务
    if (sEnableServiceNotFoundWtf && ret == null) {
        // Some services do return null in certain situations, so don't do WTF for them.
        switch (name) {
            case Context.CONTENT_CAPTURE_MANAGER_SERVICE:
            case Context.APP_PREDICTION_SERVICE:
            case Context.INCREMENTAL_SERVICE:
                return null;
        }
        Slog.wtf(TAG, "Manager wrapper not available: " + name);
        return null;
    }
    return ret;
}

查看SystemServiceRegistry.java代码可以看出有个static代码块,在SystemServiceRegistry首次被加载的时候就会执行静态代码块中的代码,把系统服务注册添加到集合SYSTEM_SERVICE_FETCHERS 中,后面使用的时候通过getSystemService从集合中去获取。

static {
    //CHECKSTYLE:OFF IndentationCheck
    registerService(Context.ACCESSIBILITY_SERVICE, AccessibilityManager.class,
            new CachedServiceFetcher<AccessibilityManager>() {
        @Override
        public AccessibilityManager createService(ContextImpl ctx) {
            return AccessibilityManager.getInstance(ctx);
        }});

    registerService(Context.CAPTIONING_SERVICE, CaptioningManager.class,
            new CachedServiceFetcher<CaptioningManager>() {
        @Override
        public CaptioningManager createService(ContextImpl ctx) {
            return new CaptioningManager(ctx);
        }});

    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);
        }});

    registerService(Context.ACTIVITY_SERVICE, ActivityManager.class,
            new CachedServiceFetcher<ActivityManager>() {
        @Override
        public ActivityManager createService(ContextImpl ctx) {
            return new ActivityManager(ctx.getOuterContext(), ctx.mMainThread.getHandler());
        }});

    registerService(Context.ACTIVITY_TASK_SERVICE, ActivityTaskManager.class,
            new CachedServiceFetcher<ActivityTaskManager>() {
        @Override
        public ActivityTaskManager createService(ContextImpl ctx) {
            return new ActivityTaskManager(
                    ctx.getOuterContext(), ctx.mMainThread.getHandler());
        }});

    registerService(Context.URI_GRANTS_SERVICE, UriGrantsManager.class,
            new CachedServiceFetcher<UriGrantsManager>() {
        @Override
        public UriGrantsManager createService(ContextImpl ctx) {
            return new UriGrantsManager(
                    ctx.getOuterContext(), ctx.mMainThread.getHandler());
        }});

    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);
        }});

    registerService(Context.AUDIO_SERVICE, AudioManager.class,
            new CachedServiceFetcher<AudioManager>() {
        @Override
        public AudioManager createService(ContextImpl ctx) {
            return new AudioManager(ctx);
        }});

    registerService(Context.MEDIA_ROUTER_SERVICE, MediaRouter.class,
            new CachedServiceFetcher<MediaRouter>() {
        @Override
        public MediaRouter createService(ContextImpl ctx) {
            return new MediaRouter(ctx);
        }});

    registerService(Context.BLUETOOTH_SERVICE, BluetoothManager.class,
            new CachedServiceFetcher<BluetoothManager>() {
        @Override
        public BluetoothManager createService(ContextImpl ctx) {
            return new BluetoothManager(ctx);
        }});

    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));
        }});

    registerService(Context.TEXT_CLASSIFICATION_SERVICE, TextClassificationManager.class,
            new CachedServiceFetcher<TextClassificationManager>() {
        @Override
        public TextClassificationManager createService(ContextImpl ctx) {
            return new TextClassificationManager(ctx);
        }});

    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());
        }});

    // The clipboard service moved to a new package.  If someone asks for the old
    // interface by class then we want to redirect over to the new interface instead
    // (which extends it).
    SYSTEM_SERVICE_NAMES.put(android.text.ClipboardManager.class, Context.CLIPBOARD_SERVICE);

    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);
        }});

    registerService(Context.NETD_SERVICE, IBinder.class, new StaticServiceFetcher<IBinder>() {
        @Override
        public IBinder createService() throws ServiceNotFoundException {
            return ServiceManager.getServiceOrThrow(Context.NETD_SERVICE);
        }
    });

    registerService(Context.TETHERING_SERVICE, TetheringManager.class,
            new CachedServiceFetcher<TetheringManager>() {
        @Override
        public TetheringManager createService(ContextImpl ctx) {
            return new TetheringManager(
                    ctx, () -> ServiceManager.getService(Context.TETHERING_SERVICE));
        }});


    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);
        }});

    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);
        }});

    registerService(Context.CONNECTIVITY_DIAGNOSTICS_SERVICE,
            ConnectivityDiagnosticsManager.class,
            new CachedServiceFetcher<ConnectivityDiagnosticsManager>() {
        @Override
        public ConnectivityDiagnosticsManager createService(ContextImpl ctx)
                throws ServiceNotFoundException {
            // ConnectivityDiagnosticsManager is backed by ConnectivityService
            IBinder b = ServiceManager.getServiceOrThrow(Context.CONNECTIVITY_SERVICE);
            IConnectivityManager service = IConnectivityManager.Stub.asInterface(b);
            return new ConnectivityDiagnosticsManager(ctx, service);
        }});

    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);
                }
            });

    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));
        }});

    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));
        }});

    registerService(Context.DOWNLOAD_SERVICE, DownloadManager.class,
            new CachedServiceFetcher<DownloadManager>() {
        @Override
        public DownloadManager createService(ContextImpl ctx) {
            return new DownloadManager(ctx);
        }});

    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);
        }});

    registerService(Context.NFC_SERVICE, NfcManager.class,
            new CachedServiceFetcher<NfcManager>() {
        @Override
        public NfcManager createService(ContextImpl ctx) {
            return new NfcManager(ctx);
        }});

    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);
        }});

    registerService(Context.INPUT_SERVICE, InputManager.class,
            new StaticServiceFetcher<InputManager>() {
        @Override
        public InputManager createService() {
            return InputManager.getInstance();
        }});

    registerService(Context.DISPLAY_SERVICE, DisplayManager.class,
            new CachedServiceFetcher<DisplayManager>() {
        @Override
        public DisplayManager createService(ContextImpl ctx) {
            return new DisplayManager(ctx.getOuterContext());
        }});

    registerService(Context.COLOR_DISPLAY_SERVICE, ColorDisplayManager.class,
            new CachedServiceFetcher<ColorDisplayManager>() {
                @Override
                public ColorDisplayManager createService(ContextImpl ctx) {
                    return new ColorDisplayManager();
                }
            });

    // InputMethodManager has its own cache strategy based on display id to support apps that
    // still assume InputMethodManager is a per-process singleton and it's safe to directly
    // access internal fields via reflection.  Hence directly use ServiceFetcher instead of
    // StaticServiceFetcher/CachedServiceFetcher.
    registerService(Context.INPUT_METHOD_SERVICE, InputMethodManager.class,
            new ServiceFetcher<InputMethodManager>() {
        @Override
        public InputMethodManager getService(ContextImpl ctx) {
            return InputMethodManager.forContext(ctx.getOuterContext());
        }});

    registerService(Context.TEXT_SERVICES_MANAGER_SERVICE, TextServicesManager.class,
            new CachedServiceFetcher<TextServicesManager>() {
        @Override
        public TextServicesManager createService(ContextImpl ctx)
                throws ServiceNotFoundException {
            return TextServicesManager.createInstance(ctx);
        }});

    registerService(Context.KEYGUARD_SERVICE, KeyguardManager.class,
            new CachedServiceFetcher<KeyguardManager>() {
        @Override
        public KeyguardManager createService(ContextImpl ctx) throws ServiceNotFoundException {
            return new KeyguardManager(ctx);
        }});

    registerService(Context.LAYOUT_INFLATER_SERVICE, LayoutInflater.class,
            new CachedServiceFetcher<LayoutInflater>() {
        @Override
        public LayoutInflater createService(ContextImpl ctx) {
            return new PhoneLayoutInflater(ctx.getOuterContext());
        }});

    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));
        }});

    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)));
        }});

    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());
        }});

    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);
        }});

    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());
        }});

    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);
        }});

    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());
        }});

    registerService(Context.SENSOR_SERVICE, SensorManager.class,
            new CachedServiceFetcher<SensorManager>() {
        @Override
        public SensorManager createService(ContextImpl ctx) {
            return new SystemSensorManager(ctx.getOuterContext(),
              ctx.mMainThread.getHandler().getLooper());
        }});

    registerService(Context.SENSOR_PRIVACY_SERVICE, SensorPrivacyManager.class,
            new CachedServiceFetcher<SensorPrivacyManager>() {
                @Override
                public SensorPrivacyManager createService(ContextImpl ctx) {
                    return SensorPrivacyManager.getInstance(ctx);
                }});

    registerService(Context.STATUS_BAR_SERVICE, StatusBarManager.class,
            new CachedServiceFetcher<StatusBarManager>() {
        @Override
        public StatusBarManager createService(ContextImpl ctx) {
            return new StatusBarManager(ctx.getOuterContext());
        }});

    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());
        }});

    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);
        }});

    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);
                }});

    registerService(Context.SYSTEM_CONFIG_SERVICE, SystemConfigManager.class,
            new CachedServiceFetcher<SystemConfigManager>() {
                @Override
                public SystemConfigManager createService(ContextImpl ctx) {
                    return new SystemConfigManager();
                }});

    registerService(Context.TELEPHONY_REGISTRY_SERVICE, TelephonyRegistryManager.class,
        new CachedServiceFetcher<TelephonyRegistryManager>() {
            @Override
            public TelephonyRegistryManager createService(ContextImpl ctx) {
                return new TelephonyRegistryManager(ctx);
            }});

    registerService(Context.TELECOM_SERVICE, TelecomManager.class,
            new CachedServiceFetcher<TelecomManager>() {
        @Override
        public TelecomManager createService(ContextImpl ctx) {
            return new TelecomManager(ctx.getOuterContext());
        }});

    registerService(Context.MMS_SERVICE, MmsManager.class,
            new CachedServiceFetcher<MmsManager>() {
                @Override
                public MmsManager createService(ContextImpl ctx) {
                    return new MmsManager(ctx.getOuterContext());
                }});

    registerService(Context.UI_MODE_SERVICE, UiModeManager.class,
            new CachedServiceFetcher<UiModeManager>() {
        @Override
        public UiModeManager createService(ContextImpl ctx) throws ServiceNotFoundException {
            return new UiModeManager(ctx.getOuterContext());
        }});

    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));
        }});

    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));
                }});

    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));
        }});

    registerService(Context.VIBRATOR_SERVICE, Vibrator.class,
            new CachedServiceFetcher<Vibrator>() {
        @Override
        public Vibrator createService(ContextImpl ctx) {
            return new SystemVibrator(ctx);
        }});

    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()) {
                    // Instant app
                    throw new ServiceNotFoundException(Context.WALLPAPER_SERVICE);
                }
                final boolean enabled = Resources.getSystem()
                        .getBoolean(com.android.internal.R.bool.config_enableWallpaperService);
                if (!enabled) {
                    // Device doesn't support wallpaper, return a limited manager
                    return DisabledWallpaperManager.getInstance();
                }
                // Bad state - WallpaperManager methods will throw exception
                Log.e(TAG, "No wallpaper service");
            }
            IWallpaperManager service = IWallpaperManager.Stub.asInterface(b);
            return new WallpaperManager(service, ctx.getOuterContext(),
                    ctx.mMainThread.getHandler());
        }});

    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());
        }});

    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);
        }});

    registerService(Context.WIFI_NL80211_SERVICE, WifiNl80211Manager.class,
            new CachedServiceFetcher<WifiNl80211Manager>() {
                @Override
                public WifiNl80211Manager createService(ContextImpl ctx) {
                    return new WifiNl80211Manager(ctx.getOuterContext());
                }
            });

    registerService(Context.WINDOW_SERVICE, WindowManager.class,
            new CachedServiceFetcher<WindowManager>() {
        @Override
        public WindowManager createService(ContextImpl ctx) {
            return new WindowManagerImpl(ctx);
        }});

    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);
        }});

    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);
        }});

    registerService(Context.CAMERA_SERVICE, CameraManager.class,
            new CachedServiceFetcher<CameraManager>() {
        @Override
        public CameraManager createService(ContextImpl ctx) {
            return new CameraManager(ctx);
        }});

    registerService(Context.LAUNCHER_APPS_SERVICE, LauncherApps.class,
            new CachedServiceFetcher<LauncherApps>() {
        @Override
        public LauncherApps createService(ContextImpl ctx) {
            return new LauncherApps(ctx);
        }});

    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);
        }});

    registerService(Context.PRINT_SERVICE, PrintManager.class,
            new CachedServiceFetcher<PrintManager>() {
        @Override
        public PrintManager createService(ContextImpl ctx) throws ServiceNotFoundException {
            IPrintManager service = null;
            // If the feature not present, don't try to look up every time
            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);
        }});

    registerService(Context.COMPANION_DEVICE_SERVICE, CompanionDeviceManager.class,
            new CachedServiceFetcher<CompanionDeviceManager>() {
        @Override
        public CompanionDeviceManager createService(ContextImpl ctx)
                throws ServiceNotFoundException {
            ICompanionDeviceManager service = null;
            // If the feature not present, don't try to look up every time
            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());
        }});

    registerService(Context.CONSUMER_IR_SERVICE, ConsumerIrManager.class,
            new CachedServiceFetcher<ConsumerIrManager>() {
        @Override
        public ConsumerIrManager createService(ContextImpl ctx) throws ServiceNotFoundException {
            return new ConsumerIrManager(ctx);
        }});

    registerService(Context.MEDIA_SESSION_SERVICE, MediaSessionManager.class,
            new CachedServiceFetcher<MediaSessionManager>() {
        @Override
        public MediaSessionManager createService(ContextImpl ctx) {
            return new MediaSessionManager(ctx);
        }});

    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);
        }});

    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);
        }});

    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);
                }
            });

    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);
                }
            });

    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);
                }
            });

    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());
        }});

    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());
        }});

    registerService(Context.NETWORK_SCORE_SERVICE, NetworkScoreManager.class,
            new CachedServiceFetcher<NetworkScoreManager>() {
        @Override
        public NetworkScoreManager createService(ContextImpl ctx) throws ServiceNotFoundException {
            return new NetworkScoreManager(ctx);
        }});

    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);
        }});

    registerService(Context.NETWORK_STATS_SERVICE, NetworkStatsManager.class,
            new CachedServiceFetcher<NetworkStatsManager>() {
        @Override
        public NetworkStatsManager createService(ContextImpl ctx) throws ServiceNotFoundException {
            return new NetworkStatsManager(ctx.getOuterContext());
        }});

    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 {
                // not supported
                return null;
            }
        }});

    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 {
                // not supported
                return null;
            }
        }});

    registerService(Context.MEDIA_PROJECTION_SERVICE, MediaProjectionManager.class,
            new CachedServiceFetcher<MediaProjectionManager>() {
        @Override
        public MediaProjectionManager createService(ContextImpl ctx) {
            return new MediaProjectionManager(ctx);
        }});

    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));
        }});

    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));
        }});

    registerService(Context.RADIO_SERVICE, RadioManager.class,
            new CachedServiceFetcher<RadioManager>() {
        @Override
        public RadioManager createService(ContextImpl ctx) throws ServiceNotFoundException {
            return new RadioManager(ctx);
        }});

    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);
        }});

    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));
        }});

    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));
        }});

    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));
        }});

    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));
                }});

    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));
        }});

    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());
        }});

    registerService(Context.INCIDENT_SERVICE, IncidentManager.class,
            new CachedServiceFetcher<IncidentManager>() {
        @Override
        public IncidentManager createService(ContextImpl ctx) throws ServiceNotFoundException {
            return new IncidentManager(ctx);
        }});

    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));
                }});

    registerService(Context.AUTOFILL_MANAGER_SERVICE, AutofillManager.class,
            new CachedServiceFetcher<AutofillManager>() {
        @Override
        public AutofillManager createService(ContextImpl ctx) throws ServiceNotFoundException {
            // Get the services without throwing as this is an optional feature
            IBinder b = ServiceManager.getService(Context.AUTOFILL_MANAGER_SERVICE);
            IAutoFillManager service = IAutoFillManager.Stub.asInterface(b);
            return new AutofillManager(ctx.getOuterContext(), service);
        }});

    registerService(Context.CONTENT_CAPTURE_MANAGER_SERVICE, ContentCaptureManager.class,
            new CachedServiceFetcher<ContentCaptureManager>() {
        @Override
        public ContentCaptureManager createService(ContextImpl ctx)
                throws ServiceNotFoundException {
            // Get the services without throwing as this is an optional feature
            Context outerContext = ctx.getOuterContext();
            ContentCaptureOptions options = outerContext.getContentCaptureOptions();
            // Options is null when the service didn't whitelist the activity or package
            if (options != null && (options.lite || options.isWhitelisted(outerContext))) {
                IBinder b = ServiceManager
                        .getService(Context.CONTENT_CAPTURE_MANAGER_SERVICE);
                IContentCaptureManager service = IContentCaptureManager.Stub.asInterface(b);
                // Service is null when not provided by OEM or disabled by kill-switch.
                if (service != null) {
                    return new ContentCaptureManager(outerContext, service, options);
                }
            }
            // When feature is disabled or app / package not whitelisted, we return a null
            // manager to apps so the performance impact is practically zero
            return null;
        }});

    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);
        }
    });

    registerService(Context.CONTENT_SUGGESTIONS_SERVICE,
            ContentSuggestionsManager.class,
            new CachedServiceFetcher<ContentSuggestionsManager>() {
                @Override
                public ContentSuggestionsManager createService(ContextImpl ctx) {
                    // No throw as this is an optional service
                    IBinder b = ServiceManager.getService(
                            Context.CONTENT_SUGGESTIONS_SERVICE);
                    IContentSuggestionsManager service =
                            IContentSuggestionsManager.Stub.asInterface(b);
                    return new ContentSuggestionsManager(ctx.getUserId(), service);
                }
            });

    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));
        }
    });

    registerService(Context.TIME_ZONE_RULES_MANAGER_SERVICE, RulesManager.class,
            new CachedServiceFetcher<RulesManager>() {
        @Override
        public RulesManager createService(ContextImpl ctx) {
            return new RulesManager(ctx.getOuterContext());
        }});

    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));
                }
            });

    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());
                }
        });

    registerService(Context.TIME_DETECTOR_SERVICE, TimeDetector.class,
            new CachedServiceFetcher<TimeDetector>() {
                @Override
                public TimeDetector createService(ContextImpl ctx)
                        throws ServiceNotFoundException {
                    return new TimeDetectorImpl();
                }});

    registerService(Context.TIME_ZONE_DETECTOR_SERVICE, TimeZoneDetector.class,
            new CachedServiceFetcher<TimeZoneDetector>() {
                @Override
                public TimeZoneDetector createService(ContextImpl ctx)
                        throws ServiceNotFoundException {
                    return new TimeZoneDetectorImpl();
                }});

    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);
                }});

    registerService(Context.PERMISSION_CONTROLLER_SERVICE, PermissionControllerManager.class,
            new CachedServiceFetcher<PermissionControllerManager>() {
                @Override
                public PermissionControllerManager createService(ContextImpl ctx) {
                    return new PermissionControllerManager(ctx.getOuterContext(),
                            ctx.getMainThreadHandler());
                }});

    registerService(Context.ROLE_SERVICE, RoleManager.class,
            new CachedServiceFetcher<RoleManager>() {
                @Override
                public RoleManager createService(ContextImpl ctx)
                        throws ServiceNotFoundException {
                    return new RoleManager(ctx.getOuterContext());
                }});

    registerService(Context.ROLE_CONTROLLER_SERVICE, RoleControllerManager.class,
            new CachedServiceFetcher<RoleControllerManager>() {
                @Override
                public RoleControllerManager createService(ContextImpl ctx)
                        throws ServiceNotFoundException {
                    return new RoleControllerManager(ctx.getOuterContext());
                }});

    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));
                }});

    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));
                }});

    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));
                }});
    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));
                }});
    registerService(Context.LIGHTS_SERVICE, LightsManager.class,
        new CachedServiceFetcher<LightsManager>() {
            @Override
            public LightsManager createService(ContextImpl ctx)
                throws ServiceNotFoundException {
                return new LightsManager(ctx);
            }});
    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));
                }});

    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));
                }});
    //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));
                }});
    registerService(Context.DREAM_SERVICE, DreamManager.class,
            new CachedServiceFetcher<DreamManager>() {
                @Override
                public DreamManager createService(ContextImpl ctx)
                        throws ServiceNotFoundException {
                    return new DreamManager(ctx);
                }});

    sInitializing = true;
    try {
        // Note: the following functions need to be @SystemApis, once they become mainline
        // modules.
        JobSchedulerFrameworkInitializer.registerServiceWrappers();
        BlobStoreManagerFrameworkInitializer.initialize();
        TelephonyFrameworkInitializer.registerServiceWrappers();
        WifiFrameworkInitializer.registerServiceWrappers();
        StatsFrameworkInitializer.registerServiceWrappers();
    } finally {
        // If any of the above code throws, we're in a pretty bad shape and the process
        // will likely crash, but we'll reset it just in case there's an exception handler...
        sInitializing = false;
    }
}

3.2 Glide

Glide图片加载框架大家应该很熟悉,实际上Glide也使用单例模式。在执行Glide三部曲的第一步with方法的时候就会初始化并创建Glide实例,以Glide上下文举例
3.2.1 Glide.with
Glide.with调用getRetriever方法

//Glide.java
public static RequestManager with(@NonNull Activity activity) {
  return getRetriever(activity).get(activity);
}

3.2.2 Glide.getRetriever
Glide.getRetriever调用了Glide.get

//Glide.java
private static RequestManagerRetriever getRetriever(@Nullable Context context) {
  // Context could be null for other reasons (ie the user passes in null), but in practice it will
  // only occur due to errors with the Fragment lifecycle.
  Preconditions.checkNotNull(
      context,
      "You cannot start a load on a not yet attached View or a Fragment where getActivity() "
          + "returns null (which usually occurs when getActivity() is called before the Fragment "
          + "is attached or after the Fragment is destroyed).");
  return Glide.get(context).getRequestManagerRetriever();
}

3.2.3 Glide.get

Glide.get就是一个典型的改进版DCL单例模式了

//Glide.java
private static volatile Glide glide;
……
public static Glide get(@NonNull Context context) {
  if (glide == null) {
    GeneratedAppGlideModule annotationGeneratedModule =
        getAnnotationGeneratedGlideModules(context.getApplicationContext());
    synchronized (Glide.class) {
      if (glide == null) {
        checkAndInitializeGlide(context, annotationGeneratedModule);
      }
    }
  }

  return glide;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值