ApiLoader.java revision 365ded397ce0211c0356b563551866b2f3cdf62c
1/*
2 * Copyright (C) 2017 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 android.media.update;
18
19import android.content.res.Resources;
20import android.content.res.Resources.Theme;
21import android.content.Context;
22import android.content.pm.PackageManager.NameNotFoundException;
23
24/**
25 * @hide
26 */
27public final class ApiLoader {
28    private static Object sMediaLibrary;
29
30    private static final String UPDATE_PACKAGE = "com.android.media.update";
31    private static final String UPDATE_CLASS = "com.android.media.update.ApiFactory";
32    private static final String UPDATE_METHOD = "initialize";
33
34    private ApiLoader() { }
35
36    public static StaticProvider getProvider(Context context) {
37        try {
38            return (StaticProvider) getMediaLibraryImpl(context);
39        } catch (NameNotFoundException | ReflectiveOperationException e) {
40            throw new RuntimeException(e);
41        }
42    }
43
44    // TODO This method may do I/O; Ensure it does not violate (emit warnings in) strict mode.
45    private static synchronized Object getMediaLibraryImpl(Context appContext)
46            throws NameNotFoundException, ReflectiveOperationException {
47        if (sMediaLibrary != null) return sMediaLibrary;
48
49        // TODO Dynamically find the package name
50        Context libContext = appContext.createPackageContext(UPDATE_PACKAGE,
51                Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY);
52        sMediaLibrary = libContext.getClassLoader()
53                .loadClass(UPDATE_CLASS)
54                .getMethod(UPDATE_METHOD, Resources.class, Theme.class)
55                .invoke(null, libContext.getResources(), libContext.getTheme());
56        return sMediaLibrary;
57    }
58}
59