1 /* 2 * Copyright 2024 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.media.mediatestutils; 18 19 import android.content.Context; 20 import android.media.AudioManager; 21 22 import androidx.test.platform.app.InstrumentationRegistry; 23 24 import org.junit.rules.TestRule; 25 import org.junit.runner.Description; 26 import org.junit.runners.model.Statement; 27 28 /** 29 * Barrier to wait for permission updates to propagate to audioserver, to avoid flakiness when using 30 * {@code com.android.compatability.common.util.AdoptShellPermissionsRule}. Note, this rule should 31 * <b> always </b> be placed after the adopt permission rule. Don't use rule when changing 32 * permission state in {@code @Before}, since that executes after all rules. 33 */ 34 public class PermissionUpdateBarrierRule implements TestRule { 35 36 private final Context mContext; 37 38 /** 39 * @param context the context to use 40 */ PermissionUpdateBarrierRule(Context context)41 public PermissionUpdateBarrierRule(Context context) { 42 mContext = context; 43 } 44 PermissionUpdateBarrierRule()45 public PermissionUpdateBarrierRule() { 46 this(InstrumentationRegistry.getInstrumentation().getContext()); 47 } 48 49 @Override apply(Statement base, Description description)50 public Statement apply(Statement base, Description description) { 51 return new Statement() { 52 @Override 53 public void evaluate() throws Throwable { 54 mContext.getSystemService(AudioManager.class).permissionUpdateBarrier(); 55 base.evaluate(); 56 } 57 }; 58 } 59 } 60