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.adservices.service.common; 18 19 import android.os.Binder; 20 21 import androidx.annotation.NonNull; 22 23 import java.util.Objects; 24 import java.util.function.Supplier; 25 26 /** 27 * Utility class for reading {@link android.provider.DeviceConfig} flags from the Binder thread. 28 * 29 * <p>The caller in the {@link Binder} thread does not have the {@link 30 * android.Manifest.permission#READ_DEVICE_CONFIG} permission, so the calling identity needs to be 31 * temporarily cleared in order to read with the local process's permissions. 32 */ 33 public class BinderFlagReader { 34 /** 35 * Reads and returns the given flag from the {@link Binder} thread. 36 * 37 * <p>The {@link Binder} thread does not have the {@link 38 * android.Manifest.permission#READ_DEVICE_CONFIG} permission, so the calling identity needs to 39 * be temporarily cleared in order to read with the local process's permissions. 40 * 41 * @param <T> type returned by the {@code flagSupplier} 42 */ readFlag(@onNull Supplier<T> flagSupplier)43 public static <T> T readFlag(@NonNull Supplier<T> flagSupplier) { 44 Objects.requireNonNull(flagSupplier); 45 final long token = Binder.clearCallingIdentity(); 46 try { 47 return flagSupplier.get(); 48 } finally { 49 Binder.restoreCallingIdentity(token); 50 } 51 } 52 } 53