1 /*
2  * Copyright (C) 2023 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.permissioncontroller.permission.utils;
18 
19 import android.content.Context;
20 
21 import androidx.annotation.NonNull;
22 
23 import com.android.modules.utils.build.SdkLevel;
24 
25 /**
26  * Helper Context compat class for {@link Context}.
27  */
28 public class ContextCompat {
29     /**
30      * The default device ID, which is the ID of the primary (non-virtual) device.
31      *
32      * @see Context#DEVICE_ID_DEFAULT
33      */
34     public static final int DEVICE_ID_DEFAULT = 0;
35 
ContextCompat()36     private ContextCompat() {
37     }
38 
39     /**
40      * @return The default device ID for pre V platforms, otherwise returns the device ID from
41      * the context.
42      */
getDeviceId(@onNull Context context)43     public static int getDeviceId(@NonNull Context context) {
44         if (SdkLevel.isAtLeastU()) {
45             return context.getDeviceId();
46         } else {
47             return DEVICE_ID_DEFAULT;
48         }
49 
50     }
51 
52     /**
53      * Creates a new device context, if needed.
54      *
55      * @return A new context if the input context is for a different device, otherwise
56      * return the same context object. See {@link Context#DEVICE_ID_DEFAULT}
57      */
58     @NonNull
createDeviceContext(@onNull Context context, int deviceId)59     public static Context createDeviceContext(@NonNull Context context, int deviceId) {
60         if (SdkLevel.isAtLeastU()) {
61             return deviceId == context.getDeviceId()
62                     ? context : context.createDeviceContext(deviceId);
63         } else {
64             if (deviceId != DEVICE_ID_DEFAULT) {
65                 throw new IllegalArgumentException("Invalid device ID " + deviceId);
66             }
67             return context;
68         }
69     }
70 }
71