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
17package com.google.android.droiddriver.uiautomation;
18
19import android.app.Instrumentation;
20import android.app.UiAutomation;
21import android.view.accessibility.AccessibilityNodeInfo;
22
23import com.google.android.droiddriver.base.DroidDriverContext;
24import com.google.android.droiddriver.exceptions.UnrecoverableException;
25
26public class UiAutomationContext extends
27    DroidDriverContext<AccessibilityNodeInfo, UiAutomationElement> {
28  private final UiAutomation uiAutomation;
29
30  public UiAutomationContext(Instrumentation instrumentation, UiAutomationDriver driver) {
31    super(instrumentation, driver);
32    this.uiAutomation = instrumentation.getUiAutomation();
33  }
34
35  @Override
36  public UiAutomationDriver getDriver() {
37    return (UiAutomationDriver) super.getDriver();
38  }
39
40  public interface UiAutomationCallable<T> {
41    T call(UiAutomation uiAutomation);
42  }
43
44  /**
45   * Wraps calls to UiAutomation API. Currently supports fail-fast if
46   * UiAutomation throws IllegalStateException, which occurs when the connection
47   * to UiAutomation service is lost.
48   */
49  public <T> T callUiAutomation(UiAutomationCallable<T> uiAutomationCallable) {
50    try {
51      return uiAutomationCallable.call(uiAutomation);
52    } catch (IllegalStateException e) {
53      throw new UnrecoverableException(e);
54    }
55  }
56}
57