1 /* 2 * Copyright (C) 2021 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.connectivity; 18 19 import android.annotation.NonNull; 20 import android.annotation.Nullable; 21 import android.content.Context; 22 import android.content.pm.PackageManager; 23 import android.content.res.Resources; 24 25 import com.android.internal.annotations.VisibleForTesting; 26 import com.android.net.module.util.DeviceConfigUtils; 27 28 /** 29 * Utility to obtain the {@link com.android.server.ConnectivityService} {@link Resources}, in the 30 * ServiceConnectivityResources APK. 31 * @hide 32 */ 33 public class ConnectivityResources { 34 @NonNull 35 private final Context mContext; 36 37 @Nullable 38 private Context mResourcesContext = null; 39 40 @Nullable 41 private static Context sTestResourcesContext = null; 42 ConnectivityResources(Context context)43 public ConnectivityResources(Context context) { 44 mContext = context; 45 } 46 47 /** 48 * Convenience method to mock all resources for the duration of a test. 49 * 50 * Call with a null context to reset after the test. 51 */ 52 @VisibleForTesting setResourcesContextForTest(@ullable Context testContext)53 public static void setResourcesContextForTest(@Nullable Context testContext) { 54 sTestResourcesContext = testContext; 55 } 56 57 /** 58 * Get the {@link Context} of the resources package. 59 */ getResourcesContext()60 public synchronized Context getResourcesContext() { 61 if (sTestResourcesContext != null) { 62 return sTestResourcesContext; 63 } 64 65 if (mResourcesContext != null) { 66 return mResourcesContext; 67 } 68 69 final String resPkg = DeviceConfigUtils.getConnectivityResourcesPackageName(mContext); 70 final Context pkgContext; 71 try { 72 pkgContext = mContext.createPackageContext(resPkg, 0 /* flags */); 73 } catch (PackageManager.NameNotFoundException e) { 74 throw new IllegalStateException("Resolved package not found", e); 75 } 76 77 mResourcesContext = pkgContext; 78 return pkgContext; 79 } 80 81 /** 82 * Get the {@link Resources} of the ServiceConnectivityResources APK. 83 */ get()84 public Resources get() { 85 return getResourcesContext().getResources(); 86 } 87 } 88