aboutsummaryrefslogtreecommitdiff
path: root/src/io/appium/droiddriver/util/InstrumentationUtils.java
blob: 0ca087af0fc6fbc724bd8637586bb9fd5a89551a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
/*
 * Copyright (C) 2015 DroidDriver committers
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.appium.droiddriver.util;

import android.app.Instrumentation;
import android.content.Context;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import io.appium.droiddriver.exceptions.DroidDriverException;
import io.appium.droiddriver.exceptions.TimeoutException;
import io.appium.droiddriver.exceptions.UnrecoverableException;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

/** Static utility methods pertaining to {@link Instrumentation}. */
public class InstrumentationUtils {
  private static final Runnable EMPTY_RUNNABLE =
      new Runnable() {
        @Override
        public void run() {}
      };
  private static final Executor RUN_ON_MAIN_SYNC_EXECUTOR = Executors.newSingleThreadExecutor();
  private static Instrumentation instrumentation;
  private static Bundle options;
  private static long runOnMainSyncTimeoutMillis;

  /**
   * Initializes this class. If you use a runner that is not DroidDriver-aware, you need to call
   * this method appropriately. See {@link io.appium.droiddriver.runner.TestRunner#onCreate} for
   * example.
   */
  public static void init(Instrumentation instrumentation, Bundle arguments) {
    if (InstrumentationUtils.instrumentation != null) {
      throw new DroidDriverException("init() can only be called once");
    }
    InstrumentationUtils.instrumentation = instrumentation;
    options = arguments;

    String timeoutString = getD2Option("runOnMainSyncTimeout");
    runOnMainSyncTimeoutMillis = timeoutString == null ? 10000L : Long.parseLong(timeoutString);
  }

  private static void checkInitialized() {
    if (instrumentation == null) {
      throw new UnrecoverableException(
          "If you use a runner that is not DroidDriver-aware, you"
              + " need to call InstrumentationUtils.init appropriately");
    }
  }

  public static Instrumentation getInstrumentation() {
    checkInitialized();
    return instrumentation;
  }

  public static Context getTargetContext() {
    return getInstrumentation().getTargetContext();
  }

  /**
   * Gets the <a href=
   * "http://developer.android.com/tools/testing/testing_otheride.html#AMOptionsSyntax" >am
   * instrument options</a>.
   */
  public static Bundle getOptions() {
    checkInitialized();
    return options;
  }

  /**
   * Gets the string value associated with the given key. This is preferred over using {@link
   * #getOptions} because the returned {@link Bundle} contains only string values - am instrument
   * options do not support value types other than string.
   */
  public static String getOption(String key) {
    return getOptions().getString(key);
  }

  /**
   * Calls {@link #getOption} with "dd." prefixed to {@code key}. This is for DroidDriver
   * implementation to use a consistent pattern for its options.
   */
  public static String getD2Option(String key) {
    return getOption("dd." + key);
  }

  /**
   * Tries to wait for an idle state on the main thread on best-effort basis up to {@code
   * timeoutMillis}. The main thread may not enter the idle state when animation is playing, for
   * example, the ProgressBar.
   */
  public static boolean tryWaitForIdleSync(long timeoutMillis) {
    checkNotMainThread();
    FutureTask<Void> emptyTask = new FutureTask<Void>(EMPTY_RUNNABLE, null);
    instrumentation.waitForIdle(emptyTask);

    try {
      emptyTask.get(timeoutMillis, TimeUnit.MILLISECONDS);
    } catch (java.util.concurrent.TimeoutException e) {
      Logs.log(
          Log.INFO,
          "Timed out after " + timeoutMillis + " milliseconds waiting for idle on main looper");
      return false;
    } catch (Throwable t) {
      throw DroidDriverException.propagate(t);
    }
    return true;
  }

  public static void runOnMainSyncWithTimeout(final Runnable runnable) {
    runOnMainSyncWithTimeout(
        new Callable<Void>() {
          @Override
          public Void call() throws Exception {
            runnable.run();
            return null;
          }
        });
  }

  /**
   * Runs {@code callable} on the main thread on best-effort basis up to a time limit, which
   * defaults to {@code 10000L} and can be set as an am instrument option under the key {@code
   * dd.runOnMainSyncTimeout}.
   *
   * <p>This is a safer variation of {@link Instrumentation#runOnMainSync} because the latter may
   * hang. You may turn off this behavior by setting {@code "-e dd.runOnMainSyncTimeout 0"} on the
   * am command line.The {@code callable} may never run, for example, if the main Looper has exited
   * due to uncaught exception.
   */
  public static <V> V runOnMainSyncWithTimeout(Callable<V> callable) {
    checkNotMainThread();
    final RunOnMainSyncFutureTask<V> futureTask = new RunOnMainSyncFutureTask<>(callable);

    if (runOnMainSyncTimeoutMillis <= 0L) {
      // Call runOnMainSync on current thread without time limit.
      futureTask.runOnMainSyncNoThrow();
    } else {
      RUN_ON_MAIN_SYNC_EXECUTOR.execute(
          new Runnable() {
            @Override
            public void run() {
              futureTask.runOnMainSyncNoThrow();
            }
          });
    }

    try {
      return futureTask.get(runOnMainSyncTimeoutMillis, TimeUnit.MILLISECONDS);
    } catch (java.util.concurrent.TimeoutException e) {
      throw new TimeoutException(
          "Timed out after "
              + runOnMainSyncTimeoutMillis
              + " milliseconds waiting for Instrumentation.runOnMainSync",
          e);
    } catch (Throwable t) {
      throw DroidDriverException.propagate(t);
    } finally {
      futureTask.cancel(false);
    }
  }

  public static void checkMainThread() {
    if (Looper.myLooper() != Looper.getMainLooper()) {
      throw new DroidDriverException("This method must be called on the main thread");
    }
  }

  public static void checkNotMainThread() {
    if (Looper.myLooper() == Looper.getMainLooper()) {
      throw new DroidDriverException("This method cannot be called on the main thread");
    }
  }

  private static class RunOnMainSyncFutureTask<V> extends FutureTask<V> {
    public RunOnMainSyncFutureTask(Callable<V> callable) {
      super(callable);
    }

    public void runOnMainSyncNoThrow() {
      try {
        getInstrumentation().runOnMainSync(this);
      } catch (Throwable e) {
        setException(e);
      }
    }
  }
}