1 /* 2 * Copyright (C) 2013 DroidDriver committers 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 io.appium.droiddriver.util; 18 19 import android.app.Activity; 20 21 import io.appium.droiddriver.exceptions.UnrecoverableException; 22 import io.appium.droiddriver.instrumentation.InstrumentationDriver; 23 24 /** 25 * Static helper methods for retrieving activities. 26 */ 27 public class ActivityUtils { 28 public interface Supplier<T> { 29 /** 30 * Retrieves an instance of the appropriate type. The returned object may or 31 * may not be a new instance, depending on the implementation. 32 * 33 * @return an instance of the appropriate type 34 */ get()35 T get(); 36 } 37 38 private static Supplier<Activity> runningActivitySupplier; 39 40 /** 41 * Sets the Supplier for the running (a.k.a. resumed or foreground) activity. 42 * Called from {@link io.appium.droiddriver.runner.TestRunner}. If a 43 * custom runner is used, this method must be called appropriately, otherwise 44 * {@link #getRunningActivity} won't work. 45 */ setRunningActivitySupplier(Supplier<Activity> activitySupplier)46 public static synchronized void setRunningActivitySupplier(Supplier<Activity> activitySupplier) { 47 runningActivitySupplier = activitySupplier; 48 } 49 50 /** 51 * Gets the running (a.k.a. resumed or foreground) activity. 52 * {@link InstrumentationDriver} depends on this. 53 * 54 * @return the currently running activity, or null if no activity has focus. 55 */ getRunningActivity()56 public static synchronized Activity getRunningActivity() { 57 if (runningActivitySupplier == null) { 58 throw new UnrecoverableException("If you don't use DroidDriver TestRunner, you need to call" + 59 " ActivityUtils.setRunningActivitySupplier appropriately"); 60 } 61 return runningActivitySupplier.get(); 62 } 63 } 64