ApiLoader.java revision 3661ad03d2cde4e04e10ee5226e8aa1f05d70413
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.Context; 21import android.content.pm.PackageManager; 22import android.os.Build; 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 (PackageManager.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 context) 46 throws PackageManager.NameNotFoundException, ReflectiveOperationException { 47 if (sMediaLibrary != null) return sMediaLibrary; 48 49 // TODO Figure out when to use which package (query media update service) 50 int flags = Build.IS_DEBUGGABLE ? 0 : PackageManager.MATCH_FACTORY_ONLY; 51 Context libContext = context.createApplicationContext( 52 context.getPackageManager().getPackageInfo(UPDATE_PACKAGE, flags).applicationInfo, 53 Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY); 54 sMediaLibrary = libContext.getClassLoader() 55 .loadClass(UPDATE_CLASS) 56 .getMethod(UPDATE_METHOD, Resources.class, Resources.Theme.class) 57 .invoke(null, libContext.getResources(), libContext.getTheme()); 58 return sMediaLibrary; 59 } 60} 61