1 /* 2 * Copyright 2018 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.accessibilityservice.cts.utils; 18 19 import android.app.Instrumentation; 20 21 import java.util.concurrent.Callable; 22 import java.util.concurrent.atomic.AtomicReference; 23 24 /** 25 * Utilities to return values from {@link Instrumentation#runOnMainSync()} 26 */ 27 public class RunOnMainUtils { 28 /** 29 * Execute a callable on main and return its value 30 */ getOnMain( Instrumentation instrumentation, Callable<T> callable)31 public static <T extends Object> T getOnMain( 32 Instrumentation instrumentation, Callable<T> callable) { 33 AtomicReference<T> returnValue = new AtomicReference<>(null); 34 AtomicReference<Throwable> throwable = new AtomicReference<>(null); 35 instrumentation.runOnMainSync(() -> { 36 try { 37 returnValue.set(callable.call()); 38 } catch (Throwable e) { 39 throwable.set(e); 40 } 41 }); 42 if (throwable.get() != null) { 43 throw new RuntimeException(throwable.get()); 44 } 45 return returnValue.get(); 46 } 47 } 48