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 android.telephony.cts.util; 18 19 import static com.android.internal.util.FunctionalUtils.ThrowingConsumer; 20 import static com.android.internal.util.FunctionalUtils.ThrowingFunction; 21 22 import android.content.Context; 23 import android.os.ParcelUuid; 24 import android.telephony.SubscriptionManager; 25 26 import java.util.Collections; 27 28 /** 29 * Utility to execute a code block with an ephemeral subscription group. 30 * 31 * <p>These methods will remove the subscription(s) from the ephemeral subscription group once the 32 * specified task is completed. 33 * 34 * <p>Example: 35 * 36 * <pre> 37 * SubscriptionGroupUtils.withEphemeralSubscriptionGroup( 38 * ctx, subId, (subGrp) -> telephonyManager.doFoo(subGrp, bar)); 39 * </pre> 40 */ 41 public class SubscriptionGroupUtils { withEphemeralSubscriptionGroup( Context c, int subId, ThrowingConsumer<ParcelUuid> action)42 public static void withEphemeralSubscriptionGroup( 43 Context c, int subId, ThrowingConsumer<ParcelUuid> action) throws Exception { 44 final SubscriptionManager subMgr = c.getSystemService(SubscriptionManager.class); 45 ParcelUuid subGrp = null; 46 try { 47 subGrp = subMgr.createSubscriptionGroup(Collections.singletonList(subId)); 48 action.acceptOrThrow(subGrp); 49 } finally { 50 if (subGrp != null) { 51 subMgr.removeSubscriptionsFromGroup(Collections.singletonList(subId), subGrp); 52 } 53 } 54 } 55 withEphemeralSubscriptionGroup( Context c, int subId, ThrowingFunction<ParcelUuid, R> action)56 public static <R> R withEphemeralSubscriptionGroup( 57 Context c, int subId, ThrowingFunction<ParcelUuid, R> action) throws Exception { 58 final SubscriptionManager subMgr = c.getSystemService(SubscriptionManager.class); 59 ParcelUuid subGrp = null; 60 try { 61 subGrp = subMgr.createSubscriptionGroup(Collections.singletonList(subId)); 62 return action.applyOrThrow(subGrp); 63 } finally { 64 if (subGrp != null) { 65 subMgr.removeSubscriptionsFromGroup(Collections.singletonList(subId), subGrp); 66 } 67 } 68 } 69 } 70