下面列出了怎么用android.support.test.uiautomator.UiDevice的API类实例代码及写法,或者点击链接到github查看源代码。
@Before
public void startMainActivityFromHomeScreen() {
mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
mDevice.pressHome();
final String launcherPackage = mDevice.getLauncherPackageName();
assertThat(launcherPackage, notNullValue());
mDevice.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)),
LAUNCH_TIMEOUT);
Context context = InstrumentationRegistry.getContext();
final Intent intent = context.getPackageManager().getLaunchIntentForPackage(TARGET_PACKAGE);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
context.startActivity(intent);
mDevice.wait(Until.hasObject(By.pkg(TARGET_PACKAGE).depth(0)), LAUNCH_TIMEOUT);
}
@Before
public void startMainActivityFromHomeScreen() {
mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
mDevice.pressHome();
final String launcherPackage = mDevice.getLauncherPackageName();
assertThat(launcherPackage, notNullValue());
mDevice.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)),
LAUNCH_TIMEOUT);
Context context = InstrumentationRegistry.getContext();
final Intent intent = context.getPackageManager().getLaunchIntentForPackage(TARGET_PACKAGE);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
context.startActivity(intent);
mDevice.wait(Until.hasObject(By.pkg(TARGET_PACKAGE).depth(0)), LAUNCH_TIMEOUT);
}
@Before
public void startMainActivityFromHomeScreen() {
mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
mDevice.pressHome();
final String launcherPackage = mDevice.getLauncherPackageName();
assertThat(launcherPackage, notNullValue());
mDevice.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)),
LAUNCH_TIMEOUT);
Context context = InstrumentationRegistry.getContext();
final Intent intent = context.getPackageManager().getLaunchIntentForPackage(TARGET_PACKAGE);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
context.startActivity(intent);
mDevice.wait(Until.hasObject(By.pkg(TARGET_PACKAGE).depth(0)), LAUNCH_TIMEOUT);
}
@Before
public void startMainActivityFromHomeScreen() {
mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
mDevice.pressHome();
final String launcherPackage = mDevice.getLauncherPackageName();
assertThat(launcherPackage, notNullValue());
mDevice.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)),
LAUNCH_TIMEOUT);
Context context = InstrumentationRegistry.getContext();
final Intent intent = context.getPackageManager().getLaunchIntentForPackage(TARGET_PACKAGE);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
context.startActivity(intent);
mDevice.wait(Until.hasObject(By.pkg(TARGET_PACKAGE).depth(0)), LAUNCH_TIMEOUT);
}
@Before
public void startMainActivityFromHomeScreen() {
mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
mDevice.pressHome();
final String launcherPackage = mDevice.getLauncherPackageName();
assertThat(launcherPackage, notNullValue());
mDevice.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)),
LAUNCH_TIMEOUT);
Context context = InstrumentationRegistry.getContext();
final Intent intent = context.getPackageManager().getLaunchIntentForPackage(TARGET_PACKAGE);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
context.startActivity(intent);
mDevice.wait(Until.hasObject(By.pkg(TARGET_PACKAGE).depth(0)), LAUNCH_TIMEOUT);
}
@Before
public void startMainActivityFromHomeScreen() {
mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
mDevice.pressHome();
final String launcherPackage = mDevice.getLauncherPackageName();
assertThat(launcherPackage, notNullValue());
mDevice.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)),
LAUNCH_TIMEOUT);
Context context = InstrumentationRegistry.getContext();
final Intent intent = context.getPackageManager().getLaunchIntentForPackage(TARGET_PACKAGE);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
context.startActivity(intent);
mDevice.wait(Until.hasObject(By.pkg(TARGET_PACKAGE).depth(0)), LAUNCH_TIMEOUT);
}
@Before
public void startMainActivityFromHomeScreen() {
// Initialize UiDevice instance
mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
// Start from the home screen
mDevice.pressHome();
// Wait for launcher
final String launcherPackage = mDevice.getLauncherPackageName();
Assert.assertThat(launcherPackage, CoreMatchers.notNullValue());
mDevice.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)),
LAUNCH_TIMEOUT);
// Launch the app
Context context = InstrumentationRegistry.getContext();
final Intent intent = context.getPackageManager()
.getLaunchIntentForPackage(BASIC_SAMPLE_PACKAGE);
// Clear out any previous instances
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
context.startActivity(intent);
// Wait for the app to appear
mDevice.wait(Until.hasObject(By.pkg(BASIC_SAMPLE_PACKAGE).depth(0)),
LAUNCH_TIMEOUT);
}
private static UiObject2 getAlertButton(String alertType) throws Exception {
UiDevice mDevice = Elements.getGlobal().getmDevice();
int buttonIndex;
if (alertType.equals("accept")) {
buttonIndex = 1;
} else if (alertType.equals("dismiss")) {
buttonIndex = 0;
} else {
throw new Exception("alertType can only be 'accept' or 'dismiss'");
}
List<UiObject2> alertButtons = mDevice.findObjects(By.clazz("android.widget.Button").clickable(true).checkable(false));
if (alertButtons.size() == 0) {
return null;
}
UiObject2 alertButton = alertButtons.get(buttonIndex);
return alertButton;
}
@Override
public NanoHTTPD.Response get(RouterNanoHTTPD.UriResource uriResource, Map<String, String> urlParams, NanoHTTPD.IHTTPSession session) {
String sessionId = urlParams.get("sessionId");
Map<String, String> body = new HashMap<String, String>();
UiDevice mDevice = Elements.getGlobal().getmDevice();
JSONObject result = null;
try {
session.parseBody(body);
String postData = body.get("postData");
JSONObject jsonObj = JSON.parseObject(postData);
JSONArray keycodes = (JSONArray)jsonObj.get("value");
for (Iterator iterator = keycodes.iterator(); iterator.hasNext();) {
int keycode = (int) iterator.next();
mDevice.pressKeyCode(keycode);
}
return NanoHTTPD.newFixedLengthResponse(getStatus(), getMimeType(), new Response(result, sessionId).toString());
} catch (Exception e) {
return NanoHTTPD.newFixedLengthResponse(getStatus(), getMimeType(), new Response(Status.UnknownError, sessionId).toString());
}
}
public void allowPermissionsIfNeeded() {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
sleep(PERMISSIONS_DIALOG_DELAY);
UiDevice device = UiDevice.getInstance(getInstrumentation());
UiSelector selector = new UiSelector()
.clickable(true)
.checkable(false)
.index(GRANT_BUTTON_INDEX);
UiObject allowPermissions = device.findObject(selector);
if (allowPermissions.exists()) {
allowPermissions.click();
}
}
} catch (UiObjectNotFoundException e) {
System.out.println("There is no permissions dialog to interact with");
}
}
public void allowPermissionsIfNeeded() {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
sleep(PERMISSIONS_DIALOG_DELAY);
UiDevice device = UiDevice.getInstance(getInstrumentation());
UiObject allowPermissions = device.findObject(new UiSelector()
.clickable(true)
.checkable(false)
.index(GRANT_BUTTON_INDEX));
if (allowPermissions.exists()) {
allowPermissions.click();
}
}
} catch (UiObjectNotFoundException e) {
System.out.println("There is no permissions dialog to interact with");
}
}
@Ignore
@Test
public void testUiAutomatorAPI() throws UiObjectNotFoundException, InterruptedException {
UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
UiSelector editTextSelector = new UiSelector().className("android.widget.EditText").text("this is a test").focusable(true);
UiObject editTextWidget = device.findObject(editTextSelector);
editTextWidget.setText("this is new text");
Thread.sleep(2000);
UiSelector buttonSelector = new UiSelector().className("android.widget.Button").text("CLICK ME").clickable(true);
UiObject buttonWidget = device.findObject(buttonSelector);
buttonWidget.click();
Thread.sleep(2000);
}
public static boolean handleCommonDialog() {
UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
UiObject button = null;
for (String keyword : Config.COMMON_BUTTONS) {
button = device.findObject(new UiSelector().text(keyword).enabled(true));
if (button != null && button.exists()) {
break;
}
}
try {
// sometimes it takes a while for the OK button to become enabled
if (button != null && button.exists()) {
button.waitForExists(5000);
button.click();
Log.i("AppCrawlerAction", "{Click} " + button.getText() + " Button succeeded");
return true; // triggered
}
} catch (UiObjectNotFoundException e) {
Log.w(TAG, "UiObject disappear");
}
return false; // no trigger
}
public static void inputRandomTextToEditText() {
UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
UiObject edit = null;
int i = 0;
do {
edit = null;
edit = device.findObject(new UiSelector().className("android.widget.EditText").instance(i++));
if (edit != null && edit.exists()) {
try {
Random rand = new Random();
String text = Config.RANDOM_TEXT[rand.nextInt(Config.RANDOM_TEXT.length - 1)];
edit.setText(text);
} catch (UiObjectNotFoundException e) {
// Don't worry
}
}
} while (edit != null && edit.exists());
}
private DeviceInfo() {
this._sdkInt = android.os.Build.VERSION.SDK_INT;
UiDevice ud = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
this._currentPackageName = ud.getCurrentPackageName();
this._displayWidth = ud.getDisplayWidth();
this._displayHeight = ud.getDisplayHeight();
this._displayRotation = ud.getDisplayRotation();
this._productName = ud.getProductName();
this._naturalOrientation = ud.isNaturalOrientation();
this._displaySizeDpX = ud.getDisplaySizeDp().x;
this._displaySizeDpY = ud.getDisplaySizeDp().y;
try {
this._screenOn = ud.isScreenOn();
} catch (RemoteException e) {
e.printStackTrace();
Log.e(e.getMessage());
}
}
@Before
public void startMainActivityFromHomeScreen() {
// Initialize UiDevice instance
device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
// Start from the home screen
device.pressHome();
// Wait for launcher
final String launcherPackage = getLauncherPackageName();
MatcherAssert.assertThat(launcherPackage, IsNull.notNullValue());
device.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)), LAUNCH_TIMEOUT);
// Launch the app
Context context = InstrumentationRegistry.getContext();
final Intent intent = context.getPackageManager()
.getLaunchIntentForPackage(APP_PACKAGE_NAME);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); // Clear out any previous instances
context.startActivity(intent);
// Wait for the app to appear
device.wait(Until.hasObject(By.pkg(APP_PACKAGE_NAME).depth(0)), LAUNCH_TIMEOUT);
}
/**
* When using UiAutomator you can interact with ui elements outside of your own process.
* You can start your application by pressing the home button of the device and launch the
* target app through the android launcher.
*
* <p>
* If you only want to launch and test a single {@link Activity} you can use {@link
* Instrumentation} directly to only launch the target {@link Activity}
* </p>
*/
@Before
public void startBlueprintActivityFromHomeScreen() {
// Initialize UiDevice instance
mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
// Start from the home screen
mDevice.pressHome();
// Wait for launcher
final String launcherPackage = getLauncherPackageName();
assertThat(launcherPackage, notNullValue());
mDevice.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)), LAUNCH_TIMEOUT);
// Launch the blueprint app
Context context = InstrumentationRegistry.getContext();
final Intent intent = context.getPackageManager().getLaunchIntentForPackage(TARGET_PACKAGE);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); // Clear out any previous instances
context.startActivity(intent);
// Wait for the app to appear
mDevice.wait(Until.hasObject(By.pkg(TARGET_PACKAGE).depth(0)), LAUNCH_TIMEOUT);
}
public static boolean viewExistsContains(UiDevice device, String... textToMatch) throws UiObjectNotFoundException
{
if (textToMatch == null || textToMatch.length < 1)
{
return false;
}
UiObject view;
boolean contains = false;
for (int i = 0; i < textToMatch.length; i++)
{
view = device.findObject(new UiSelector().textContains(textToMatch[i]));
contains = view.exists();
if (contains) return true;
}
return false;
}
private void allowPermissionsIfNeeded() {
if (Build.VERSION.SDK_INT >= 23) {
// Initialize UiDevice instance
UiDevice uiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
// notice that we typically receive 2-3 permission prompts, hence the loop
while (true) {
UiObject allowPermissions = uiDevice.findObject(new UiSelector().text("Allow"));
if (allowPermissions.exists()) {
try {
allowPermissions.click();
} catch (UiObjectNotFoundException e) {
e.printStackTrace();
Log.e(TAG, "There is no permissions dialog to interact with ");
}
} else {
break;
}
}
}
}
public static boolean viewExistsContains(UiDevice device, String... textToMatch) throws UiObjectNotFoundException
{
if (textToMatch == null || textToMatch.length < 1)
{
return false;
}
UiObject view;
boolean contains = false;
for (int i = 0; i < textToMatch.length; i++)
{
view = device.findObject(new UiSelector().textContains(textToMatch[i]));
contains = view.exists();
if (contains) return true;
}
return false;
}
public static void handleBluetoothEnablerDialogs(UiDevice uiDevice, Activity activity) throws UiObjectNotFoundException
{
if (viewExistsExact(uiDevice, "Bluetooth permission request"))
{
if (viewExistsExact(uiDevice, "ALLOW"))
{
clickButton(uiDevice, "ALLOW");
}
else if (viewExistsExact(uiDevice, "Yes"))
{
clickButton(uiDevice, "Yes");
}
}
if (viewExistsExact(uiDevice, P_StringHandler.getString(activity, P_StringHandler.REQUIRES_LOCATION_PERMISSION)))
{
clickButton(uiDevice, P_StringHandler.getString(activity, P_StringHandler.ACCEPT));
}
if (viewExistsContains(uiDevice, "Allow", "access this device's location") && UIUtil.viewExistsExact(uiDevice, "ALLOW") && UIUtil.viewExistsExact(uiDevice, "DENY"))
{
clickButton(uiDevice, "ALLOW");
}
}
@Override
public NanoHTTPD.Response get(RouterNanoHTTPD.UriResource uriResource, Map<String, String> urlParams, NanoHTTPD.IHTTPSession session) {
String sessionId = urlParams.get("sessionId");
try {
UiDevice mDevice = Elements.getGlobal().getmDevice();
Integer width = mDevice.getDisplayWidth();
Integer height = mDevice.getDisplayHeight();
JSONObject size = new JSONObject();
size.put("width", width);
size.put("height", height);
return NanoHTTPD.newFixedLengthResponse(getStatus(), getMimeType(), new Response(size, sessionId).toString());
} catch(Exception e) {
return NanoHTTPD.newFixedLengthResponse(getStatus(), getMimeType(), new Response(Status.UnknownError, sessionId).toString());
}
}
public void skipPermission(JSONArray permissionPatterns, int scanningCount) {
UiDevice mDevice = Elements.getGlobal().getmDevice();
// if permission list is empty, avoid execution
if (permissionPatterns.size() == 0) {
return;
}
// regular check for permission scanning
try {
for (int i = 0; i < scanningCount; i++) {
inner:
for (int j = 0; j < permissionPatterns.size(); j++) {
String text = permissionPatterns.getString(j);
UiObject object = mDevice.findObject(new UiSelector().text(text));
if (object.exists()) {
object.click();
break inner;
}
}
Thread.sleep(3000);
}
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.println(e.getCause().toString());
}
}
@Before
public void setUp() throws InterruptedException {
Thread.sleep(WAIT_TEST_MANAGER);
instrumentation = InstrumentationRegistry.getInstrumentation();
activity = testRule.getActivity();
uiDevice = UiDevice.getInstance(instrumentation);
}
public static void allowPermissionsIfNeeded(UiDevice device) {
if (Build.VERSION.SDK_INT >= 23) {
UiObject allowPermissions = device.findObject(new UiSelector().text(TEXT_ALLOW));
if (allowPermissions.exists()) {
try {
allowPermissions.click();
} catch (UiObjectNotFoundException ignored) {
}
}
}
}
@Test
public void d() throws UiObjectNotFoundException {
// Initialize UiDevice instance
mDevice = UiDevice.getInstance(getInstrumentation());
// Perform a short press on the HOME button
mDevice.pressHome();
// Bring up the default launcher by searching for
// a UI component that matches the content-description for the launcher button
UiObject allAppsButton = mDevice.findObject(new UiSelector().description("Apps"));
// Perform a click on the button to bring up the launcher
allAppsButton.clickAndWaitForNewWindow();
}
protected void click(String targetId) {
UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
UiObject button = device.findObject(new UiSelector().resourceId(targetId));
try {
button.waitForExists(3000);
button.click();
} catch (UiObjectNotFoundException e) {
throw new IllegalStateException(e);
}
}
@Test
public void testUiDevice() throws RemoteException {
UiDevice device = UiDevice.getInstance(
InstrumentationRegistry.getInstrumentation());
if (device.isScreenOn()) {
device.setOrientationLeft();
device.openNotification();
}
}
/**
* <i>The tests have to start from the screen home</i>
*/
@BeforeClass
public static void start(){
l("AbstractTest","@BeforeClass start");
UiDevice d = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
d.pressHome();
}
/**
* <i>The device should be at its initial state when all tests are done</i>
*/
@AfterClass
public static void end(){
l("AbstractTest","@AfterClass end");
UiDevice d = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
d.pressHome();
}