Wednesday, April 2, 2014

UiAutomator简介(2)

在这篇,会详细介绍UiAutomator怎么获取app的信息


首先,用uiautomator分析页面元素(uiautomatorviewer.bat under tools in android sdk)



旧版uiautomator用class来定位,新版更准确,可以用resourceId来定位


下面说说代码

package com;
import com.android.uiautomator.core.UiObject;
import com.android.uiautomator.core.UiObjectNotFoundException;
import com.android.uiautomator.core.UiScrollable;
import com.android.uiautomator.core.UiSelector;
import com.android.uiautomator.testrunner.UiAutomatorTestCase;

public class Runner extends UiAutomatorTestCase {

  public void testDemo() throws UiObjectNotFoundException {
   
     // Simulate a short press on the HOME button.
     getUiDevice().pressHome();
   
     UiScrollable appViews = new UiScrollable(new UiSelector()
        .scrollable(true));
   
     UiObject carmaxApp = appViews.getChildByText(new UiSelector()
        .className(android.widget.TextView.class.getName()),
        "CarMax",true);
     carmaxApp.clickAndWaitForNewWindow();
     try
     {
     Thread.sleep(3000);
     }
     catch (InterruptedException e1) {
       e1.printStackTrace();
     }
   
     //getUiDevice().click(721,589);
     new UiObject(new UiSelector().className("android.widget.EditText")).setText("Blue");
     //new UiObject(new UiSelector().description("loginButton")).click();
 

     try
     {
     Thread.sleep(3000);
     }
     catch (InterruptedException e1) {
       e1.printStackTrace();
     }
     getUiDevice().pressEnter();
     getUiDevice().pressEnter();
   
     UiObject listCars = new UiObject(new UiSelector().className("android.widget.ListView"));
   
     for(int j=0;j<listCars.getChildCount()-1;j++)
  {
  //System.out.println("index:"+j);
  UiObject objName = new UiObject(new UiSelector().className("android.widget.TextView").instance(j));
        String name = objName.getText();
        System.out.println(name);

  }

 }

}



这里是打开carmax这个app,然后输入blue关键字进行搜索,再打印第一页的汽车名字。
uiautomator api的reference: http://developer.android.com/tools/help/uiautomator/index.html

reference:
androd key events:
http://developer.android.com/reference/android/view/KeyEvent.html

No comments:

Post a Comment