1 /* 2 * Copyright (C) 2013 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 com.android.server; 18 19 import com.android.internal.annotations.VisibleForTesting; 20 21 import android.util.ArrayMap; 22 23 /** 24 * This class is used in a similar way as ServiceManager, except the services registered here 25 * are not Binder objects and are only available in the same process. 26 * 27 * Once all services are converted to the SystemService interface, this class can be absorbed 28 * into SystemServiceManager. 29 * 30 * {@hide} 31 */ 32 public final class LocalServices { LocalServices()33 private LocalServices() {} 34 35 private static final ArrayMap<Class<?>, Object> sLocalServiceObjects = 36 new ArrayMap<Class<?>, Object>(); 37 38 /** 39 * Returns a local service instance that implements the specified interface. 40 * 41 * @param type The type of service. 42 * @return The service object. 43 */ 44 @SuppressWarnings("unchecked") getService(Class<T> type)45 public static <T> T getService(Class<T> type) { 46 synchronized (sLocalServiceObjects) { 47 return (T) sLocalServiceObjects.get(type); 48 } 49 } 50 51 /** 52 * Adds a service instance of the specified interface to the global registry of local services. 53 */ addService(Class<T> type, T service)54 public static <T> void addService(Class<T> type, T service) { 55 synchronized (sLocalServiceObjects) { 56 if (sLocalServiceObjects.containsKey(type)) { 57 throw new IllegalStateException("Overriding service registration"); 58 } 59 sLocalServiceObjects.put(type, service); 60 } 61 } 62 63 /** 64 * Remove a service instance, must be only used in tests. 65 */ 66 @VisibleForTesting removeServiceForTest(Class<T> type)67 public static <T> void removeServiceForTest(Class<T> type) { 68 synchronized (sLocalServiceObjects) { 69 sLocalServiceObjects.remove(type); 70 } 71 } 72 } 73