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