blob: 2c619afddce53289dc15382a1afe111b87c5e007 [file] [log] [blame]
Keun-young Parkd462a912019-02-11 08:53:42 -08001/*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.car;
18
19import android.util.ArrayMap;
20
21import com.android.internal.annotations.VisibleForTesting;
22
23/**
24 * Copy of frameworks/base/core/java/com/android/server/LocalServices.java
25 * This is for accessing other car service components.
26 */
27public class CarLocalServices {
28 private CarLocalServices() {}
29
30 private static final ArrayMap<Class<?>, Object> sLocalServiceObjects =
31 new ArrayMap<Class<?>, Object>();
32
33 /**
34 * Returns a local service instance that implements the specified interface.
35 *
36 * @param type The type of service.
37 * @return The service object.
38 */
39 @SuppressWarnings("unchecked")
40 public static <T> T getService(Class<T> type) {
41 synchronized (sLocalServiceObjects) {
42 return (T) sLocalServiceObjects.get(type);
43 }
44 }
45
46 /**
47 * Adds a service instance of the specified interface to the global registry of local services.
48 */
49 public static <T> void addService(Class<T> type, T service) {
50 synchronized (sLocalServiceObjects) {
51 if (sLocalServiceObjects.containsKey(type)) {
52 throw new IllegalStateException("Overriding service registration");
53 }
54 sLocalServiceObjects.put(type, service);
55 }
56 }
57
58 /**
59 * Remove a service instance, must be only used in tests.
60 */
61 @VisibleForTesting
62 public static <T> void removeServiceForTest(Class<T> type) {
63 synchronized (sLocalServiceObjects) {
64 sLocalServiceObjects.remove(type);
65 }
66 }
67
68 /**
69 * Remove all registered services. Should be called when car service restarts.
70 */
71 public static void removeAllServices() {
72 synchronized (sLocalServiceObjects) {
73 sLocalServiceObjects.clear();
74 }
75 }
76}