uiautomator中一些常用的方法
来源:互联网 发布:经常性失眠的原因 知乎 编辑:程序博客网 时间:2024/06/06 04:50
package com.sprd.uiautomator.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Random;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.json.JSONArray;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Environment;
import android.os.RemoteException;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.view.InputDevice;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import com.android.uiautomator.core.UiCollection;
import com.android.uiautomator.core.UiDevice;
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.core.UiWatcher;
import com.android.uiautomator.testrunner.UiAutomatorTestCase;
import com.sprd.uiautomator.camera.CameraUtils.SWIPEDIRECTION;
public class UiUtil extends UiAutomatorTestCase {
public static String TAG = "testlog";
// private static final String path_screenshot =
// "/storage/sdcard0/slog/screenshot/";
private static final String dir_result = "result/";
private static final String dir_fail = "fail/";
private static final String path_screenshot = readConfig("path_screenshot");//getSDPath()+"/";
private static final String path_screenshot_result = path_screenshot
+ dir_result;
private static final String path_screenshot_fail = path_screenshot
+ dir_fail;
public static final String OWN_NUMBER_OF_SIM1 = readConfig("SIM1_Number");
public static final String OWN_NUMBER_OF_SIM2 = readConfig("SIM2_Number");
// public static final String TEST_CONTACT_NAME = readConfig("Contacts_Name");
public static final String TEST_CONTACT_NUMBER = readConfig("Contacts_Number");
// ningbiao
public static final String ACCOUNT_NAME = readConfig("account_name");
public static final String ACCOUNT_PASSWORD = readConfig("account_password");
// ningbiao
public static final String TEST_RECIPIENTS = OWN_NUMBER_OF_SIM1;
// public static final String TEST_MESSAGE = readConfig("Message_Test_Content");
public static final int RES_CONFIG = 0;
public static final String RES_CONFIG_FILE = "config.xml";
public static final int RES_RESOURCE = 1;
public static final String RES_RESOURCE_FILE = "resource.xml";
public static final String RES_RESOURCE_FILE_EN = "resource-EN.xml";
public static final String RES_CONFIG_FOLER_CASE = "config_hq_uiautotest";
public static final String RES_CONFIG_PATH = "/data/local/tmp/"
+ RES_CONFIG_FOLER_CASE + "/";
public static enum SIM_SELECT_TYPE {
DATACONNECT, CALL, VIDEOCALL, MMS
}
public static enum CALL_SIM_TYPE {
SIM1, SIM2
}
public static enum PREFERRED_NETWORK_TYPE {
AUTO, GSM_ONLY, WCDMA_ONLY, TD_ONLY, LTE_ONLY
}
protected void setUp() throws Exception {
super.setUp();
// addWatcher();
// checkFirstPowerOn();
}
protected void tearDown() throws Exception {
// releaseAllWatcher();
super.tearDown();
}
// ningbiao add begin
private static String[][] setupWizard = {
// welcome
{ "Welcome", "com.google.android.setupwizard:id/start", "2" },
// when there is no sim cards
{
"Insert SIM cards",
"com.google.android.setupwizard:id/setup_wizard_navbar_next",
"2" },
// select prime sim card
{
"Select a SIM for cellular data",
"com.google.android.setupwizard:id/setup_wizard_navbar_next",
"2" },
// select sim for calls
{
"Select a SIM for calls",
"com.google.android.setupwizard:id/setup_wizard_navbar_next",
"2" },
// select sim for sms
{
"Select a SIM for text messages",
"com.google.android.setupwizard:id/setup_wizard_navbar_next",
"2" },
// select wifi hotpot
{ "Select Wi‑Fi network",
"com.android.settings:id/setup_wizard_navbar_next", "2" },
// skip wifi connect
{ "Skip anyway", "android:id/button1", "2" },
// connect check
{
"Checking connection…",
"com.google.android.setupwizard:id/setup_wizard_navbar_next",
"30" },
// connect skip
{ "Skip anyway", "android:id/button1", "2" },
// when there is no sim cards
{
"Date & time",
"com.google.android.setupwizard:id/setup_wizard_navbar_next",
"2" },
// input name
{
"Name",
"com.google.android.setupwizard:id/setup_wizard_navbar_next",
"10" },
// more
{
"Google services",
"com.google.android.setupwizard:id/setup_wizard_navbar_next",
"2" },
// more
{
"Google services",
"com.google.android.setupwizard:id/setup_wizard_navbar_next",
"2" },
// next
{
"Google services",
"com.google.android.setupwizard:id/setup_wizard_navbar_next",
"2" },
// welcome
{
"Welcome",
"com.google.android.googlequicksearchbox:id/cling_dismiss_longpress_info",
"2" },
// welcome(has not GMS)
{ "Welcome",
"com.android.launcher3:id/cling_dismiss_longpress_info",
"2" } };
private static void checkCardSel() throws UiObjectNotFoundException {
loginfo(TAG, "checkCardSel");
UiObject objCardSel = findByText("Select primary card");
UiObject objCardSelCN = findByText("主卡选择");
if (objCardSel.exists() || objCardSelCN.exists()) {
loginfo(TAG, "find primary card");
UiObject objTopItem = findById("android:id/select_dialog_listview")
.getChild(
new UiSelector().className(
"android.widget.LinearLayout").index(0));
if (objTopItem.exists()) {
objTopItem.click();
}
}
}
private static void checkUsbPrompt() throws UiObjectNotFoundException {
loginfo(TAG, "checkUsbPrompt");
UiObject usbTitle = findByText("USB computer connection");
if (usbTitle.exists()) {
pressBack();
}
}
private static void keepBackLightOn() {
try {
if (!isScreenOn()) {
// UiDevice.getInstance().pressKeyCode(26);
UiDevice.getInstance().wakeUp();
}
} catch (Exception e) {
}
}
private boolean clickNextIfExistByTitleAndId(String title, String id,
int timeout) throws UiObjectNotFoundException {
// if(title.equals("Name")){
// Configurator.getInstance().setWaitForIdleTimeout(5 * 1000);
// }else{
// Configurator.getInstance().setWaitForIdleTimeout(10 * 1000);
// }
// UiObject objTitle = findByTextContains(title);
UiObject objId = findById(id);
loginfo(TAG, "check next title:" + title + ",id:" + id + ",timeout:"
+ timeout);
while (timeout-- >= 0) {
Sleep(1000);
onScreen();
// if (!objTitle.exists()) {
// // keepBackLightOn();
// loginfo(TAG, "!objTitle.exists() timeout:" + timeout);
// continue;
// }
if (!objId.exists()) {
// keepBackLightOn();
loginfo(TAG, "!objId.exists() timeout:" + timeout);
continue;
}
if (!objId.isEnabled()) {
// keepBackLightOn();
loginfo(TAG, "!objId.isEnabled() timeout:" + timeout);
continue;
}
objId.clickAndWaitForNewWindow();
return true;
}
return false;
}
private void clickSetupWizard() throws UiObjectNotFoundException,
RemoteException {
loginfo(TAG, "clickSetupWizard start...");
for (int i = 0; i < setupWizard.length; i++) {
loginfo(TAG, "check " + setupWizard[i][0]);
onScreen();
boolean result = clickNextIfExistByTitleAndId(setupWizard[i][0],
setupWizard[i][1], Integer.parseInt(setupWizard[i][2]));
if (!result && i == 0) {
loginfo(TAG,
"clickSetupWizard first welcome ui result is false!");
break;
}
}
loginfo(TAG, "clickSetupWizard end...");
}
public void checkFirstPowerOn() throws Exception {
loginfo(TAG, "checkFirstPowerOn");
updateLanguage(Locale.ENGLISH);
sleep(2000);
onScreen();
clickSetupWizard();
loginfo(TAG, "checkFirstPowerOn.........");
}
public void checkLongpress() throws Exception {
int length = setupWizard.length;
loginfo(TAG, "checkLongpress length=" + length);
if (length <= 0) {
return;
}
clickNextIfExistByTitleAndId(setupWizard[length - 1][0],
setupWizard[length - 1][1],
Integer.parseInt(setupWizard[length - 1][2]));
}
public static boolean checkInLauncher() throws UiObjectNotFoundException {
onScreen();
boolean searchBox = checkObjectExistsByID("com.google.android.googlequicksearchbox:id/search_plate");
boolean appsButton = checkObjectExistsByTextDesc(readResResource("ui_text_application")) && false;
boolean nativeLauncherPackage = checkObjectExistsByPackage("com.android.launcher3");
loginfo(TAG, "checkInLauncher searchBox=" + searchBox + ",appsButton="
+ appsButton + ",nativeLauncherPackage="
+ nativeLauncherPackage);
return searchBox || appsButton || nativeLauncherPackage;
}
public void addWatcher() throws Exception {
addWatcher(
"selectPrimaryCard",
findByText("Select primary card"),
findById("android:id/select_dialog_listview").getChild(
new UiSelector().className(
"android.widget.LinearLayout").index(0)));
addWatcher(
"selectPrimaryCardCN",
findByText("主卡选择"),
findById("android:id/select_dialog_listview").getChild(
new UiSelector().className(
"android.widget.LinearLayout").index(0)));
addWatcher(
"launcherWelcome",
findById("com.android.launcher3:id/cling_dismiss_longpress_info"),
findById("com.android.launcher3:id/cling_dismiss_longpress_info"));
addWatcher(
"launcherWelcomeGMS",
findById("com.google.android.googlequicksearchbox:id/cling_dismiss_longpress_info"),
findById("com.google.android.googlequicksearchbox:id/cling_dismiss_longpress_info"));
addWatcher("skipAnyway", findByText("Skip anyway"),
findById("android:id/button1"));
addWatcher(
"navbarNext",
findById("com.google.android.setupwizard:id/setup_wizard_navbar_next"),
findById("com.google.android.setupwizard:id/setup_wizard_navbar_next"));
addWatcher("skipNext",
findById("com.android.settings:id/setup_wizard_navbar_next"),
findById("com.android.settings:id/setup_wizard_navbar_next"));
addWatcher("wizardStart",
findById("com.google.android.setupwizard:id/start"),
findById("com.google.android.setupwizard:id/start"));
addWatcher("simNotify1", findByText("com.android.stk1:id/button_ok"),
findById("com.android.stk1:id/button_ok"));
addWatcher("simNotify2", findByText("com.android.stk2:id/button_ok"),
findById("com.android.stk2:id/button_ok"));
addWatcherCheckable("Aceptar", findByText("No volver a mostrar"),
findByText("Aceptar"));
}
public void releaseAllWatcher() throws Exception {
realeseWatcher("selectPrimaryCard");
realeseWatcher("selectPrimaryCardCN");
realeseWatcher("launcherWelcome");
realeseWatcher("launcherWelcomeGMS");
realeseWatcher("skipAnyway");
realeseWatcher("navbarNext");
realeseWatcher("skipNext");
realeseWatcher("wizardStart");
realeseWatcher("simNotify1");
realeseWatcher("simNotify2");
realeseWatcher("Aceptar");
}
// ningbiao add end
public static enum SHARE_TYPE {
MESSAGING, EMAIL, BLUETOOTH, GMAIL
}
/**
* 电话:com.android.dialer/com.android.dialer.DialtactsActivity
* 联系�?com.android.contacts/com.android.contacts.activities.PeopleActivity
* 信息:com.android.mms/.ui.ConversationList
* 浏览�?com.android.browser/.BrowserActivity
* 设置:com.android.settings/.Settings
*/
public static void openAppBypkgName(String name) {
try {
String pkgname = "";
if (name == "Dialer"
|| TextUtils.equals(name,
readResResource("phone_text_app_name"))) {
pkgname = "com.android.dialer/com.android.dialer.DialtactsActivity";
} else if (name == "People"
|| TextUtils.equals(name,
readResResource("contact_text_app_name_contacts"))
|| TextUtils.equals(name,
readResResource("contact_text_app_name"))) {
pkgname = "com.android.contacts/com.android.contacts.activities.PeopleActivity";
} else if (name == "Messaging"
|| TextUtils.equals(name,
readResResource("mms_text_app_name"))) {
pkgname = "com.android.mms/com.android.mms.ui.ConversationList";
} else if (name == "Browser"
|| TextUtils.equals(name,
readResResource("ui_text_browser"))) {
pkgname = "com.android.browser/.BrowserActivity";
} else if (name == "Settings"
|| TextUtils.equals(name,
readResResource("ui_text_setting"))) {
pkgname = "com.android.settings/.Settings";
} else if (name == "Calculator"
|| TextUtils.equals(name,
readResResource("ui_text_calculator"))) {
pkgname = "com.android.calculator2/.Calculator";
} else if (name == "Calendar"
|| TextUtils.equals(name,
readResResource("calendar_text_app_name"))) {
pkgname = "com.android.calendar/.AllInOneActivity";
} else if (name == "Camera"
|| TextUtils.equals(name,
readResResource("camera_text_app_name"))) {
pkgname = "com.android.camera2/com.android.camera.CameraLauncher";
} else if (name == readResResource("clock_text_app_name")) {
pkgname = "com.android.deskclock/.DeskClock";
} else if (name == "FileExplore"
|| TextUtils.equals(name,
readResResource("fileexplorer_text_app_name"))) {
pkgname = "com.sprd.fileexplorer/.activities.FileExploreActivity";
} else if (name == "Gallery"
|| TextUtils.equals(name,
readResResource("gallery_text_app_name"))) {
pkgname = "com.android.gallery3d/.app.GalleryActivity";
} else if (name == "Music"
|| TextUtils.equals(name, readResResource("ui_text_music"))) {
pkgname = "com.android.music/.MusicBrowserActivity";
} else if (name == "SoundRecorder"
|| TextUtils
.equals(name, readResResource("ui_text_record"))) {
pkgname = "com.android.soundrecorder/.SoundRecorder";
} else if (name == "Email") {
pkgname = "com.android.email/.activity.Welcome";
} else if (name == "FmRadio"
|| TextUtils.equals(name, readResResource("ui_text_fm"))) {
pkgname = "com.thunderst.radio/.FMRadioMainActivity";
} else if (name == "CallLog"
|| TextUtils.equals(name,
readResResource("calllog_text_app_name"))) {
pkgname = "com.android.dialer/com.android.dialer.calllog.CallLogActivity";
} else if (name == "Email"
|| TextUtils.equals(name,
readResResource("email_text_app_name"))) {
pkgname = "com.android.email/.activity.Welcome";
}
UiDevice.getInstance().pressHome();
UiUtil.Sleep(1000);
execCommand("am start -n " + pkgname);
UiUtil.Sleep(3000);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
// checkPoint("openApp", false);
}
}
// 通过ID查找
public static UiObject findById(String text)
throws UiObjectNotFoundException {
UiObject appBtn = new UiObject(new UiSelector().resourceId(text));
return appBtn;
}
// 通过resource和descrice查找
public static UiObject findByResourceIdAndDesc(String className, String text)
throws UiObjectNotFoundException {
UiObject appBtn = new UiObject(new UiSelector().resourceId(className)
.description(text));
return appBtn;
}
// 按Text Contains定位
public static UiObject findByTextContains(String text) {
UiObject getItem = new UiObject(new UiSelector().textContains(text));
return getItem;
}
// 通过resource和index查找
public static UiObject findByResourceIdAndIndex(String className, int index)
throws UiObjectNotFoundException {
UiObject appBtn = new UiObject(new UiSelector().resourceId(className)
.index(index));
return appBtn;
}
// 通过ID,instance查找
public static UiObject findByIdInStance(String text, int index)
throws UiObjectNotFoundException {
UiObject appBtn = new UiObject(new UiSelector().resourceId(text)
.instance(index));
return appBtn;
}
// 通过ID,index查找
public static UiObject findByIdIndex(String text, int index)
throws UiObjectNotFoundException {
UiObject appBtn = new UiObject(new UiSelector().resourceId(text).index(
index));
return appBtn;
}
// 通过Uisourceid查找
public static UiObject findByResourceId(String text)
throws UiObjectNotFoundException {
UiObject appBtn = new UiObject(new UiSelector().resourceId(text));
return appBtn;
}
// 按照className查找UiScrollable;
public static UiScrollable findUiScrollableByClassName(String className)
throws UiObjectNotFoundException {
UiScrollable scrItem = new UiScrollable(
new UiSelector().className(className));
return scrItem;
}
// 通过source和text查找
public static UiObject findByResourceIdAndText(String text1, String text2)
throws UiObjectNotFoundException {
UiObject appBtn = new UiObject(new UiSelector().resourceId(text1).text(
text2));
return appBtn;
}
// 通过source和text查找
public static UiObject findByResourceIdAndTextContains(String resourceId, String textContains)
throws UiObjectNotFoundException {
UiObject appBtn = new UiObject(new UiSelector().resourceId(resourceId).textContains(
textContains));
return appBtn;
}
// 按照className和index在UiScrollable中查找
public static UiScrollable findUiScrollableByClassNameAndInstance(
UiScrollable uiScrollable, String className, int index)
throws UiObjectNotFoundException {
UiScrollable scrItem = new UiScrollable(new UiSelector().className(
className).instance(index));
return scrItem;
}
// 获取UiCollection中的子对象的个数
public static int findChildCountFromUiCollectionByClassName(
UiCollection uiCollection, String className)
throws UiObjectNotFoundException {
return uiCollection
.getChildCount(new UiSelector().className(className));
}
// 在UiScrollable中通过className和instance查找
public static UiObject findFromUiScrollableByClassNameAndInstance(
UiScrollable uiScrollable, String className, int index)
throws UiObjectNotFoundException {
return uiScrollable.getChild(new UiSelector().className(className)
.index(index));
}
// 按className定位Scrollable
public static UiScrollable findScrollableByClass(String className) {
return new UiScrollable(new UiSelector().className(className));
}
// 按resource定位Scrollable
public static UiScrollable findScrollableByResource(String text) {
return new UiScrollable(new UiSelector().resourceId(text));
}
// 从UiScrollable得到子对象,通过className和instance
public static UiObject findChildFromUiScrollableByClassNameAndInstance(
UiScrollable scrollable, String className, int instance)
throws UiObjectNotFoundException {
return scrollable.getChild(new UiSelector().className(className)
.instance(instance));
}
// 从UiScrollable得到子对象,通过TEXT
public static UiObject findChildFromUiScrollableByText(
UiScrollable scrollable, String text)
throws UiObjectNotFoundException {
return scrollable.getChild(new UiSelector().text(text));
}
// 获得collection对象中的子元素个数,以className作为筛选标准
public static int findChildCountFromCollection(UiCollection collection,
String className) {
return collection.getChildCount(new UiSelector().className(className));
}
// 在UiScrollable中通过className查找
public static UiObject findFromUiScrollableByClassName(
UiScrollable uiScrollable, String className)
throws UiObjectNotFoundException {
return uiScrollable.getChild(new UiSelector().className(className));
}
// 通过resource查找UiCollection
public static UiCollection findUicollectionByResource(String text)
throws UiObjectNotFoundException {
UiCollection uiCollection = new UiCollection(
new UiSelector().resourceId(text));
return uiCollection;
}
// 通过test查找
public static UiObject findByText(String text)
throws UiObjectNotFoundException {
UiObject appBtn = new UiObject(new UiSelector().text(text));
return appBtn;
}
// 通过package查找
public static UiObject findByPackage(String text)
throws UiObjectNotFoundException {
UiObject appBtn = new UiObject(new UiSelector().packageName(text));
return appBtn;
}
// 通过description查找
public static UiObject findByDesc(String text)
throws UiObjectNotFoundException {
UiObject appBtn = new UiObject(new UiSelector().description(text));
return appBtn;
}
// 通过className查找
public static UiObject findByClassName(String className)
throws UiObjectNotFoundException {
UiObject appBtn = new UiObject(new UiSelector().className(className));
return appBtn;
}
// 通过className和index查找
public static UiObject findByClassNameAndIndex(String className, int index)
throws UiObjectNotFoundException {
UiObject appBtn = new UiObject(new UiSelector().className(className)
.index(index));
return appBtn;
}
// 通过className和text查找
public static UiObject findByClassNameAndText(String className, String text)
throws UiObjectNotFoundException {
UiObject appBtn = new UiObject(new UiSelector().className(className)
.text(text));
return appBtn;
}
// 通过descrice和index查找
public static UiObject findByDescContInstance(String text, int index)
throws UiObjectNotFoundException {
UiObject appBtn = new UiObject(new UiSelector().descriptionContains(
text).instance(index));
return appBtn;
}
// Sleep();
public static void Sleep(int ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
// 进入APPS
public static boolean openApp(String appName)
throws UiObjectNotFoundException {
loginfo(TAG, "openApp :" + appName);
try {
UiObject appButton;
appButton = findByText(appName);
if (appButton.exists()) {
appButton.clickAndWaitForNewWindow();
} else {
UiObject appBtn = findByDesc(readResResource("ui_text_application"));
if (appBtn.exists()) {
appBtn.clickAndWaitForNewWindow();
appButton = findByClassNameAndText(
"android.widget.TextView", appName);
if (!appButton.exists()) {
UiSelector uiselector = new UiSelector();
UiScrollable uiscrollable = new UiScrollable(
uiselector.scrollable(true));
uiscrollable.setAsHorizontalList();
uiscrollable.flingToBeginning(5);
int count = 10;
if (!appButton.exists()) {
while (!appButton.exists() && count-- >= 0) {
uiscrollable.swipeLeft(50);
}
}
count = 10;
if (!appButton.exists()) {
while (!appButton.exists() && count-- >= 0) {
uiscrollable.swipeRight(50);
}
}
}
if (appButton.exists()) {
// System.out.println("------------------click");
appButton.clickAndWaitForNewWindow();
} else {
System.out.println("No Found " + appName + " in home");
return false;
}
} else {
appButton = findByClassNameAndText(
"android.widget.TextView", appName);
if (!appButton.exists()) {
UiSelector uiselector = new UiSelector();
UiScrollable uiscrollable = new UiScrollable(
uiselector.scrollable(true));
uiscrollable.setAsHorizontalList();
uiscrollable.flingToBeginning(5);
int count = 10;
if (!appButton.exists()) {
while (!appButton.exists() && count-- >= 0) {
uiscrollable.swipeLeft(50);
}
}
count = 10;
if (!appButton.exists()) {
while (!appButton.exists() && count-- >= 0) {
uiscrollable.swipeRight(50);
}
}
}
if (appButton.exists()) {
// System.out.println("------------------click");
appButton.clickAndWaitForNewWindow();
} else {
System.out
.println("Can't found Apps button,use api start activity!"
+ appName + "\n");
// openAppBypkgName(appName);
return false;
}
}
}
Sleep(2000);
} catch (Exception e) {
return false;
}
return true;
}
// 切换中英文
// public static void switchLanguage()throws UiObjectNotFoundException {
// UiObject appBtn =
// findByResourceId("android:id/action_bar_overlay_layout");
// appBtn.clickTopLeft();
// Sleep(2000);
// }
// 测试结果检查点
public static void checkPointForRsult(String msg) {
SimpleDateFormat format = new SimpleDateFormat("MM_dd_HH_mm_ss");
Date curDate = new Date(System.currentTimeMillis());
String time = format.format(curDate);
loginfo(TAG, "path_screenshot_result = " + path_screenshot_result);
if (new File(path_screenshot_result).exists() == false) {
boolean res = new File(path_screenshot_result).mkdirs();
loginfo(TAG, "mkdir return " + res);
}
File screenshot = new File(path_screenshot_result + msg + "_" + time
+ ".png");
UiDevice.getInstance().takeScreenshot(screenshot);
loginfo(TAG, "checkPointForRsult msg=" + msg);
}
// 测试检查点
public static void checkPoint(String msg, boolean statue) {
if (!statue) {
SimpleDateFormat format = new SimpleDateFormat("MM_dd_HH_mm_ss");
Date curDate = new Date(System.currentTimeMillis());
String time = format.format(curDate);
loginfo(TAG, "path_screenshot_fail = " + path_screenshot_fail);
if (new File(path_screenshot_fail).exists() == false) {
boolean res = new File(path_screenshot_fail).mkdirs();
loginfo(TAG, "mkdir return " + res);
}
File screenshot = new File(path_screenshot_fail + msg + "_" + time
+ ".png");
UiDevice.getInstance().takeScreenshot(screenshot);
loginfo(TAG, "checkPoint msg=" + msg);
assertTrue(msg, statue);
}
}
public static void checkPoint(String msg, boolean statue,
UiObjectNotFoundException e) {
if (!statue) {
loginfo(TAG, msg, e);
checkPoint(msg, statue);
}
}
/*
* 修改语言输入法 输入法选择:启用【谷歌拼音输入法】\启用【Android 键盘 (AOSP)】
*/
/*
* public static void changeInputMethod(String inputMethodName) throws
* UiObjectNotFoundException { if
* (UiUtil.openApp(readResResource("ui_text_setting"))) { UiObject
* languageAndInputMethodItem = new UiObject( new
* UiSelector().text(readResResource("ui_text_lanuage_input"))); if
* (languageAndInputMethodItem.exists()) { UiObject myDeviceTab = new
* UiObject( new UiSelector().text(readResResource("ui_text_device")));
* myDeviceTab.click();
* languageAndInputMethodItem.clickAndWaitForNewWindow(); UiScrollable
* languageAndInputMethodList = new UiScrollable( new
* UiSelector().className("android.widget.ListView")); int count =
* languageAndInputMethodList .getChildCount(new UiSelector()
* .className("android.widget.LinearLayout")); UiObject childCheckBox1 =
* null; UiObject childCheckBox2 = null; UiObject chooseItem = null; for
* (int i = 0; i < count; i++) { UiObject item = languageAndInputMethodList
* .getChildByInstance(new UiSelector()
* .className("android.widget.LinearLayout"), i); // 启用【谷歌拼音输入法】 UiObject
* childTextView1 = item.getChild(new UiSelector()
* .text(readResResource("ui_text_input_google")));
*
* if (childTextView1.exists()) { childCheckBox1 = item.getChild(new
* UiSelector() .className("android.widget.CheckBox")); if
* (!childCheckBox1.isChecked()) { childCheckBox1.click(); } } // 启用【Android
* 键盘 (AOSP)】 UiObject childTextView2 = item.getChild(new UiSelector()
* .text("Android 键盘 (AOSP)"));
*
* if (childTextView2.exists()) { childCheckBox2 = item.getChild(new
* UiSelector() .className("android.widget.CheckBox")); if
* (!childCheckBox2.isChecked()) { childCheckBox2.click(); } } // 选择输入法
* UiObject childTextView3 = item.getChild(new UiSelector()
* .text(readResResource("ui_text_default"))); if (childTextView3.exists())
* { chooseItem = childTextView3; } } if (childCheckBox1 != null &&
* childCheckBox2 != null && chooseItem != null) {
* chooseItem.clickAndWaitForNewWindow(); UiObject choose = new UiObject(
* new UiSelector().text(inputMethodName));
* choose.clickAndWaitForNewWindow(); } } } }
*/
/*
* 测试当前输入法是否为英文 参数:UiObject 默认字符串(如地址栏默认包含http://) 返回:英文true,其他false
*/
public static boolean testInputIsEng(UiObject ob, String str)
throws UiObjectNotFoundException {
String s = ob.getText();
if (!s.equals(str)) {
return true;
} else {
return false;
}
}
/*
* 在定位到输入框的情况下,该方法在输入时更换输入法
*/
/*
* public static void changeInputMethodByShotCut(String inputMethodName,
* UiDevice uiDevice) throws UiObjectNotFoundException {
* uiDevice.drag(uiDevice.getDisplayWidth() / 2, 0,
* uiDevice.getDisplayWidth() / 2, uiDevice.getDisplayHeight(), 10);
* UiUtil.Sleep(2000); UiObject chooseItem = new UiObject(new
* UiSelector().text(readResResource("ui_text_input_sel")));
* chooseItem.clickAndWaitForNewWindow(); UiUtil.Sleep(1000); UiObject
* choose = new UiObject(new UiSelector().text(inputMethodName));
* choose.clickAndWaitForNewWindow(); }
*/
/*
* 点亮屏幕并解锁手机
*/
public static void onScreen() throws UiObjectNotFoundException {
System.out.print("onScreen android version:" + Build.VERSION.SDK_INT
+ "\n");
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
onScreenAndroidL();
} else {
try {
if (!UiDevice.getInstance().isScreenOn()) {
UiDevice.getInstance().pressKeyCode(26);
}
UiObject lockKey = findByResourceId("com.android.keyguard:id/keyguard_selector_view_frame");
if (lockKey.exists()) {
int left = lockKey.getBounds().left;
int right = lockKey.getBounds().right;
int top = lockKey.getBounds().top;
int bottom = lockKey.getBounds().bottom;
int x = (left + right) / 2;
int y = (top + bottom) / 2;
UiDevice.getInstance().drag(x, y, right, y, 10);
} else {
System.out.print("No Found lock Key\n");
}
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// ningbiao
public static void onScreenAndroidL() throws UiObjectNotFoundException {
try {
if (!UiDevice.getInstance().isScreenOn()) {
UiDevice.getInstance().pressKeyCode(26);
}
UiObject lockKey = findByResourceId("com.android.systemui:id/lock_icon");
if (lockKey.exists()) {
int w = UiDevice.getInstance().getDisplayWidth();
int h = UiDevice.getInstance().getDisplayHeight();
lockKey.dragTo(w / 2, h / 2, 10);
} else {
System.out.print("No Found lock Key\n");
}
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 进入设置中改为谷歌输入法
public static void switchLan() throws UiObjectNotFoundException {
UiDevice.getInstance().pressHome();
UiUtil.openApp(readResResource("ui_text_setting"));
UiScrollable list = new UiScrollable(new UiSelector().scrollable(true));
list.setAsVerticalList();
UiObject item = new UiObject(
new UiSelector().text(readResResource("ui_text_lanuage_input")));
while (!item.exists()) {
list.flingForward();
}
item.clickAndWaitForNewWindow();
UiObject choose = UiUtil
.findByText(readResResource("ui_text_input_google"));
if (choose.exists() && !choose.isChecked() && choose.isCheckable()) {
choose.click();
UiUtil.Sleep(1000);
}
UiDevice.getInstance().pressHome();
}
// 输入的过程中将输入法更改为英文输入法(搜索联系人界面)
public static void switchLanguage() throws UiObjectNotFoundException {
UiDevice uiDevice = UiDevice.getInstance();
uiDevice.drag(uiDevice.getDisplayWidth() / 2, 0,
uiDevice.getDisplayWidth() / 2, uiDevice.getDisplayHeight(), 10);
UiUtil.Sleep(2000);
UiObject chooseItem = new UiObject(
new UiSelector().text(readResResource("ui_text_input_sel")));
chooseItem.clickAndWaitForNewWindow();
UiUtil.Sleep(2000);
UiObject choose = UiUtil.findByText(readResResource("ui_text_english"));
if (choose.exists())
choose.clickAndWaitForNewWindow();
UiUtil.Sleep(1000);
}
// 点击双卡弹出的提示,0为SIM1,1为SIM2
public static UiObject click_sim_byid(String first, String second, int sim)
throws UiObjectNotFoundException {
// TODO Auto-generated method stub
UiObject ab = new UiCollection(new UiSelector().className(first).index(
sim)).getChild(new UiSelector().resourceId(second));
return ab;
}
// 长按坐标点
public static void longclick(UiObject object)
throws UiObjectNotFoundException {
int x = (object.getBounds().left + object.getBounds().right) / 2;
int y = (object.getBounds().top + object.getBounds().bottom) / 2;
UiDevice.getInstance().drag(x, y, x, y, 20);
}
// 下拉通知栏 ,进入
public static void downScreen() throws UiObjectNotFoundException {
int xLocation;
int yLocation;
xLocation = UiDevice.getInstance().getDisplayWidth() / 2;
yLocation = UiDevice.getInstance().getDisplayHeight() / 2;
UiDevice.getInstance().swipe(xLocation, 0, xLocation, yLocation, 10);
}
// 清除后台
public static void clearBackgroundApps() throws UiObjectNotFoundException {
loginfo(TAG, "clearBackgroundApps");
try {
UiDevice.getInstance().pressRecentApps();
Sleep(5000);
UiObject clearBtn = findByResourceId(readResResource("ui_resid_recent_sprdramopt_view"));
if (clearBtn.exists()) {
clearBtn.click();
} else {
clearBtn = findByResourceId(readResResource("ui_resid_recent_dismiss"));
int count = 50;
while (clearBtn.exists() && count-- >= 0) {
clearBtn.click();
Sleep(2000);
}
}
pressHome();
Sleep(1000);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pressHome();
}
// 调节音量
public static void adjustVolume() throws UiObjectNotFoundException {
for (int i = 0; i < 10; i++) {
UiDevice.getInstance().pressKeyCode(KeyEvent.KEYCODE_VOLUME_UP);
UiUtil.Sleep(1000);
}
UiUtil.Sleep(5000);
for (int j = 0; j < 8; j++) {
UiDevice.getInstance().pressKeyCode(KeyEvent.KEYCODE_VOLUME_DOWN);
UiUtil.Sleep(1000);
}
UiUtil.Sleep(3000);
}
// 横竖屏旋转
public void gsensor() throws UiObjectNotFoundException, RemoteException {
UiDevice.getInstance().setOrientationLeft();
sleep(5000);
UiDevice.getInstance().setOrientationRight();
sleep(5000);
UiDevice.getInstance().setOrientationNatural();
sleep(5000);
}
// 保证正常退出应用
public static void goHome() throws UiObjectNotFoundException {
for (int i = 0; i < 5; i++) {
if (checkInLauncher()) {
loginfo(TAG, "Already in launcher!");
break;
}
pressBack();
Sleep(200);
}
pressHome();
}
public static void pressHome() throws UiObjectNotFoundException {
UiDevice.getInstance().pressHome();
}
public static void pressBack() throws UiObjectNotFoundException {
UiDevice.getInstance().pressBack();
}
public static void openNotification() throws UiObjectNotFoundException {
UiDevice.getInstance().openNotification();
}
public static void pressMenu() throws UiObjectNotFoundException {
UiDevice.getInstance().pressMenu();
}
public static void pressEnter() throws UiObjectNotFoundException {
UiDevice.getInstance().pressEnter();
}
public static void pressDPadUp() throws UiObjectNotFoundException {
UiDevice.getInstance().pressDPadUp();
}
public static void pressDPadDown() throws UiObjectNotFoundException {
UiDevice.getInstance().pressDPadDown();
}
public static void pressDPadLeft() throws UiObjectNotFoundException {
UiDevice.getInstance().pressDPadLeft();
}
public static void pressDPadRight() throws UiObjectNotFoundException {
UiDevice.getInstance().pressDPadRight();
}
public static boolean isScreenOn() throws RemoteException {
return UiDevice.getInstance().isScreenOn();
}
public static void openQuickSettings() throws UiObjectNotFoundException {
UiDevice.getInstance().openQuickSettings();
}
// 检查所有进入应用是否正确
public static void checkAppView(String name)
throws UiObjectNotFoundException {
if (name.equals(readResResource("ui_text_dial"))
|| name.equals(readResResource("dial_text_app_dial"))) {
UiObject dialBtn = findByResourceId(readResResource("dial_resid_dialpad_button"));
checkPoint("enter call fail ", dialBtn.exists());
} else if (name.equals(readResResource("ui_text_contact"))
|| name.equals(readResResource("contact_text_app_name_contacts"))) {
UiObject pb = findByDesc(readResResource("ui_text_contact_all"));
boolean contactsText = checkObjectExistsByText(name);
checkPoint("enter pb fail ", pb.exists() || contactsText);
} else if (name.equals(readResResource("ui_text_message"))) {
UiObject message = findByResourceIdAndText(
"android:id/action_bar_title",
readResResource("ui_text_message"));
boolean messageTitle = checkObjectExistsByText(readResResource("mms_text_app_name"));
checkPoint("enter message fail ", message.exists() || messageTitle);
} else if (name.equals(readResResource("ui_text_setting"))) {
UiObject setting = findByText(readResResource("ui_text_setting"));
checkPoint("enter setting fail ", setting.exists());
} else if (name.equals(readResResource("ui_text_calculator"))) {
UiObject calculate = findByResourceIdAndText(
"com.android.calculator2:id/del",
readResResource("ui_text_back"));
checkPoint("enter calculate fail ", calculate.exists());
} else if (name.equals(readResResource("ui_text_calendar"))) {
UiObject data = findByResourceIdAndDesc(
"com.android.calendar:id/action_today",
readResResource("ui_text_today"));
checkPoint("enter data fail ", data.exists());
} else if (name.equals(readResResource("ui_text_camera"))) {
UiObject camera = findByResourceId("com.android.camera2:id/filmstrip_bottom_controls");
UiObject notice = findByText(readResResource("ui_text_remember_address"));
boolean overlay = checkObjectExistsByID("com.android.camera2:id/mode_options_overlay");
checkPoint("enter camera fail ",
(camera.exists() || notice.exists() || overlay));
} else if (name.equals(readResResource("ui_text_clock"))) {
UiObject clock = findByResourceIdAndText(
"com.android.deskclock:id/tab_text",
readResResource("ui_text_alarm"));
checkPoint("enter clock fail ", clock.exists());
} else if (name.equals(readResResource("ui_text_gallary"))) {
UiObject picture = findByResourceId("com.android.gallery3d:id/gl_root_view");
checkPoint("enter picture fail ", picture.exists());
} else if (name.equals(readResResource("ui_text_video"))) {
UiObject video = findByResourceIdAndText("android:id/text1",
readResResource("ui_text_video"));
checkPoint("enter video fail", video.exists());
} else if (name.equals(readResResource("ui_text_music"))) {
UiObject music = findById(readResResource("music_resid_artisttab"));
checkPoint("enter music fail ", music.exists());
} else if (name.equals(readResResource("ui_text_record"))) {
UiObject recorder = findByText(readResResource("ui_text_save_record"));
checkPoint("enter recorder fail ", recorder.exists());
} else if (name.equals(readResResource("ui_text_playstore"))) {
UiObject addaccount = findByText(readResResource("playstore_add_account"));
UiObject confirm = findByText(readResResource("browser_text_ok"));
UiObject googleplay = findByResourceId("com.android.vending:id/search_box_idle_text");
checkPoint("enter playstore fail ", addaccount.exists() || confirm.exists() || googleplay.exists());
} else if (name.equals(readResResource("ui_text_fm"))) {
Sleep(3000);
UiObject storeBtn = findByText(readResResource("fm_text_save_channel"));
UiObject searchBtn = findByText(readResResource("fm_text_search"));
UiObject fm = findByText(readResResource("ui_text_fm"));
UiObject fm1 = findByText(readResResource("fm_text_airplane_warn"));
UiObject fm2 = findByText(readResResource("fm_text_earphone_warn"));
checkPoint(
"enter fm fail ",
(fm.exists() || fm1.exists() || fm2.exists()
|| storeBtn.exists() || searchBtn.exists()));
} else {
loginfo(TAG, "Wrong app name:" + name);
// checkPoint("Wrong app name:" + name, false);
}
}
/*
* 进入某文件夹的某个文件
*/
public void openAppFloder(String floder, String name)
throws UiObjectNotFoundException {
UiDevice.getInstance().pressHome();
UiDevice.getInstance().pressHome();
sleep(1000);
UiObject obj = new UiObject(new UiSelector().text(floder));// 文件夹名
UiObject name1 = new UiObject(new UiSelector().text(name));
for (int i = 0; i < 3; i++) {
if (obj.exists()) {
obj.clickAndWaitForNewWindow();
name1.clickAndWaitForNewWindow();
break;
}
getUiDevice();
UiDevice.getInstance().drag(421, 694, 50, 694, 5);
sleep(1000);
obj = new UiObject(new UiSelector().text(name));
}
}
// 打开文件
public static void openFloder(String name) throws UiObjectNotFoundException {
System.out.println("switch to TF card");
UiObject CheckedTextView = UiUtil
.findByClassName("android.widget.CheckedTextView");
CheckedTextView.clickAndWaitForNewWindow();
UiObject storage = UiUtil
.findByText(readResResource("foldermgr_text_switch_to_tf"));
storage.clickAndWaitForNewWindow();
UiScrollable scrollable = new UiScrollable(new UiSelector().resourceId(
"com.sprd.fileexplorer:id/detailed_file_list").scrollable(true));
scrollable.setAsVerticalList();
UiObject file = UiUtil.findByText(name);
while (!file.exists()) {
boolean fling = scrollable.scrollForward();
if (fling == false) {
break;
}
}
if (file.exists()) {
file.clickAndWaitForNewWindow();
// sleep(2000);
} else {
System.out.println(name + "file not exist");
UiUtil.goHome();
}
}
// 获取命令并执行 ,返回0表示执行成功
public static void exeCommand(String command) throws IOException {
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec(command);
UiUtil.Sleep(3000);
try {
if (proc.waitFor() != 0) {
System.err.println("exit value = " + proc.exitValue());
}
BufferedReader in = new BufferedReader(new InputStreamReader(
proc.getInputStream()));
StringBuffer stringBuffer = new StringBuffer();
String line = null;
while ((line = in.readLine()) != null) {
stringBuffer.append(line + " ");
}
System.out.println(stringBuffer.toString());
} catch (InterruptedException e) {
System.err.println(e);
UiUtil.checkPoint("ping error", false);
} finally {
try {
proc.destroy();
} catch (Exception e2) {
}
}
}
// 长按物理键
public static boolean longPressKeyCode(int keyCode) {
try {
Object deviceObj = UiDevice.getInstance();
Field mUiAutomationBridge = Class.forName(
"com.android.uiautomator.core.UiDevice").getDeclaredField(
"mUiAutomationBridge");
mUiAutomationBridge.setAccessible(true);
Object bridgeObj = mUiAutomationBridge.get(deviceObj);
Method injectInputEvent = Class.forName(
"com.android.uiautomator.core.UiAutomatorBridge")
.getDeclaredMethod(
"injectInputEvent",
new Class[] { android.view.InputEvent.class,
boolean.class });
final long eventTime = SystemClock.uptimeMillis();
KeyEvent downEvent = new KeyEvent(eventTime, eventTime,
KeyEvent.ACTION_DOWN, keyCode, 0, 0,
KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0,
InputDevice.SOURCE_KEYBOARD);
if ((Boolean) injectInputEvent.invoke(bridgeObj, new Object[] {
downEvent, true })) {
SystemClock.sleep(500);
for (int repetition = 0; repetition < 10; repetition++) {
KeyEvent newEvent = KeyEvent.changeTimeRepeat(downEvent,
SystemClock.uptimeMillis(), repetition,
downEvent.getFlags() | KeyEvent.FLAG_LONG_PRESS);
injectInputEvent.invoke(bridgeObj, new Object[] { newEvent,
true });
SystemClock.sleep(5);
}
KeyEvent upEvent = new KeyEvent(eventTime, eventTime,
KeyEvent.ACTION_UP, keyCode, 0, 0,
KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0,
InputDevice.SOURCE_KEYBOARD);
if ((Boolean) injectInputEvent.invoke(bridgeObj, new Object[] {
upEvent, true })) {
return true;
}
}
} catch (NoSuchMethodException e) {
Log.d("TAG", e.getMessage());
} catch (ClassNotFoundException e) {
Log.d("TAG", e.getMessage());
} catch (InvocationTargetException e) {
Log.d("TAG", e.getMessage());
} catch (IllegalAccessException e) {
Log.d("TAG", e.getMessage());
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
return false;
}
/*
* 按power键,灭屏,锁屏
*/
public static void offScreen() throws UiObjectNotFoundException {
try {
if (UiDevice.getInstance().isScreenOn()) {
UiDevice.getInstance().pressKeyCode(26);
UiUtil.Sleep(2000);
}
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 判断一个字符串是否都为数字
public static boolean isDigit(String strNum) {
return strNum.matches("[0-9]{1,}");
}
/*
* 获取XML文件节点 参数:文件名,节点名,属性名 返回:字符串数组
*/
public static String[] getXmlValue(String file, String value, String attr) {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dbf.newDocumentBuilder();
Document doc = builder.parse("file:///data//local//tmp//" + file); // 获取到xml文件
String s;
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr = xpath.compile("//" + value); // 获取节点名称
NodeList nodes = (NodeList) expr.evaluate(doc,
XPathConstants.NODESET);
String sp[] = new String[nodes.getLength()];
for (int i = 0; i < nodes.getLength(); i++) {
Node nd = nodes.item(i);
s = nd.getAttributes().getNamedItem(attr).getTextContent();
sp[i] = s;
}
return sp;
} catch (XPathExpressionException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String readConfig(String tagname) {
return readJson(tagname);
}
// 读取XML文件参数
public static String readXml(String tagname) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
String folder = RES_CONFIG_FOLER_CASE;
if (!new File("/data/local/tmp/" + folder).exists()) {
folder = ".";
}
DocumentBuilder builder = dbf.newDocumentBuilder();
Document doc = builder.parse("file:///data//local//tmp//" + folder
+ "//config.xml");
doc.normalize();
NodeList node = doc.getElementsByTagName(tagname);
String result = node.item(0).getTextContent();
return result;
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
}
// 文件名,TAG名来读取XML文件参数
public static String readXml(String fileName, String tagname) {
loginfo(TAG, "readXml fileName=" + fileName + ",tagname=" + tagname);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
String folder = RES_CONFIG_FOLER_CASE;
if (!new File("/data/local/tmp/" + folder).exists()) {
folder = ".";
}
DocumentBuilder builder = dbf.newDocumentBuilder();
Document doc = builder.parse("file:///data//local//tmp//" + folder
+ "//" + fileName + ".xml");
doc.normalize();
NodeList node = doc.getElementsByTagName(tagname);
String result = node.item(0).getTextContent();
return result;
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
}
private static final int s_config_total_size = 5 * 1024 * 1024;
private static JSONObject s_json_config = null;
private static final String s_config_main_tag = "config";
private static final String s_config_value_tag = "value";
private static final String s_config_id_tag = "id";
private static String readJson(String tagname) {
if (s_json_config == null) {
try {
FileInputStream fis = new FileInputStream(new File(
RES_CONFIG_PATH + "config.json"));
int iLen = fis.available();
loginfo(TAG, "iLen = " + iLen);
if (iLen <= 0 || iLen >= s_config_total_size) {
fis.close();
loginfo(TAG, "read json fail: iLen = " + iLen);
return readXml(tagname);
}
int num = 0;
char[] cbuf = new char[1024];
StringBuilder sb = new StringBuilder(iLen + 1);
InputStreamReader isReader = new InputStreamReader(fis);
while ((num = isReader.read(cbuf)) > 0) {
sb.append(cbuf);
}
loginfo(TAG, "buff: " + sb.toString());
s_json_config = new JSONObject(sb.toString());
isReader.close();
} catch (Exception e) {
loginfo(TAG, "read json fail: " + e.getMessage());
return readXml(tagname);
}
}
try {
String content = s_json_config.getString(s_config_main_tag);
JSONArray jsonArray = new JSONArray(content);
for (int i = 0; i < jsonArray.length(); i++) {
String param = jsonArray.getString(i);
JSONObject obj = new JSONObject(param);
if (obj.getString(s_config_id_tag).equals(tagname)) {
String value = obj.getString(s_config_value_tag);
loginfo(TAG, "tagname = " + tagname + ", value = " + value);
return value;
}
}
} catch (Exception e) {
}
loginfo(TAG, "read json fail: can't find " + tagname
+ " in config.json");
return readXml(tagname);
}
// 读取XML文件参数
public static String readRes(int res, String tagname) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
String filename = null;
if (res == RES_CONFIG) {
filename = RES_CONFIG_FILE;
} else if (res == RES_RESOURCE) {
filename = RES_RESOURCE_FILE;
} else {
return null;
}
try {
String folder = RES_CONFIG_FOLER_CASE;
if (!new File("/data/local/tmp/" + folder).exists()) {
folder = ".";
}
DocumentBuilder builder = dbf.newDocumentBuilder();
Document doc = builder.parse("file:///data//local//tmp//" + folder
+ "//" + filename);
doc.normalize();
NodeList node = doc.getElementsByTagName(tagname);
String result = node.item(0).getTextContent();
return result;
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
}
// 删除文件
/**
* @Title: deleteFloder
* @Description: 通过文件管理器删除文件/文件夹
* @param String
* name
* @param
* @param
* @return
* @throws UiObjectNotFoundException
*/
public static void deleteFloder(String name)
throws UiObjectNotFoundException {
UiObject fileexplorer = UiUtil.findByPackage("com.sprd.fileexplorer");
if (!fileexplorer.exists()) {
openApp(readResResource("ui_text_foldermanager"));
}
System.out.println("switch to tf card");
UiObject CheckedTextView = UiUtil
.findByClassName("android.widget.CheckedTextView");
CheckedTextView.clickAndWaitForNewWindow();
UiObject storage = UiUtil
.findByText(readResResource("foldermgr_text_switch_to_tf"));
storage.clickAndWaitForNewWindow();
UiScrollable scrollable = new UiScrollable(new UiSelector().resourceId(
"com.sprd.fileexplorer:id/detailed_file_list").scrollable(true));
scrollable.setAsVerticalList();
UiObject file = UiUtil.findByText(name);
try {
scrollable.flingBackward();
scrollable.flingBackward();
} catch (Exception e) {
// TODO: handle exception
}
int i = 0;
while (!file.exists()) {
UiDevice.getInstance().pressDPadDown();
i++;
if (i == 50) {
break;
}
}
file = UiUtil.findByText(name);
if (file.exists()) {
UiDevice.getInstance().pressDPadDown();
UiUtil.Sleep(1000);
UiObject floder = UiUtil.findByText(name);
longclick(floder);
UiUtil.Sleep(2000);
UiObject delete = UiUtil
.findByText(readResResource("button_text_delete"));
delete.clickAndWaitForNewWindow();
UiObject confirm = UiUtil
.findByText(readResResource("button_text_ok"));
confirm.clickAndWaitForNewWindow();
UiUtil.Sleep(3000);
} else {
System.out.println(name + "file not exist");
}
}
// ningbiao
/**
* @Title: setPreferredNetworkType
* @Description: 设置首选网络
* @param CALL_SIM_TYPE
* sim_TYPE
* @param PREFERRED_NETWORK_TYPE
* network_TYPE
* @param
* @return
* @throws UiObjectNotFoundException
*/
public void setPreferredNetworkType(CALL_SIM_TYPE sim_TYPE,
PREFERRED_NETWORK_TYPE network_TYPE)
throws UiObjectNotFoundException {
openApp(UiUtil.readResResource("ui_text_setting"));
sleep(1000);
UiObject more = new UiObject(new UiSelector().className(
"android.widget.TextView").textContains(
UiUtil.readResResource("settings_text_more")));
if (more.exists()) {
more.clickAndWaitForNewWindow();
UiObject mobile_network = new UiObject(new UiSelector().className(
"android.widget.TextView").text(
UiUtil.readResResource("settings_text_mobile_networks")));
mobile_network.clickAndWaitForNewWindow();
if (sim_TYPE == CALL_SIM_TYPE.SIM1) {
UiObject setting_sim1 = new UiObject(
new UiSelector()
.className("android.widget.TextView")
.text(UiUtil
.readResResource("settings_text_mobile_networks_sim1")));
if (setting_sim1.exists()) {
setting_sim1.clickAndWaitForNewWindow();
} else {
System.out
.print("SIM1 Mobile Network settings did't exists!");
}
} else if (sim_TYPE == CALL_SIM_TYPE.SIM2) {
UiObject setting_sim2 = new UiObject(
new UiSelector()
.className("android.widget.TextView")
.text(UiUtil
.readResResource("settings_text_mobile_networks_sim2")));
if (setting_sim2.exists()) {
setting_sim2.clickAndWaitForNewWindow();
} else {
System.out
.print("SIM2 Mobile Network settings did't exists!");
}
} else {
System.out.print("SIM type error!");
}
UiObject preferred_network = new UiObject(
new UiSelector()
.className("android.widget.TextView")
.text(UiUtil
.readResResource("settings_text_preferred_network_type")));
if (preferred_network.exists()) {
preferred_network.clickAndWaitForNewWindow();
}
String typeText = "Auto";
switch (network_TYPE) {
case AUTO:
typeText = UiUtil
.readResResource("settings_preferred_text_auto");
break;
case GSM_ONLY:
typeText = UiUtil
.readResResource("settings_preferred_text_gsm_only");
break;
case LTE_ONLY:
typeText = UiUtil
.readResResource("settings_preferred_text_lte_only");
break;
case TD_ONLY:
typeText = UiUtil
.readResResource("settings_preferred_text_td_only");
break;
case WCDMA_ONLY:
typeText = UiUtil
.readResResource("settings_preferred_text_wcdma_only");
break;
default:
break;
}
UiObject checked_option = new UiObject(new UiSelector().className(
"android.widget.CheckedTextView").text(typeText));
if (checked_option.exists()) {
checked_option.clickAndWaitForNewWindow();
sleep(3000);
} else {
System.out.print("Has't Preferred network type options!");
}
} else {
System.out.print("Has't more button!");
}
}
// ningbiao
/**
* @Title: openMoreOptionsMenu
* @Description: 打开menu菜单
* @param
* @param
* @param
* @return
* @throws UiObjectNotFoundException
*/
public static void openMoreOptionsMenu() throws UiObjectNotFoundException {
UiObject moreOptionsButton = new UiObject(new UiSelector()
.className("android.widget.ImageButton")
.description(UiUtil.readResResource("menu_text_more_option"))
.instance(0));
if (moreOptionsButton.exists()) {
moreOptionsButton.clickAndWaitForNewWindow();
} else {
UiDevice.getInstance().pressMenu();
}
}
// ningbiao
/**
* @Title: updateLanguage
* @Description: 切换系统语言
* @param Locale
* locale
* @param
* @param
* @return
* @throws
*/
public static void updateLanguage(Locale locale) {
Log.d("ANDROID_LAB", locale.toString());
try {
Object objIActMag, objActMagNative;
Class clzIActMag = Class.forName("android.app.IActivityManager");
Class clzActMagNative = Class
.forName("android.app.ActivityManagerNative");
Method mtdActMagNative$getDefault = clzActMagNative
.getDeclaredMethod("getDefault");
// IActivityManager iActMag = ActivityManagerNative.getDefault();
objIActMag = mtdActMagNative$getDefault.invoke(clzActMagNative);
// Configuration config = iActMag.getConfiguration();
Method mtdIActMag$getConfiguration = clzIActMag
.getDeclaredMethod("getConfiguration");
Configuration config = (Configuration) mtdIActMag$getConfiguration
.invoke(objIActMag);
config.locale = locale;
// iActMag.updateConfiguration(config);
// 此处�?��声明权限:android.permission.CHANGE_CONFIGURATION
// 会重新调�?onCreate();
Class[] clzParams = { Configuration.class };
Method mtdIActMag$updateConfiguration = clzIActMag
.getDeclaredMethod("updateConfiguration", clzParams);
mtdIActMag$updateConfiguration.invoke(objIActMag, config);
} catch (Exception e) {
e.printStackTrace();
}
}
// ningbiao
/**
* @Title: openFloderEn
* @Description: 从文件管理器中打开某一个文件夹
* @param String
* name
* @param
* @param
* @return
* @throws UiObjectNotFoundException
*/
public void openFloderEn(String name) throws UiObjectNotFoundException {
UiObject CheckedTextView = findByClassName("android.widget.CheckedTextView");
CheckedTextView.clickAndWaitForNewWindow();
UiObject storage = findByText(UiUtil
.readResResource("fileexplorer_text_external_storage"));
if (!storage.exists()) {
storage = findByText(UiUtil
.readResResource("fileexplorer_text_internal_storage"));
}
storage.clickAndWaitForNewWindow();
UiScrollable scrollable = new UiScrollable(new UiSelector().resourceId(
"com.sprd.fileexplorer:id/detailed_file_list").scrollable(true));
scrollable.setAsVerticalList();
UiObject file = findByText(name);
while (!file.exists()) {
boolean fling = scrollable.scrollForward();
if (fling == false) {
break;
}
}
if (file.exists()) {
file.clickAndWaitForNewWindow();
// sleep(2000);
} else {
System.out.println(name + "File is not exists!");
}
}
// ningbiao
/**
* @Title: findByPackageName
* @Description: 通过包名获取对象
* @param String
* packageName
* @param
* @param
* @return UiObject
* @throws
*/
public static UiObject findByPackageName(String packageName) {
return new UiObject(new UiSelector().packageName(packageName));
}
/**
* @Title: deleteFloderCamera
* @Description: 删除DCIM中的Camera文件夹
* @param String
* floderName
* @param String
* storageName
* @param
* @return
* @throws UiObjectNotFoundException
*/
public static void deleteFloderCamera(String floderName, String storageName)
throws UiObjectNotFoundException {
UiObject fileexplorer = findByPackageName("com.sprd.fileexplorer");
if (!fileexplorer.exists()) {
openApp(UiUtil.readResResource("fileexplorer_text_app_name"));
}
UiObject CheckedTextView = findByClassName("android.widget.CheckedTextView");
CheckedTextView.clickAndWaitForNewWindow();
UiObject storage = findByText(storageName);
if (!storage.exists()) {
storage = findByText(UiUtil
.readResResource("fileexplorer_text_external_storage"));
if (!storage.exists()) {
storage = findByText(UiUtil
.readResResource("fileexplorer_text_internal_storage"));
}
}
storage.clickAndWaitForNewWindow();
UiScrollable scrollable = new UiScrollable(new UiSelector().resourceId(
"com.sprd.fileexplorer:id/detailed_file_list").scrollable(true));
scrollable.setAsVerticalList();
UiObject file = findByText(floderName);
try {
scrollable.flingBackward();
scrollable.flingBackward();
} catch (Exception e) {
// TODO: handle exception
}
int i = 0;
while (!file.exists()) {
UiDevice.getInstance().pressDPadDown();
i++;
if (i == 50) {
break;
}
}
file = findByText(floderName);
if (file.exists()) {
UiDevice.getInstance().pressDPadDown();
UiUtil.Sleep(1000);
UiObject floder = findByText(floderName);
// longclick(floder);
floder.clickAndWaitForNewWindow();
UiUtil.Sleep(1000);
// delete Camera floder
scrollable = new UiScrollable(new UiSelector().resourceId(
"com.sprd.fileexplorer:id/detailed_file_list").scrollable(
true));
scrollable.setAsVerticalList();
file = findByText("Camera");
try {
scrollable.flingBackward();
scrollable.flingBackward();
} catch (Exception e) {
// TODO: handle exception
}
i = 0;
while (!file.exists()) {
UiDevice.getInstance().pressDPadDown();
i++;
if (i == 50) {
break;
}
}
if (file.exists()) {
UiDevice.getInstance().pressDPadDown();
UiUtil.Sleep(1000);
longclick(file);
UiUtil.Sleep(1000);
UiObject delete = findByText(UiUtil
.readResResource("button_text_delete"));
delete.clickAndWaitForNewWindow();
UiObject confirm = findByText(UiUtil
.readResResource("button_text_ok"));
confirm.clickAndWaitForNewWindow();
UiUtil.Sleep(2000);
} else {
System.out.println(floderName + "Camera floder is not exists!");
}
} else {
System.out.println(floderName + "File is not exists!");
}
}
// ningbiao
/**
* @Title: destotyAll
* @Description: 清除所有后台程序
* @param
* @param
* @param
* @return
* @throws UiObjectNotFoundException
*/
public void destotyAll() throws UiObjectNotFoundException {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
clearBackgroundApps();
} else {
try {
UiDevice.getInstance().pressRecentApps();
UiObject recent_sprdramopt_view = new UiObject(
new UiSelector()
.resourceId("com.android.systemui:id/recent_sprdramopt_view"));
if (recent_sprdramopt_view.exists()) {
recent_sprdramopt_view.clickAndWaitForNewWindow();
}
goHome();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// ningbiao
/**
* @Title: execCommand
* @Description: 执行命令
* @param String
* command
* @param
* @param
* @return
* @throws IOException
*/
public static void execCommand(String command) throws IOException {
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec(command);
try {
if (proc.waitFor() != 0) {
System.err.println("exit value = " + proc.exitValue());
}
BufferedReader in = new BufferedReader(new InputStreamReader(
proc.getInputStream()));
StringBuffer stringBuffer = new StringBuffer();
String line = null;
while ((line = in.readLine()) != null) {
stringBuffer.append(line + " ");
}
System.out.println(stringBuffer.toString());
} catch (InterruptedException e) {
System.err.println(e);
} finally {
try {
proc.destroy();
} catch (Exception e2) {
}
}
}
// ningbiao
public static String readResResource(String tagname) {
return readResWithLocale(RES_RESOURCE, tagname);
}
/**
* @Title: readResWithLocale
* @Description: 通过tag,获取资源文件中(xml)的内容
* @param int res
* @param String
* tagname
* @param
* @return String
* @throws
*/
public static String readResWithLocale(int res, String tagname) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
Locale locale = getCurretnLocale();
String filename = null;
if (res == RES_CONFIG) {
filename = RES_CONFIG_FILE;
} else if (res == RES_RESOURCE) {
if (locale.equals(Locale.ENGLISH) || locale.equals(Locale.UK)
|| locale.equals(Locale.US)) {
filename = RES_RESOURCE_FILE_EN;
} else if (locale.equals(Locale.CHINA)
|| locale.equals(Locale.CHINESE)) {
filename = RES_RESOURCE_FILE;
} else {
filename = RES_RESOURCE_FILE_EN;
}
} else {
return null;
}
try {
String folder = RES_CONFIG_FOLER_CASE;
if (!new File("/data/local/tmp/" + folder).exists()) {
folder = ".";
}
DocumentBuilder builder = dbf.newDocumentBuilder();
Document doc = builder.parse("file:///data//local//tmp//" + folder
+ "//" + filename);
doc.normalize();
NodeList node = doc.getElementsByTagName(tagname);
String result = node.item(0).getTextContent();
return result;
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
}
// ningbiao
/**
* @Title: getCurretnLocale
* @Description: 切换手机默认语言
* @param
* @param
* @param
* @return
* @throws
*/
public static Locale getCurretnLocale() {
try {
Object objIActMag, objActMagNative;
Class clzIActMag = Class.forName("android.app.IActivityManager");
Class clzActMagNative = Class
.forName("android.app.ActivityManagerNative");
Method mtdActMagNative$getDefault = clzActMagNative
.getDeclaredMethod("getDefault");
// IActivityManager iActMag = ActivityManagerNative.getDefault();
objIActMag = mtdActMagNative$getDefault.invoke(clzActMagNative);
// Configuration config = iActMag.getConfiguration();
Method mtdIActMag$getConfiguration = clzIActMag
.getDeclaredMethod("getConfiguration");
Configuration config = (Configuration) mtdIActMag$getConfiguration
.invoke(objIActMag);
return config.locale;
} catch (Exception e) {
e.printStackTrace();
}
return Locale.ENGLISH;
}
// ningbiao
/**
* @Title: setDefaultSimCard
* @Description: 设置默认卡(短信/通话/数据链接/视频通话)
* @param SIM_SELECT_TYPE
* selectType
* @param CALL_SIM_TYPE
* simType
* @param boolean alwaysPrompt
* @return
* @throws UiObjectNotFoundException
*/
public static void setDefaultSimCard(SIM_SELECT_TYPE selectType,
CALL_SIM_TYPE simType, boolean alwaysPrompt)
throws UiObjectNotFoundException {
goHome();
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
try {
openApp(UiUtil.readResResource("ui_text_setting"));
enterSetChild(UiUtil.readResResource("settings_text_sim_cards"));
String resStr = null;
if (selectType == SIM_SELECT_TYPE.CALL) {
resStr = "settings_text_calls_setting";
} else if (selectType == SIM_SELECT_TYPE.MMS) {
resStr = "settings_text_message_setting";
} else {
return;
}
System.out.print("resStr=" + resStr);
UiObject mDialog = UiUtil.findByText(UiUtil
.readResResource(resStr));
if (mDialog.exists()) {
mDialog.clickAndWaitForNewWindow();
}
UiUtil.Sleep(1000);
if (alwaysPrompt) {
resStr = UiUtil
.readResResource("settings_text_ask_every_time");
UiObject obj = UiUtil.findByText(resStr);
obj.clickAndWaitForNewWindow();
} else {
UiCollection collextion = new UiCollection(
new UiSelector()
.resourceId("android:id/select_dialog_listview"));
int instance = 1;
if (simType == CALL_SIM_TYPE.SIM1) {
instance = 1;
} else if (simType == CALL_SIM_TYPE.SIM2) {
instance = 2;
}
System.out.print("instance:" + instance + "\n");
UiObject obj = collextion
.getChild(new UiSelector()
.resourceId(
"com.android.settings:id/default_subscription_off")
.instance(instance));
System.out.print("obj:" + obj.exists() + "\n");
if (obj.exists()) {
obj.clickAndWaitForNewWindow();
}
}
goHome();
} catch (Exception e) {
e.printStackTrace();
}
} else {
try {
openApp(UiUtil.readResResource("ui_text_setting"));
enterSetChild(UiUtil.readResResource("settings_text_mulitsim"));
String resStr = null;
if (selectType == SIM_SELECT_TYPE.CALL) {
resStr = "settings_text_mulitsim_voice";
} else if (selectType == SIM_SELECT_TYPE.DATACONNECT) {
resStr = "settings_text_mulitsim_dataconnect";
} else if (selectType == SIM_SELECT_TYPE.VIDEOCALL) {
resStr = "settings_text_mulitsim_video";
} else if (selectType == SIM_SELECT_TYPE.MMS) {
resStr = "settings_text_mulitsim_mms";
} else {
return;
}
System.out.print("resStr=" + resStr);
UiObject dialBtn = UiUtil.findByText(UiUtil
.readResResource(resStr));
// Fix for JRX test case.
if (!dialBtn.exists()) {
if (selectType == SIM_SELECT_TYPE.CALL) {
resStr = "settings_text_mulitsim_voice_call";
} else if (selectType == SIM_SELECT_TYPE.DATACONNECT) {
resStr = "settings_text_mulitsim_dataconnect";
} else if (selectType == SIM_SELECT_TYPE.VIDEOCALL) {
resStr = "settings_text_mulitsim_video_call";
} else if (selectType == SIM_SELECT_TYPE.MMS) {
resStr = "settings_text_mulitsim_mms_call";
} else {
return;
}
dialBtn = UiUtil.findByText(UiUtil.readResResource(resStr));
}
dialBtn.clickAndWaitForNewWindow();
UiUtil.Sleep(1000);
if (alwaysPrompt) {
resStr = UiUtil
.readResResource("settings_text_mulitsim_always_prompt");
} else {
resStr = UiUtil.readResResource("settings_text_sim")
+ ((simType == CALL_SIM_TYPE.SIM1) ? "1" : "2");
}
UiObject obj = UiUtil.findByText(resStr);
if (!obj.exists()) {
UiObject select_dialog_listview = findByResourceId("android:id/select_dialog_listview");
if (select_dialog_listview.exists()) {
// sim1 is index 0,sim2 is index 1;
int instance = alwaysPrompt ? 2
: (simType == CALL_SIM_TYPE.SIM1 ? 0 : 1);
UiCollection collextion = new UiCollection(
new UiSelector()
.packageName("com.android.settings")
.className(
"android.widget.RelativeLayout")
.index(instance));
UiObject mRadioButton = collextion
.getChild(new UiSelector()
.className("android.widget.RadioButton"));
if (!mRadioButton.isChecked()) {
mRadioButton.clickAndWaitForNewWindow();
}
}
} else {
obj.clickAndWaitForNewWindow();
}
goHome();
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
}
}
// ningbiao
/**
* @Title: enterSetChild
* @Description: 通过名字,进入列表中某一项
* @param String
* setName
* @param
* @param
* @return
* @throws UiObjectNotFoundException
*/
public static void enterSetChild(String setName)
throws UiObjectNotFoundException {
UiScrollable setList = UiUtil
.findScrollableByResource("android:id/list");
System.out.print("enterSetChild setList.exists" + setList.exists()
+ "\n");
if (!setList.exists()) {
setList = UiUtil.findScrollableByClass("android.widget.ScrollView");
}
setList.setAsVerticalList();
UiObject searchItem = new UiObject(new UiSelector().text(setName));
while (!searchItem.exists()) {
boolean scroll = setList.scrollForward();
UiUtil.checkPoint("no found the searchItem", (scroll == true));
}
searchItem.clickAndWaitForNewWindow();
}
// ningbiao
/**
* @Title: getRandomString
* @Description: 产生一个随机的字符串
* @param int length
* @param
* @param
* @return String
* @throws
*/
public static String getRandomString(int length) {
String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Random random = new Random();
StringBuffer buf = new StringBuffer();
for (int i = 0; i < length; i++) {
int num = random.nextInt(62);
buf.append(str.charAt(num));
}
return buf.toString();
}
/**
* @Title: loginfo
* @Description: 输出LOG
* @param String
* tag
* @param String
* info
* @param
* @return
* @throws UiObjectNotFoundException
*/
public static void loginfo(String tag, String info) {
System.out.println(TAG + ":" + info + "\n");
Log.d(TAG + tag, info);
}
/**
* @Title: loginfo
* @Description: 输出LOG
* @param String
* tag
* @param String
* info
* @param UiObjectNotFoundException
* e
* @return
* @throws UiObjectNotFoundException
*/
public static void loginfo(String tag, String info,
UiObjectNotFoundException e) {
int num = e.getStackTrace().length;
for (int i = 0; i < num; i++) {
loginfo(tag,
e.getStackTrace()[i].getClassName() + "."
+ e.getStackTrace()[i].getMethodName() + "("
+ e.getStackTrace()[i].getFileName() + ":"
+ e.getStackTrace()[i].getLineNumber() + ")");
}
}
// ningbiao
/**
* @Title: clickObjectByText
* @Description: 通过Text查找并点击对象
* @param
* @param
* @param
* @return
* @throws UiObjectNotFoundException
*/
public void clickObjectByText(String text) throws UiObjectNotFoundException {
UiObject object = findByText(text);
checkPoint("clickObjectByText fail", object.exists());
object.clickAndWaitForNewWindow();
}
public void clickObjectByDes(String text) throws UiObjectNotFoundException {
UiObject object = findByDesc(text);
checkPoint("clickObjectByDes fail", object.exists());
object.clickAndWaitForNewWindow();
}
/**
* @Title: clickObjectByID
* @Description: 通过ID查找并点击对象
* @param
* @param
* @param
* @return
* @throws UiObjectNotFoundException
*/
public void clickObjectByID(String resourceID)
throws UiObjectNotFoundException {
UiObject object = findById(resourceID);
checkPoint("clickObjectByID fail", object.exists());
object.clickAndWaitForNewWindow();
}
/**
* @Title: clickObjectByClassName
* @Description: 通过Text查找并点击对象
* @param
* @param
* @param
* @return
* @throws UiObjectNotFoundException
*/
public void clickObjectByClassName(String className)
throws UiObjectNotFoundException {
UiObject object = findByClassName(className);
checkPoint("text object is not exists", object.exists());
object.clickAndWaitForNewWindow();
}
// click if object exists
/**
* @Title: clickObjectByTextIfExists
* @Description: 通过Text查找并点击对象(对象存在)
* @param
* @param
* @param
* @return
* @throws UiObjectNotFoundException
*/
public void clickObjectByTextIfExists(String text)
throws UiObjectNotFoundException {
UiObject object = findByText(text);
if (object.exists()) {
object.clickAndWaitForNewWindow();
}
}
/**
* @Title: clickObjectByIDIfExists
* @Description: 通过ID查找并点击对象(对象存在)
* @param
* @param
* @param
* @return
* @throws UiObjectNotFoundException
*/
public void clickObjectByIDIfExists(String resourceID)
throws UiObjectNotFoundException {
UiObject object = findById(resourceID);
if (object.exists()) {
object.clickAndWaitForNewWindow();
}
}
/**
* @Title: clickObjectByClassNameIfExists
* @Description: 通过类名查找并点击对象(对象存在)
* @param
* @param
* @param
* @return
* @throws UiObjectNotFoundException
*/
public void clickObjectByClassNameIfExists(String className)
throws UiObjectNotFoundException {
UiObject object = findByClassName(className);
if (object.exists()) {
object.clickAndWaitForNewWindow();
}
}
// click if object exists end.
/**
* @Title: clickJustOnceButton
* @Description: 点击Just once按钮
* @param
* @param
* @param
* @return
* @throws UiObjectNotFoundException
*/
public void clickJustOnceButton() throws UiObjectNotFoundException {
if (checkObjectExistsByText(readResResource("ui_text_just_once"))) {
loginfo(TAG, "Has just once button,click!");
clickObjectByText(readResResource("ui_text_just_once"));
}
}
/**
* @Title: clickAlwaysButton
* @Description: 点击always按钮
* @param
* @param
* @param
* @return
* @throws UiObjectNotFoundException
*/
public void clickAlwaysButton() throws UiObjectNotFoundException {
clickObjectByText(readResResource("ui_text_always"));
}
/**
* @Title: checkObjectExistsByID
* @Description: 通过对象的资源Id,判断对象是否存在
* @param resourceId
* @param
* @param
* @return
* @throws UiObjectNotFoundException
*/
public static boolean checkObjectExistsByID(String resourceId)
throws UiObjectNotFoundException {
UiObject object = findById(resourceId);
return object.exists();
}
public static boolean checkObjectExistsByIDAndText(String resourceId,
String text) throws UiObjectNotFoundException {
UiObject object = findByResourceIdAndText(resourceId, text);
return object.exists();
}
/**
* @Title: checkObjectExistsByText
* @Description: 通过Text中的字符,判断对象是否存在
* @param text
* @param
* @param
* @return
* @throws UiObjectNotFoundException
*/
public static boolean checkObjectExistsByText(String text)
throws UiObjectNotFoundException {
UiObject object = findByText(text);
return object.exists();
}
/**
* @Title: checkObjectExistsByTextContains
* @Description: 通过Text中包含的字符,判断对象是否存在
* @param text
* @param
* @param
* @return
* @throws UiObjectNotFoundException
*/
public static boolean checkObjectExistsByTextContains(String text)
throws UiObjectNotFoundException {
UiObject object = findByTextContains(text);
return object.exists();
}
/**
* @Title: checkObjectExistsByTextDesc
* @Description: 通过Desc中包含的字符,判断对象是否存在
* @param text
* @param
* @param
* @return
* @throws UiObjectNotFoundException
*/
public static boolean checkObjectExistsByTextDesc(String text)
throws UiObjectNotFoundException {
UiObject object = findByDesc(text);
return object.exists();
}
/**
* @Title: checkObjectExistsByPackage
* @Description: 通过包名,判断对象是否存在
* @param text
* @param
* @param
* @return
* @throws UiObjectNotFoundException
*/
public static boolean checkObjectExistsByPackage(String packageName)
throws UiObjectNotFoundException {
UiObject object = findByPackageName(packageName);
return object.exists();
}
/**
* @Title: connectMobileData
* @Description: 进入设置打开数据链接
* @param
* @param
* @param
* @return
* @throws UiObjectNotFoundException
*/
public void connectMobileData() throws UiObjectNotFoundException {
goHome();
openApp(UiUtil.readResResource("ui_text_setting"));
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
enterSetChild(UiUtil.readResResource("settings_text_sim_cards"));
} else {
enterSetChild(UiUtil.readResResource("settings_text_mulitsim"));
}
UiObject universal_switch = findByIdIndex(
"com.android.settings:id/universal_switch", 1);
boolean checked = universal_switch.isChecked();
loginfo(TAG, "connectMobileData checked=" + checked);
if (!checked) {
universal_switch.clickAndWaitForNewWindow();
}
}
/**
* @Title: UiUtil
* @Description: 从垂直滚动listview中按名称查找控件
* @param scrollId
* @param name
* @return
* @throws UiObjectNotFoundException
* @throws
*/
public UiObject findByTextAsVerticalScroll(String scrollId, String name)
throws UiObjectNotFoundException {
// UiScrollable scrollView = new UiScrollable(new UiSelector().resourceId(scrollId).scrollable(true));
UiScrollable scrollView = new UiScrollable(new UiSelector().resourceId(scrollId));
scrollView.setAsVerticalList();
UiObject object = findByText(name);
int i = 0;
while (!object.exists()) {
scrollView.scrollForward();
i++;
if (i == 50) {
break;
}
}
return object;
}
// ningbiao
/**
* @Title: addWatcher
* @Description: 添加监听器
* @param watcherName
* @param watcherObject
* @param conditionObject
* @return
* @throws
*/
public void addWatcher(final String watcherName,
final UiObject watcherObject, final UiObject conditionObject) {
try {
UiDevice.getInstance().registerWatcher(watcherName,
new UiWatcher() {
public boolean checkForCondition() {
// TODO Auto-generated method stub
if (watcherObject.exists()) {
try {
loginfo(TAG, "watcherName:" + watcherName);
if (conditionObject.exists()
&& conditionObject.isEnabled()) {
conditionObject
.clickAndWaitForNewWindow();
}
} catch (UiObjectNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
loginfo(TAG, "addWatcher!", e);
return false;
}
sleep(2000);
return true;
} else {
return false;
}
}
});
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
loginfo(TAG, "addWatcher!");
}
}
/**
* @Title: addWatcherCheckable
* @Description: 添加勾选框监听器
* @param watcherName
* @param watcherObject
* @param conditionObject
* @return
* @throws
*/
public void addWatcherCheckable(String watcherName,
final UiObject watcherObject, final UiObject conditionObject) {
try {
UiDevice.getInstance().registerWatcher(watcherName,
new UiWatcher() {
public boolean checkForCondition() {
// TODO Auto-generated method stub
if (watcherObject.exists()) {
try {
if (conditionObject.isCheckable()
&& !conditionObject.isChecked()) {
conditionObject
.clickAndWaitForNewWindow();
}
} catch (UiObjectNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
loginfo(TAG, "addWatcher!", e);
return false;
}
return true;
} else {
return false;
}
}
});
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
loginfo(TAG, "addWatcher!");
}
}
/**
* @Title: realeseWatcher
* @Description: 取消监听器
* @param watcherName
* @return
* @throws
*/
public void realeseWatcher(String watcherName) {
UiDevice.getInstance().removeWatcher(watcherName);
}
public static String getSDPath(){
File sdDir = null;
boolean sdCardExist = Environment.getExternalStorageState()
.equals(android.os.Environment.MEDIA_MOUNTED); //判断sd卡是否存在
if (sdCardExist)
{
sdDir = Environment.getExternalStorageDirectory();//获取根目录
}
loginfo(TAG, "sd card dir = "+sdDir.toString());
return sdDir.toString();
}
public void swipe(SWIPEDIRECTION direction) {
int xLocation;
int yLocation;
xLocation = UiDevice.getInstance().getDisplayWidth();
yLocation = UiDevice.getInstance().getDisplayHeight() / 2;
switch (direction) {
case LEFT:
UiDevice.getInstance().swipe(xLocation - 10, yLocation, 10,
yLocation, 10);
sleep(2000);
break;
case RIGHT:
UiDevice.getInstance().swipe(10, yLocation, xLocation - 10,
yLocation, 10);
sleep(2000);
break;
default:
break;
}
}
}
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Random;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.json.JSONArray;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Environment;
import android.os.RemoteException;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.view.InputDevice;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import com.android.uiautomator.core.UiCollection;
import com.android.uiautomator.core.UiDevice;
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.core.UiWatcher;
import com.android.uiautomator.testrunner.UiAutomatorTestCase;
import com.sprd.uiautomator.camera.CameraUtils.SWIPEDIRECTION;
public class UiUtil extends UiAutomatorTestCase {
public static String TAG = "testlog";
// private static final String path_screenshot =
// "/storage/sdcard0/slog/screenshot/";
private static final String dir_result = "result/";
private static final String dir_fail = "fail/";
private static final String path_screenshot = readConfig("path_screenshot");//getSDPath()+"/";
private static final String path_screenshot_result = path_screenshot
+ dir_result;
private static final String path_screenshot_fail = path_screenshot
+ dir_fail;
public static final String OWN_NUMBER_OF_SIM1 = readConfig("SIM1_Number");
public static final String OWN_NUMBER_OF_SIM2 = readConfig("SIM2_Number");
// public static final String TEST_CONTACT_NAME = readConfig("Contacts_Name");
public static final String TEST_CONTACT_NUMBER = readConfig("Contacts_Number");
// ningbiao
public static final String ACCOUNT_NAME = readConfig("account_name");
public static final String ACCOUNT_PASSWORD = readConfig("account_password");
// ningbiao
public static final String TEST_RECIPIENTS = OWN_NUMBER_OF_SIM1;
// public static final String TEST_MESSAGE = readConfig("Message_Test_Content");
public static final int RES_CONFIG = 0;
public static final String RES_CONFIG_FILE = "config.xml";
public static final int RES_RESOURCE = 1;
public static final String RES_RESOURCE_FILE = "resource.xml";
public static final String RES_RESOURCE_FILE_EN = "resource-EN.xml";
public static final String RES_CONFIG_FOLER_CASE = "config_hq_uiautotest";
public static final String RES_CONFIG_PATH = "/data/local/tmp/"
+ RES_CONFIG_FOLER_CASE + "/";
public static enum SIM_SELECT_TYPE {
DATACONNECT, CALL, VIDEOCALL, MMS
}
public static enum CALL_SIM_TYPE {
SIM1, SIM2
}
public static enum PREFERRED_NETWORK_TYPE {
AUTO, GSM_ONLY, WCDMA_ONLY, TD_ONLY, LTE_ONLY
}
protected void setUp() throws Exception {
super.setUp();
// addWatcher();
// checkFirstPowerOn();
}
protected void tearDown() throws Exception {
// releaseAllWatcher();
super.tearDown();
}
// ningbiao add begin
private static String[][] setupWizard = {
// welcome
{ "Welcome", "com.google.android.setupwizard:id/start", "2" },
// when there is no sim cards
{
"Insert SIM cards",
"com.google.android.setupwizard:id/setup_wizard_navbar_next",
"2" },
// select prime sim card
{
"Select a SIM for cellular data",
"com.google.android.setupwizard:id/setup_wizard_navbar_next",
"2" },
// select sim for calls
{
"Select a SIM for calls",
"com.google.android.setupwizard:id/setup_wizard_navbar_next",
"2" },
// select sim for sms
{
"Select a SIM for text messages",
"com.google.android.setupwizard:id/setup_wizard_navbar_next",
"2" },
// select wifi hotpot
{ "Select Wi‑Fi network",
"com.android.settings:id/setup_wizard_navbar_next", "2" },
// skip wifi connect
{ "Skip anyway", "android:id/button1", "2" },
// connect check
{
"Checking connection…",
"com.google.android.setupwizard:id/setup_wizard_navbar_next",
"30" },
// connect skip
{ "Skip anyway", "android:id/button1", "2" },
// when there is no sim cards
{
"Date & time",
"com.google.android.setupwizard:id/setup_wizard_navbar_next",
"2" },
// input name
{
"Name",
"com.google.android.setupwizard:id/setup_wizard_navbar_next",
"10" },
// more
{
"Google services",
"com.google.android.setupwizard:id/setup_wizard_navbar_next",
"2" },
// more
{
"Google services",
"com.google.android.setupwizard:id/setup_wizard_navbar_next",
"2" },
// next
{
"Google services",
"com.google.android.setupwizard:id/setup_wizard_navbar_next",
"2" },
// welcome
{
"Welcome",
"com.google.android.googlequicksearchbox:id/cling_dismiss_longpress_info",
"2" },
// welcome(has not GMS)
{ "Welcome",
"com.android.launcher3:id/cling_dismiss_longpress_info",
"2" } };
private static void checkCardSel() throws UiObjectNotFoundException {
loginfo(TAG, "checkCardSel");
UiObject objCardSel = findByText("Select primary card");
UiObject objCardSelCN = findByText("主卡选择");
if (objCardSel.exists() || objCardSelCN.exists()) {
loginfo(TAG, "find primary card");
UiObject objTopItem = findById("android:id/select_dialog_listview")
.getChild(
new UiSelector().className(
"android.widget.LinearLayout").index(0));
if (objTopItem.exists()) {
objTopItem.click();
}
}
}
private static void checkUsbPrompt() throws UiObjectNotFoundException {
loginfo(TAG, "checkUsbPrompt");
UiObject usbTitle = findByText("USB computer connection");
if (usbTitle.exists()) {
pressBack();
}
}
private static void keepBackLightOn() {
try {
if (!isScreenOn()) {
// UiDevice.getInstance().pressKeyCode(26);
UiDevice.getInstance().wakeUp();
}
} catch (Exception e) {
}
}
private boolean clickNextIfExistByTitleAndId(String title, String id,
int timeout) throws UiObjectNotFoundException {
// if(title.equals("Name")){
// Configurator.getInstance().setWaitForIdleTimeout(5 * 1000);
// }else{
// Configurator.getInstance().setWaitForIdleTimeout(10 * 1000);
// }
// UiObject objTitle = findByTextContains(title);
UiObject objId = findById(id);
loginfo(TAG, "check next title:" + title + ",id:" + id + ",timeout:"
+ timeout);
while (timeout-- >= 0) {
Sleep(1000);
onScreen();
// if (!objTitle.exists()) {
// // keepBackLightOn();
// loginfo(TAG, "!objTitle.exists() timeout:" + timeout);
// continue;
// }
if (!objId.exists()) {
// keepBackLightOn();
loginfo(TAG, "!objId.exists() timeout:" + timeout);
continue;
}
if (!objId.isEnabled()) {
// keepBackLightOn();
loginfo(TAG, "!objId.isEnabled() timeout:" + timeout);
continue;
}
objId.clickAndWaitForNewWindow();
return true;
}
return false;
}
private void clickSetupWizard() throws UiObjectNotFoundException,
RemoteException {
loginfo(TAG, "clickSetupWizard start...");
for (int i = 0; i < setupWizard.length; i++) {
loginfo(TAG, "check " + setupWizard[i][0]);
onScreen();
boolean result = clickNextIfExistByTitleAndId(setupWizard[i][0],
setupWizard[i][1], Integer.parseInt(setupWizard[i][2]));
if (!result && i == 0) {
loginfo(TAG,
"clickSetupWizard first welcome ui result is false!");
break;
}
}
loginfo(TAG, "clickSetupWizard end...");
}
public void checkFirstPowerOn() throws Exception {
loginfo(TAG, "checkFirstPowerOn");
updateLanguage(Locale.ENGLISH);
sleep(2000);
onScreen();
clickSetupWizard();
loginfo(TAG, "checkFirstPowerOn.........");
}
public void checkLongpress() throws Exception {
int length = setupWizard.length;
loginfo(TAG, "checkLongpress length=" + length);
if (length <= 0) {
return;
}
clickNextIfExistByTitleAndId(setupWizard[length - 1][0],
setupWizard[length - 1][1],
Integer.parseInt(setupWizard[length - 1][2]));
}
public static boolean checkInLauncher() throws UiObjectNotFoundException {
onScreen();
boolean searchBox = checkObjectExistsByID("com.google.android.googlequicksearchbox:id/search_plate");
boolean appsButton = checkObjectExistsByTextDesc(readResResource("ui_text_application")) && false;
boolean nativeLauncherPackage = checkObjectExistsByPackage("com.android.launcher3");
loginfo(TAG, "checkInLauncher searchBox=" + searchBox + ",appsButton="
+ appsButton + ",nativeLauncherPackage="
+ nativeLauncherPackage);
return searchBox || appsButton || nativeLauncherPackage;
}
public void addWatcher() throws Exception {
addWatcher(
"selectPrimaryCard",
findByText("Select primary card"),
findById("android:id/select_dialog_listview").getChild(
new UiSelector().className(
"android.widget.LinearLayout").index(0)));
addWatcher(
"selectPrimaryCardCN",
findByText("主卡选择"),
findById("android:id/select_dialog_listview").getChild(
new UiSelector().className(
"android.widget.LinearLayout").index(0)));
addWatcher(
"launcherWelcome",
findById("com.android.launcher3:id/cling_dismiss_longpress_info"),
findById("com.android.launcher3:id/cling_dismiss_longpress_info"));
addWatcher(
"launcherWelcomeGMS",
findById("com.google.android.googlequicksearchbox:id/cling_dismiss_longpress_info"),
findById("com.google.android.googlequicksearchbox:id/cling_dismiss_longpress_info"));
addWatcher("skipAnyway", findByText("Skip anyway"),
findById("android:id/button1"));
addWatcher(
"navbarNext",
findById("com.google.android.setupwizard:id/setup_wizard_navbar_next"),
findById("com.google.android.setupwizard:id/setup_wizard_navbar_next"));
addWatcher("skipNext",
findById("com.android.settings:id/setup_wizard_navbar_next"),
findById("com.android.settings:id/setup_wizard_navbar_next"));
addWatcher("wizardStart",
findById("com.google.android.setupwizard:id/start"),
findById("com.google.android.setupwizard:id/start"));
addWatcher("simNotify1", findByText("com.android.stk1:id/button_ok"),
findById("com.android.stk1:id/button_ok"));
addWatcher("simNotify2", findByText("com.android.stk2:id/button_ok"),
findById("com.android.stk2:id/button_ok"));
addWatcherCheckable("Aceptar", findByText("No volver a mostrar"),
findByText("Aceptar"));
}
public void releaseAllWatcher() throws Exception {
realeseWatcher("selectPrimaryCard");
realeseWatcher("selectPrimaryCardCN");
realeseWatcher("launcherWelcome");
realeseWatcher("launcherWelcomeGMS");
realeseWatcher("skipAnyway");
realeseWatcher("navbarNext");
realeseWatcher("skipNext");
realeseWatcher("wizardStart");
realeseWatcher("simNotify1");
realeseWatcher("simNotify2");
realeseWatcher("Aceptar");
}
// ningbiao add end
public static enum SHARE_TYPE {
MESSAGING, EMAIL, BLUETOOTH, GMAIL
}
/**
* 电话:com.android.dialer/com.android.dialer.DialtactsActivity
* 联系�?com.android.contacts/com.android.contacts.activities.PeopleActivity
* 信息:com.android.mms/.ui.ConversationList
* 浏览�?com.android.browser/.BrowserActivity
* 设置:com.android.settings/.Settings
*/
public static void openAppBypkgName(String name) {
try {
String pkgname = "";
if (name == "Dialer"
|| TextUtils.equals(name,
readResResource("phone_text_app_name"))) {
pkgname = "com.android.dialer/com.android.dialer.DialtactsActivity";
} else if (name == "People"
|| TextUtils.equals(name,
readResResource("contact_text_app_name_contacts"))
|| TextUtils.equals(name,
readResResource("contact_text_app_name"))) {
pkgname = "com.android.contacts/com.android.contacts.activities.PeopleActivity";
} else if (name == "Messaging"
|| TextUtils.equals(name,
readResResource("mms_text_app_name"))) {
pkgname = "com.android.mms/com.android.mms.ui.ConversationList";
} else if (name == "Browser"
|| TextUtils.equals(name,
readResResource("ui_text_browser"))) {
pkgname = "com.android.browser/.BrowserActivity";
} else if (name == "Settings"
|| TextUtils.equals(name,
readResResource("ui_text_setting"))) {
pkgname = "com.android.settings/.Settings";
} else if (name == "Calculator"
|| TextUtils.equals(name,
readResResource("ui_text_calculator"))) {
pkgname = "com.android.calculator2/.Calculator";
} else if (name == "Calendar"
|| TextUtils.equals(name,
readResResource("calendar_text_app_name"))) {
pkgname = "com.android.calendar/.AllInOneActivity";
} else if (name == "Camera"
|| TextUtils.equals(name,
readResResource("camera_text_app_name"))) {
pkgname = "com.android.camera2/com.android.camera.CameraLauncher";
} else if (name == readResResource("clock_text_app_name")) {
pkgname = "com.android.deskclock/.DeskClock";
} else if (name == "FileExplore"
|| TextUtils.equals(name,
readResResource("fileexplorer_text_app_name"))) {
pkgname = "com.sprd.fileexplorer/.activities.FileExploreActivity";
} else if (name == "Gallery"
|| TextUtils.equals(name,
readResResource("gallery_text_app_name"))) {
pkgname = "com.android.gallery3d/.app.GalleryActivity";
} else if (name == "Music"
|| TextUtils.equals(name, readResResource("ui_text_music"))) {
pkgname = "com.android.music/.MusicBrowserActivity";
} else if (name == "SoundRecorder"
|| TextUtils
.equals(name, readResResource("ui_text_record"))) {
pkgname = "com.android.soundrecorder/.SoundRecorder";
} else if (name == "Email") {
pkgname = "com.android.email/.activity.Welcome";
} else if (name == "FmRadio"
|| TextUtils.equals(name, readResResource("ui_text_fm"))) {
pkgname = "com.thunderst.radio/.FMRadioMainActivity";
} else if (name == "CallLog"
|| TextUtils.equals(name,
readResResource("calllog_text_app_name"))) {
pkgname = "com.android.dialer/com.android.dialer.calllog.CallLogActivity";
} else if (name == "Email"
|| TextUtils.equals(name,
readResResource("email_text_app_name"))) {
pkgname = "com.android.email/.activity.Welcome";
}
UiDevice.getInstance().pressHome();
UiUtil.Sleep(1000);
execCommand("am start -n " + pkgname);
UiUtil.Sleep(3000);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
// checkPoint("openApp", false);
}
}
// 通过ID查找
public static UiObject findById(String text)
throws UiObjectNotFoundException {
UiObject appBtn = new UiObject(new UiSelector().resourceId(text));
return appBtn;
}
// 通过resource和descrice查找
public static UiObject findByResourceIdAndDesc(String className, String text)
throws UiObjectNotFoundException {
UiObject appBtn = new UiObject(new UiSelector().resourceId(className)
.description(text));
return appBtn;
}
// 按Text Contains定位
public static UiObject findByTextContains(String text) {
UiObject getItem = new UiObject(new UiSelector().textContains(text));
return getItem;
}
// 通过resource和index查找
public static UiObject findByResourceIdAndIndex(String className, int index)
throws UiObjectNotFoundException {
UiObject appBtn = new UiObject(new UiSelector().resourceId(className)
.index(index));
return appBtn;
}
// 通过ID,instance查找
public static UiObject findByIdInStance(String text, int index)
throws UiObjectNotFoundException {
UiObject appBtn = new UiObject(new UiSelector().resourceId(text)
.instance(index));
return appBtn;
}
// 通过ID,index查找
public static UiObject findByIdIndex(String text, int index)
throws UiObjectNotFoundException {
UiObject appBtn = new UiObject(new UiSelector().resourceId(text).index(
index));
return appBtn;
}
// 通过Uisourceid查找
public static UiObject findByResourceId(String text)
throws UiObjectNotFoundException {
UiObject appBtn = new UiObject(new UiSelector().resourceId(text));
return appBtn;
}
// 按照className查找UiScrollable;
public static UiScrollable findUiScrollableByClassName(String className)
throws UiObjectNotFoundException {
UiScrollable scrItem = new UiScrollable(
new UiSelector().className(className));
return scrItem;
}
// 通过source和text查找
public static UiObject findByResourceIdAndText(String text1, String text2)
throws UiObjectNotFoundException {
UiObject appBtn = new UiObject(new UiSelector().resourceId(text1).text(
text2));
return appBtn;
}
// 通过source和text查找
public static UiObject findByResourceIdAndTextContains(String resourceId, String textContains)
throws UiObjectNotFoundException {
UiObject appBtn = new UiObject(new UiSelector().resourceId(resourceId).textContains(
textContains));
return appBtn;
}
// 按照className和index在UiScrollable中查找
public static UiScrollable findUiScrollableByClassNameAndInstance(
UiScrollable uiScrollable, String className, int index)
throws UiObjectNotFoundException {
UiScrollable scrItem = new UiScrollable(new UiSelector().className(
className).instance(index));
return scrItem;
}
// 获取UiCollection中的子对象的个数
public static int findChildCountFromUiCollectionByClassName(
UiCollection uiCollection, String className)
throws UiObjectNotFoundException {
return uiCollection
.getChildCount(new UiSelector().className(className));
}
// 在UiScrollable中通过className和instance查找
public static UiObject findFromUiScrollableByClassNameAndInstance(
UiScrollable uiScrollable, String className, int index)
throws UiObjectNotFoundException {
return uiScrollable.getChild(new UiSelector().className(className)
.index(index));
}
// 按className定位Scrollable
public static UiScrollable findScrollableByClass(String className) {
return new UiScrollable(new UiSelector().className(className));
}
// 按resource定位Scrollable
public static UiScrollable findScrollableByResource(String text) {
return new UiScrollable(new UiSelector().resourceId(text));
}
// 从UiScrollable得到子对象,通过className和instance
public static UiObject findChildFromUiScrollableByClassNameAndInstance(
UiScrollable scrollable, String className, int instance)
throws UiObjectNotFoundException {
return scrollable.getChild(new UiSelector().className(className)
.instance(instance));
}
// 从UiScrollable得到子对象,通过TEXT
public static UiObject findChildFromUiScrollableByText(
UiScrollable scrollable, String text)
throws UiObjectNotFoundException {
return scrollable.getChild(new UiSelector().text(text));
}
// 获得collection对象中的子元素个数,以className作为筛选标准
public static int findChildCountFromCollection(UiCollection collection,
String className) {
return collection.getChildCount(new UiSelector().className(className));
}
// 在UiScrollable中通过className查找
public static UiObject findFromUiScrollableByClassName(
UiScrollable uiScrollable, String className)
throws UiObjectNotFoundException {
return uiScrollable.getChild(new UiSelector().className(className));
}
// 通过resource查找UiCollection
public static UiCollection findUicollectionByResource(String text)
throws UiObjectNotFoundException {
UiCollection uiCollection = new UiCollection(
new UiSelector().resourceId(text));
return uiCollection;
}
// 通过test查找
public static UiObject findByText(String text)
throws UiObjectNotFoundException {
UiObject appBtn = new UiObject(new UiSelector().text(text));
return appBtn;
}
// 通过package查找
public static UiObject findByPackage(String text)
throws UiObjectNotFoundException {
UiObject appBtn = new UiObject(new UiSelector().packageName(text));
return appBtn;
}
// 通过description查找
public static UiObject findByDesc(String text)
throws UiObjectNotFoundException {
UiObject appBtn = new UiObject(new UiSelector().description(text));
return appBtn;
}
// 通过className查找
public static UiObject findByClassName(String className)
throws UiObjectNotFoundException {
UiObject appBtn = new UiObject(new UiSelector().className(className));
return appBtn;
}
// 通过className和index查找
public static UiObject findByClassNameAndIndex(String className, int index)
throws UiObjectNotFoundException {
UiObject appBtn = new UiObject(new UiSelector().className(className)
.index(index));
return appBtn;
}
// 通过className和text查找
public static UiObject findByClassNameAndText(String className, String text)
throws UiObjectNotFoundException {
UiObject appBtn = new UiObject(new UiSelector().className(className)
.text(text));
return appBtn;
}
// 通过descrice和index查找
public static UiObject findByDescContInstance(String text, int index)
throws UiObjectNotFoundException {
UiObject appBtn = new UiObject(new UiSelector().descriptionContains(
text).instance(index));
return appBtn;
}
// Sleep();
public static void Sleep(int ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
// 进入APPS
public static boolean openApp(String appName)
throws UiObjectNotFoundException {
loginfo(TAG, "openApp :" + appName);
try {
UiObject appButton;
appButton = findByText(appName);
if (appButton.exists()) {
appButton.clickAndWaitForNewWindow();
} else {
UiObject appBtn = findByDesc(readResResource("ui_text_application"));
if (appBtn.exists()) {
appBtn.clickAndWaitForNewWindow();
appButton = findByClassNameAndText(
"android.widget.TextView", appName);
if (!appButton.exists()) {
UiSelector uiselector = new UiSelector();
UiScrollable uiscrollable = new UiScrollable(
uiselector.scrollable(true));
uiscrollable.setAsHorizontalList();
uiscrollable.flingToBeginning(5);
int count = 10;
if (!appButton.exists()) {
while (!appButton.exists() && count-- >= 0) {
uiscrollable.swipeLeft(50);
}
}
count = 10;
if (!appButton.exists()) {
while (!appButton.exists() && count-- >= 0) {
uiscrollable.swipeRight(50);
}
}
}
if (appButton.exists()) {
// System.out.println("------------------click");
appButton.clickAndWaitForNewWindow();
} else {
System.out.println("No Found " + appName + " in home");
return false;
}
} else {
appButton = findByClassNameAndText(
"android.widget.TextView", appName);
if (!appButton.exists()) {
UiSelector uiselector = new UiSelector();
UiScrollable uiscrollable = new UiScrollable(
uiselector.scrollable(true));
uiscrollable.setAsHorizontalList();
uiscrollable.flingToBeginning(5);
int count = 10;
if (!appButton.exists()) {
while (!appButton.exists() && count-- >= 0) {
uiscrollable.swipeLeft(50);
}
}
count = 10;
if (!appButton.exists()) {
while (!appButton.exists() && count-- >= 0) {
uiscrollable.swipeRight(50);
}
}
}
if (appButton.exists()) {
// System.out.println("------------------click");
appButton.clickAndWaitForNewWindow();
} else {
System.out
.println("Can't found Apps button,use api start activity!"
+ appName + "\n");
// openAppBypkgName(appName);
return false;
}
}
}
Sleep(2000);
} catch (Exception e) {
return false;
}
return true;
}
// 切换中英文
// public static void switchLanguage()throws UiObjectNotFoundException {
// UiObject appBtn =
// findByResourceId("android:id/action_bar_overlay_layout");
// appBtn.clickTopLeft();
// Sleep(2000);
// }
// 测试结果检查点
public static void checkPointForRsult(String msg) {
SimpleDateFormat format = new SimpleDateFormat("MM_dd_HH_mm_ss");
Date curDate = new Date(System.currentTimeMillis());
String time = format.format(curDate);
loginfo(TAG, "path_screenshot_result = " + path_screenshot_result);
if (new File(path_screenshot_result).exists() == false) {
boolean res = new File(path_screenshot_result).mkdirs();
loginfo(TAG, "mkdir return " + res);
}
File screenshot = new File(path_screenshot_result + msg + "_" + time
+ ".png");
UiDevice.getInstance().takeScreenshot(screenshot);
loginfo(TAG, "checkPointForRsult msg=" + msg);
}
// 测试检查点
public static void checkPoint(String msg, boolean statue) {
if (!statue) {
SimpleDateFormat format = new SimpleDateFormat("MM_dd_HH_mm_ss");
Date curDate = new Date(System.currentTimeMillis());
String time = format.format(curDate);
loginfo(TAG, "path_screenshot_fail = " + path_screenshot_fail);
if (new File(path_screenshot_fail).exists() == false) {
boolean res = new File(path_screenshot_fail).mkdirs();
loginfo(TAG, "mkdir return " + res);
}
File screenshot = new File(path_screenshot_fail + msg + "_" + time
+ ".png");
UiDevice.getInstance().takeScreenshot(screenshot);
loginfo(TAG, "checkPoint msg=" + msg);
assertTrue(msg, statue);
}
}
public static void checkPoint(String msg, boolean statue,
UiObjectNotFoundException e) {
if (!statue) {
loginfo(TAG, msg, e);
checkPoint(msg, statue);
}
}
/*
* 修改语言输入法 输入法选择:启用【谷歌拼音输入法】\启用【Android 键盘 (AOSP)】
*/
/*
* public static void changeInputMethod(String inputMethodName) throws
* UiObjectNotFoundException { if
* (UiUtil.openApp(readResResource("ui_text_setting"))) { UiObject
* languageAndInputMethodItem = new UiObject( new
* UiSelector().text(readResResource("ui_text_lanuage_input"))); if
* (languageAndInputMethodItem.exists()) { UiObject myDeviceTab = new
* UiObject( new UiSelector().text(readResResource("ui_text_device")));
* myDeviceTab.click();
* languageAndInputMethodItem.clickAndWaitForNewWindow(); UiScrollable
* languageAndInputMethodList = new UiScrollable( new
* UiSelector().className("android.widget.ListView")); int count =
* languageAndInputMethodList .getChildCount(new UiSelector()
* .className("android.widget.LinearLayout")); UiObject childCheckBox1 =
* null; UiObject childCheckBox2 = null; UiObject chooseItem = null; for
* (int i = 0; i < count; i++) { UiObject item = languageAndInputMethodList
* .getChildByInstance(new UiSelector()
* .className("android.widget.LinearLayout"), i); // 启用【谷歌拼音输入法】 UiObject
* childTextView1 = item.getChild(new UiSelector()
* .text(readResResource("ui_text_input_google")));
*
* if (childTextView1.exists()) { childCheckBox1 = item.getChild(new
* UiSelector() .className("android.widget.CheckBox")); if
* (!childCheckBox1.isChecked()) { childCheckBox1.click(); } } // 启用【Android
* 键盘 (AOSP)】 UiObject childTextView2 = item.getChild(new UiSelector()
* .text("Android 键盘 (AOSP)"));
*
* if (childTextView2.exists()) { childCheckBox2 = item.getChild(new
* UiSelector() .className("android.widget.CheckBox")); if
* (!childCheckBox2.isChecked()) { childCheckBox2.click(); } } // 选择输入法
* UiObject childTextView3 = item.getChild(new UiSelector()
* .text(readResResource("ui_text_default"))); if (childTextView3.exists())
* { chooseItem = childTextView3; } } if (childCheckBox1 != null &&
* childCheckBox2 != null && chooseItem != null) {
* chooseItem.clickAndWaitForNewWindow(); UiObject choose = new UiObject(
* new UiSelector().text(inputMethodName));
* choose.clickAndWaitForNewWindow(); } } } }
*/
/*
* 测试当前输入法是否为英文 参数:UiObject 默认字符串(如地址栏默认包含http://) 返回:英文true,其他false
*/
public static boolean testInputIsEng(UiObject ob, String str)
throws UiObjectNotFoundException {
String s = ob.getText();
if (!s.equals(str)) {
return true;
} else {
return false;
}
}
/*
* 在定位到输入框的情况下,该方法在输入时更换输入法
*/
/*
* public static void changeInputMethodByShotCut(String inputMethodName,
* UiDevice uiDevice) throws UiObjectNotFoundException {
* uiDevice.drag(uiDevice.getDisplayWidth() / 2, 0,
* uiDevice.getDisplayWidth() / 2, uiDevice.getDisplayHeight(), 10);
* UiUtil.Sleep(2000); UiObject chooseItem = new UiObject(new
* UiSelector().text(readResResource("ui_text_input_sel")));
* chooseItem.clickAndWaitForNewWindow(); UiUtil.Sleep(1000); UiObject
* choose = new UiObject(new UiSelector().text(inputMethodName));
* choose.clickAndWaitForNewWindow(); }
*/
/*
* 点亮屏幕并解锁手机
*/
public static void onScreen() throws UiObjectNotFoundException {
System.out.print("onScreen android version:" + Build.VERSION.SDK_INT
+ "\n");
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
onScreenAndroidL();
} else {
try {
if (!UiDevice.getInstance().isScreenOn()) {
UiDevice.getInstance().pressKeyCode(26);
}
UiObject lockKey = findByResourceId("com.android.keyguard:id/keyguard_selector_view_frame");
if (lockKey.exists()) {
int left = lockKey.getBounds().left;
int right = lockKey.getBounds().right;
int top = lockKey.getBounds().top;
int bottom = lockKey.getBounds().bottom;
int x = (left + right) / 2;
int y = (top + bottom) / 2;
UiDevice.getInstance().drag(x, y, right, y, 10);
} else {
System.out.print("No Found lock Key\n");
}
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// ningbiao
public static void onScreenAndroidL() throws UiObjectNotFoundException {
try {
if (!UiDevice.getInstance().isScreenOn()) {
UiDevice.getInstance().pressKeyCode(26);
}
UiObject lockKey = findByResourceId("com.android.systemui:id/lock_icon");
if (lockKey.exists()) {
int w = UiDevice.getInstance().getDisplayWidth();
int h = UiDevice.getInstance().getDisplayHeight();
lockKey.dragTo(w / 2, h / 2, 10);
} else {
System.out.print("No Found lock Key\n");
}
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 进入设置中改为谷歌输入法
public static void switchLan() throws UiObjectNotFoundException {
UiDevice.getInstance().pressHome();
UiUtil.openApp(readResResource("ui_text_setting"));
UiScrollable list = new UiScrollable(new UiSelector().scrollable(true));
list.setAsVerticalList();
UiObject item = new UiObject(
new UiSelector().text(readResResource("ui_text_lanuage_input")));
while (!item.exists()) {
list.flingForward();
}
item.clickAndWaitForNewWindow();
UiObject choose = UiUtil
.findByText(readResResource("ui_text_input_google"));
if (choose.exists() && !choose.isChecked() && choose.isCheckable()) {
choose.click();
UiUtil.Sleep(1000);
}
UiDevice.getInstance().pressHome();
}
// 输入的过程中将输入法更改为英文输入法(搜索联系人界面)
public static void switchLanguage() throws UiObjectNotFoundException {
UiDevice uiDevice = UiDevice.getInstance();
uiDevice.drag(uiDevice.getDisplayWidth() / 2, 0,
uiDevice.getDisplayWidth() / 2, uiDevice.getDisplayHeight(), 10);
UiUtil.Sleep(2000);
UiObject chooseItem = new UiObject(
new UiSelector().text(readResResource("ui_text_input_sel")));
chooseItem.clickAndWaitForNewWindow();
UiUtil.Sleep(2000);
UiObject choose = UiUtil.findByText(readResResource("ui_text_english"));
if (choose.exists())
choose.clickAndWaitForNewWindow();
UiUtil.Sleep(1000);
}
// 点击双卡弹出的提示,0为SIM1,1为SIM2
public static UiObject click_sim_byid(String first, String second, int sim)
throws UiObjectNotFoundException {
// TODO Auto-generated method stub
UiObject ab = new UiCollection(new UiSelector().className(first).index(
sim)).getChild(new UiSelector().resourceId(second));
return ab;
}
// 长按坐标点
public static void longclick(UiObject object)
throws UiObjectNotFoundException {
int x = (object.getBounds().left + object.getBounds().right) / 2;
int y = (object.getBounds().top + object.getBounds().bottom) / 2;
UiDevice.getInstance().drag(x, y, x, y, 20);
}
// 下拉通知栏 ,进入
public static void downScreen() throws UiObjectNotFoundException {
int xLocation;
int yLocation;
xLocation = UiDevice.getInstance().getDisplayWidth() / 2;
yLocation = UiDevice.getInstance().getDisplayHeight() / 2;
UiDevice.getInstance().swipe(xLocation, 0, xLocation, yLocation, 10);
}
// 清除后台
public static void clearBackgroundApps() throws UiObjectNotFoundException {
loginfo(TAG, "clearBackgroundApps");
try {
UiDevice.getInstance().pressRecentApps();
Sleep(5000);
UiObject clearBtn = findByResourceId(readResResource("ui_resid_recent_sprdramopt_view"));
if (clearBtn.exists()) {
clearBtn.click();
} else {
clearBtn = findByResourceId(readResResource("ui_resid_recent_dismiss"));
int count = 50;
while (clearBtn.exists() && count-- >= 0) {
clearBtn.click();
Sleep(2000);
}
}
pressHome();
Sleep(1000);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pressHome();
}
// 调节音量
public static void adjustVolume() throws UiObjectNotFoundException {
for (int i = 0; i < 10; i++) {
UiDevice.getInstance().pressKeyCode(KeyEvent.KEYCODE_VOLUME_UP);
UiUtil.Sleep(1000);
}
UiUtil.Sleep(5000);
for (int j = 0; j < 8; j++) {
UiDevice.getInstance().pressKeyCode(KeyEvent.KEYCODE_VOLUME_DOWN);
UiUtil.Sleep(1000);
}
UiUtil.Sleep(3000);
}
// 横竖屏旋转
public void gsensor() throws UiObjectNotFoundException, RemoteException {
UiDevice.getInstance().setOrientationLeft();
sleep(5000);
UiDevice.getInstance().setOrientationRight();
sleep(5000);
UiDevice.getInstance().setOrientationNatural();
sleep(5000);
}
// 保证正常退出应用
public static void goHome() throws UiObjectNotFoundException {
for (int i = 0; i < 5; i++) {
if (checkInLauncher()) {
loginfo(TAG, "Already in launcher!");
break;
}
pressBack();
Sleep(200);
}
pressHome();
}
public static void pressHome() throws UiObjectNotFoundException {
UiDevice.getInstance().pressHome();
}
public static void pressBack() throws UiObjectNotFoundException {
UiDevice.getInstance().pressBack();
}
public static void openNotification() throws UiObjectNotFoundException {
UiDevice.getInstance().openNotification();
}
public static void pressMenu() throws UiObjectNotFoundException {
UiDevice.getInstance().pressMenu();
}
public static void pressEnter() throws UiObjectNotFoundException {
UiDevice.getInstance().pressEnter();
}
public static void pressDPadUp() throws UiObjectNotFoundException {
UiDevice.getInstance().pressDPadUp();
}
public static void pressDPadDown() throws UiObjectNotFoundException {
UiDevice.getInstance().pressDPadDown();
}
public static void pressDPadLeft() throws UiObjectNotFoundException {
UiDevice.getInstance().pressDPadLeft();
}
public static void pressDPadRight() throws UiObjectNotFoundException {
UiDevice.getInstance().pressDPadRight();
}
public static boolean isScreenOn() throws RemoteException {
return UiDevice.getInstance().isScreenOn();
}
public static void openQuickSettings() throws UiObjectNotFoundException {
UiDevice.getInstance().openQuickSettings();
}
// 检查所有进入应用是否正确
public static void checkAppView(String name)
throws UiObjectNotFoundException {
if (name.equals(readResResource("ui_text_dial"))
|| name.equals(readResResource("dial_text_app_dial"))) {
UiObject dialBtn = findByResourceId(readResResource("dial_resid_dialpad_button"));
checkPoint("enter call fail ", dialBtn.exists());
} else if (name.equals(readResResource("ui_text_contact"))
|| name.equals(readResResource("contact_text_app_name_contacts"))) {
UiObject pb = findByDesc(readResResource("ui_text_contact_all"));
boolean contactsText = checkObjectExistsByText(name);
checkPoint("enter pb fail ", pb.exists() || contactsText);
} else if (name.equals(readResResource("ui_text_message"))) {
UiObject message = findByResourceIdAndText(
"android:id/action_bar_title",
readResResource("ui_text_message"));
boolean messageTitle = checkObjectExistsByText(readResResource("mms_text_app_name"));
checkPoint("enter message fail ", message.exists() || messageTitle);
} else if (name.equals(readResResource("ui_text_setting"))) {
UiObject setting = findByText(readResResource("ui_text_setting"));
checkPoint("enter setting fail ", setting.exists());
} else if (name.equals(readResResource("ui_text_calculator"))) {
UiObject calculate = findByResourceIdAndText(
"com.android.calculator2:id/del",
readResResource("ui_text_back"));
checkPoint("enter calculate fail ", calculate.exists());
} else if (name.equals(readResResource("ui_text_calendar"))) {
UiObject data = findByResourceIdAndDesc(
"com.android.calendar:id/action_today",
readResResource("ui_text_today"));
checkPoint("enter data fail ", data.exists());
} else if (name.equals(readResResource("ui_text_camera"))) {
UiObject camera = findByResourceId("com.android.camera2:id/filmstrip_bottom_controls");
UiObject notice = findByText(readResResource("ui_text_remember_address"));
boolean overlay = checkObjectExistsByID("com.android.camera2:id/mode_options_overlay");
checkPoint("enter camera fail ",
(camera.exists() || notice.exists() || overlay));
} else if (name.equals(readResResource("ui_text_clock"))) {
UiObject clock = findByResourceIdAndText(
"com.android.deskclock:id/tab_text",
readResResource("ui_text_alarm"));
checkPoint("enter clock fail ", clock.exists());
} else if (name.equals(readResResource("ui_text_gallary"))) {
UiObject picture = findByResourceId("com.android.gallery3d:id/gl_root_view");
checkPoint("enter picture fail ", picture.exists());
} else if (name.equals(readResResource("ui_text_video"))) {
UiObject video = findByResourceIdAndText("android:id/text1",
readResResource("ui_text_video"));
checkPoint("enter video fail", video.exists());
} else if (name.equals(readResResource("ui_text_music"))) {
UiObject music = findById(readResResource("music_resid_artisttab"));
checkPoint("enter music fail ", music.exists());
} else if (name.equals(readResResource("ui_text_record"))) {
UiObject recorder = findByText(readResResource("ui_text_save_record"));
checkPoint("enter recorder fail ", recorder.exists());
} else if (name.equals(readResResource("ui_text_playstore"))) {
UiObject addaccount = findByText(readResResource("playstore_add_account"));
UiObject confirm = findByText(readResResource("browser_text_ok"));
UiObject googleplay = findByResourceId("com.android.vending:id/search_box_idle_text");
checkPoint("enter playstore fail ", addaccount.exists() || confirm.exists() || googleplay.exists());
} else if (name.equals(readResResource("ui_text_fm"))) {
Sleep(3000);
UiObject storeBtn = findByText(readResResource("fm_text_save_channel"));
UiObject searchBtn = findByText(readResResource("fm_text_search"));
UiObject fm = findByText(readResResource("ui_text_fm"));
UiObject fm1 = findByText(readResResource("fm_text_airplane_warn"));
UiObject fm2 = findByText(readResResource("fm_text_earphone_warn"));
checkPoint(
"enter fm fail ",
(fm.exists() || fm1.exists() || fm2.exists()
|| storeBtn.exists() || searchBtn.exists()));
} else {
loginfo(TAG, "Wrong app name:" + name);
// checkPoint("Wrong app name:" + name, false);
}
}
/*
* 进入某文件夹的某个文件
*/
public void openAppFloder(String floder, String name)
throws UiObjectNotFoundException {
UiDevice.getInstance().pressHome();
UiDevice.getInstance().pressHome();
sleep(1000);
UiObject obj = new UiObject(new UiSelector().text(floder));// 文件夹名
UiObject name1 = new UiObject(new UiSelector().text(name));
for (int i = 0; i < 3; i++) {
if (obj.exists()) {
obj.clickAndWaitForNewWindow();
name1.clickAndWaitForNewWindow();
break;
}
getUiDevice();
UiDevice.getInstance().drag(421, 694, 50, 694, 5);
sleep(1000);
obj = new UiObject(new UiSelector().text(name));
}
}
// 打开文件
public static void openFloder(String name) throws UiObjectNotFoundException {
System.out.println("switch to TF card");
UiObject CheckedTextView = UiUtil
.findByClassName("android.widget.CheckedTextView");
CheckedTextView.clickAndWaitForNewWindow();
UiObject storage = UiUtil
.findByText(readResResource("foldermgr_text_switch_to_tf"));
storage.clickAndWaitForNewWindow();
UiScrollable scrollable = new UiScrollable(new UiSelector().resourceId(
"com.sprd.fileexplorer:id/detailed_file_list").scrollable(true));
scrollable.setAsVerticalList();
UiObject file = UiUtil.findByText(name);
while (!file.exists()) {
boolean fling = scrollable.scrollForward();
if (fling == false) {
break;
}
}
if (file.exists()) {
file.clickAndWaitForNewWindow();
// sleep(2000);
} else {
System.out.println(name + "file not exist");
UiUtil.goHome();
}
}
// 获取命令并执行 ,返回0表示执行成功
public static void exeCommand(String command) throws IOException {
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec(command);
UiUtil.Sleep(3000);
try {
if (proc.waitFor() != 0) {
System.err.println("exit value = " + proc.exitValue());
}
BufferedReader in = new BufferedReader(new InputStreamReader(
proc.getInputStream()));
StringBuffer stringBuffer = new StringBuffer();
String line = null;
while ((line = in.readLine()) != null) {
stringBuffer.append(line + " ");
}
System.out.println(stringBuffer.toString());
} catch (InterruptedException e) {
System.err.println(e);
UiUtil.checkPoint("ping error", false);
} finally {
try {
proc.destroy();
} catch (Exception e2) {
}
}
}
// 长按物理键
public static boolean longPressKeyCode(int keyCode) {
try {
Object deviceObj = UiDevice.getInstance();
Field mUiAutomationBridge = Class.forName(
"com.android.uiautomator.core.UiDevice").getDeclaredField(
"mUiAutomationBridge");
mUiAutomationBridge.setAccessible(true);
Object bridgeObj = mUiAutomationBridge.get(deviceObj);
Method injectInputEvent = Class.forName(
"com.android.uiautomator.core.UiAutomatorBridge")
.getDeclaredMethod(
"injectInputEvent",
new Class[] { android.view.InputEvent.class,
boolean.class });
final long eventTime = SystemClock.uptimeMillis();
KeyEvent downEvent = new KeyEvent(eventTime, eventTime,
KeyEvent.ACTION_DOWN, keyCode, 0, 0,
KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0,
InputDevice.SOURCE_KEYBOARD);
if ((Boolean) injectInputEvent.invoke(bridgeObj, new Object[] {
downEvent, true })) {
SystemClock.sleep(500);
for (int repetition = 0; repetition < 10; repetition++) {
KeyEvent newEvent = KeyEvent.changeTimeRepeat(downEvent,
SystemClock.uptimeMillis(), repetition,
downEvent.getFlags() | KeyEvent.FLAG_LONG_PRESS);
injectInputEvent.invoke(bridgeObj, new Object[] { newEvent,
true });
SystemClock.sleep(5);
}
KeyEvent upEvent = new KeyEvent(eventTime, eventTime,
KeyEvent.ACTION_UP, keyCode, 0, 0,
KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0,
InputDevice.SOURCE_KEYBOARD);
if ((Boolean) injectInputEvent.invoke(bridgeObj, new Object[] {
upEvent, true })) {
return true;
}
}
} catch (NoSuchMethodException e) {
Log.d("TAG", e.getMessage());
} catch (ClassNotFoundException e) {
Log.d("TAG", e.getMessage());
} catch (InvocationTargetException e) {
Log.d("TAG", e.getMessage());
} catch (IllegalAccessException e) {
Log.d("TAG", e.getMessage());
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
return false;
}
/*
* 按power键,灭屏,锁屏
*/
public static void offScreen() throws UiObjectNotFoundException {
try {
if (UiDevice.getInstance().isScreenOn()) {
UiDevice.getInstance().pressKeyCode(26);
UiUtil.Sleep(2000);
}
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 判断一个字符串是否都为数字
public static boolean isDigit(String strNum) {
return strNum.matches("[0-9]{1,}");
}
/*
* 获取XML文件节点 参数:文件名,节点名,属性名 返回:字符串数组
*/
public static String[] getXmlValue(String file, String value, String attr) {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dbf.newDocumentBuilder();
Document doc = builder.parse("file:///data//local//tmp//" + file); // 获取到xml文件
String s;
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr = xpath.compile("//" + value); // 获取节点名称
NodeList nodes = (NodeList) expr.evaluate(doc,
XPathConstants.NODESET);
String sp[] = new String[nodes.getLength()];
for (int i = 0; i < nodes.getLength(); i++) {
Node nd = nodes.item(i);
s = nd.getAttributes().getNamedItem(attr).getTextContent();
sp[i] = s;
}
return sp;
} catch (XPathExpressionException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String readConfig(String tagname) {
return readJson(tagname);
}
// 读取XML文件参数
public static String readXml(String tagname) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
String folder = RES_CONFIG_FOLER_CASE;
if (!new File("/data/local/tmp/" + folder).exists()) {
folder = ".";
}
DocumentBuilder builder = dbf.newDocumentBuilder();
Document doc = builder.parse("file:///data//local//tmp//" + folder
+ "//config.xml");
doc.normalize();
NodeList node = doc.getElementsByTagName(tagname);
String result = node.item(0).getTextContent();
return result;
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
}
// 文件名,TAG名来读取XML文件参数
public static String readXml(String fileName, String tagname) {
loginfo(TAG, "readXml fileName=" + fileName + ",tagname=" + tagname);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
String folder = RES_CONFIG_FOLER_CASE;
if (!new File("/data/local/tmp/" + folder).exists()) {
folder = ".";
}
DocumentBuilder builder = dbf.newDocumentBuilder();
Document doc = builder.parse("file:///data//local//tmp//" + folder
+ "//" + fileName + ".xml");
doc.normalize();
NodeList node = doc.getElementsByTagName(tagname);
String result = node.item(0).getTextContent();
return result;
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
}
private static final int s_config_total_size = 5 * 1024 * 1024;
private static JSONObject s_json_config = null;
private static final String s_config_main_tag = "config";
private static final String s_config_value_tag = "value";
private static final String s_config_id_tag = "id";
private static String readJson(String tagname) {
if (s_json_config == null) {
try {
FileInputStream fis = new FileInputStream(new File(
RES_CONFIG_PATH + "config.json"));
int iLen = fis.available();
loginfo(TAG, "iLen = " + iLen);
if (iLen <= 0 || iLen >= s_config_total_size) {
fis.close();
loginfo(TAG, "read json fail: iLen = " + iLen);
return readXml(tagname);
}
int num = 0;
char[] cbuf = new char[1024];
StringBuilder sb = new StringBuilder(iLen + 1);
InputStreamReader isReader = new InputStreamReader(fis);
while ((num = isReader.read(cbuf)) > 0) {
sb.append(cbuf);
}
loginfo(TAG, "buff: " + sb.toString());
s_json_config = new JSONObject(sb.toString());
isReader.close();
} catch (Exception e) {
loginfo(TAG, "read json fail: " + e.getMessage());
return readXml(tagname);
}
}
try {
String content = s_json_config.getString(s_config_main_tag);
JSONArray jsonArray = new JSONArray(content);
for (int i = 0; i < jsonArray.length(); i++) {
String param = jsonArray.getString(i);
JSONObject obj = new JSONObject(param);
if (obj.getString(s_config_id_tag).equals(tagname)) {
String value = obj.getString(s_config_value_tag);
loginfo(TAG, "tagname = " + tagname + ", value = " + value);
return value;
}
}
} catch (Exception e) {
}
loginfo(TAG, "read json fail: can't find " + tagname
+ " in config.json");
return readXml(tagname);
}
// 读取XML文件参数
public static String readRes(int res, String tagname) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
String filename = null;
if (res == RES_CONFIG) {
filename = RES_CONFIG_FILE;
} else if (res == RES_RESOURCE) {
filename = RES_RESOURCE_FILE;
} else {
return null;
}
try {
String folder = RES_CONFIG_FOLER_CASE;
if (!new File("/data/local/tmp/" + folder).exists()) {
folder = ".";
}
DocumentBuilder builder = dbf.newDocumentBuilder();
Document doc = builder.parse("file:///data//local//tmp//" + folder
+ "//" + filename);
doc.normalize();
NodeList node = doc.getElementsByTagName(tagname);
String result = node.item(0).getTextContent();
return result;
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
}
// 删除文件
/**
* @Title: deleteFloder
* @Description: 通过文件管理器删除文件/文件夹
* @param String
* name
* @param
* @param
* @return
* @throws UiObjectNotFoundException
*/
public static void deleteFloder(String name)
throws UiObjectNotFoundException {
UiObject fileexplorer = UiUtil.findByPackage("com.sprd.fileexplorer");
if (!fileexplorer.exists()) {
openApp(readResResource("ui_text_foldermanager"));
}
System.out.println("switch to tf card");
UiObject CheckedTextView = UiUtil
.findByClassName("android.widget.CheckedTextView");
CheckedTextView.clickAndWaitForNewWindow();
UiObject storage = UiUtil
.findByText(readResResource("foldermgr_text_switch_to_tf"));
storage.clickAndWaitForNewWindow();
UiScrollable scrollable = new UiScrollable(new UiSelector().resourceId(
"com.sprd.fileexplorer:id/detailed_file_list").scrollable(true));
scrollable.setAsVerticalList();
UiObject file = UiUtil.findByText(name);
try {
scrollable.flingBackward();
scrollable.flingBackward();
} catch (Exception e) {
// TODO: handle exception
}
int i = 0;
while (!file.exists()) {
UiDevice.getInstance().pressDPadDown();
i++;
if (i == 50) {
break;
}
}
file = UiUtil.findByText(name);
if (file.exists()) {
UiDevice.getInstance().pressDPadDown();
UiUtil.Sleep(1000);
UiObject floder = UiUtil.findByText(name);
longclick(floder);
UiUtil.Sleep(2000);
UiObject delete = UiUtil
.findByText(readResResource("button_text_delete"));
delete.clickAndWaitForNewWindow();
UiObject confirm = UiUtil
.findByText(readResResource("button_text_ok"));
confirm.clickAndWaitForNewWindow();
UiUtil.Sleep(3000);
} else {
System.out.println(name + "file not exist");
}
}
// ningbiao
/**
* @Title: setPreferredNetworkType
* @Description: 设置首选网络
* @param CALL_SIM_TYPE
* sim_TYPE
* @param PREFERRED_NETWORK_TYPE
* network_TYPE
* @param
* @return
* @throws UiObjectNotFoundException
*/
public void setPreferredNetworkType(CALL_SIM_TYPE sim_TYPE,
PREFERRED_NETWORK_TYPE network_TYPE)
throws UiObjectNotFoundException {
openApp(UiUtil.readResResource("ui_text_setting"));
sleep(1000);
UiObject more = new UiObject(new UiSelector().className(
"android.widget.TextView").textContains(
UiUtil.readResResource("settings_text_more")));
if (more.exists()) {
more.clickAndWaitForNewWindow();
UiObject mobile_network = new UiObject(new UiSelector().className(
"android.widget.TextView").text(
UiUtil.readResResource("settings_text_mobile_networks")));
mobile_network.clickAndWaitForNewWindow();
if (sim_TYPE == CALL_SIM_TYPE.SIM1) {
UiObject setting_sim1 = new UiObject(
new UiSelector()
.className("android.widget.TextView")
.text(UiUtil
.readResResource("settings_text_mobile_networks_sim1")));
if (setting_sim1.exists()) {
setting_sim1.clickAndWaitForNewWindow();
} else {
System.out
.print("SIM1 Mobile Network settings did't exists!");
}
} else if (sim_TYPE == CALL_SIM_TYPE.SIM2) {
UiObject setting_sim2 = new UiObject(
new UiSelector()
.className("android.widget.TextView")
.text(UiUtil
.readResResource("settings_text_mobile_networks_sim2")));
if (setting_sim2.exists()) {
setting_sim2.clickAndWaitForNewWindow();
} else {
System.out
.print("SIM2 Mobile Network settings did't exists!");
}
} else {
System.out.print("SIM type error!");
}
UiObject preferred_network = new UiObject(
new UiSelector()
.className("android.widget.TextView")
.text(UiUtil
.readResResource("settings_text_preferred_network_type")));
if (preferred_network.exists()) {
preferred_network.clickAndWaitForNewWindow();
}
String typeText = "Auto";
switch (network_TYPE) {
case AUTO:
typeText = UiUtil
.readResResource("settings_preferred_text_auto");
break;
case GSM_ONLY:
typeText = UiUtil
.readResResource("settings_preferred_text_gsm_only");
break;
case LTE_ONLY:
typeText = UiUtil
.readResResource("settings_preferred_text_lte_only");
break;
case TD_ONLY:
typeText = UiUtil
.readResResource("settings_preferred_text_td_only");
break;
case WCDMA_ONLY:
typeText = UiUtil
.readResResource("settings_preferred_text_wcdma_only");
break;
default:
break;
}
UiObject checked_option = new UiObject(new UiSelector().className(
"android.widget.CheckedTextView").text(typeText));
if (checked_option.exists()) {
checked_option.clickAndWaitForNewWindow();
sleep(3000);
} else {
System.out.print("Has't Preferred network type options!");
}
} else {
System.out.print("Has't more button!");
}
}
// ningbiao
/**
* @Title: openMoreOptionsMenu
* @Description: 打开menu菜单
* @param
* @param
* @param
* @return
* @throws UiObjectNotFoundException
*/
public static void openMoreOptionsMenu() throws UiObjectNotFoundException {
UiObject moreOptionsButton = new UiObject(new UiSelector()
.className("android.widget.ImageButton")
.description(UiUtil.readResResource("menu_text_more_option"))
.instance(0));
if (moreOptionsButton.exists()) {
moreOptionsButton.clickAndWaitForNewWindow();
} else {
UiDevice.getInstance().pressMenu();
}
}
// ningbiao
/**
* @Title: updateLanguage
* @Description: 切换系统语言
* @param Locale
* locale
* @param
* @param
* @return
* @throws
*/
public static void updateLanguage(Locale locale) {
Log.d("ANDROID_LAB", locale.toString());
try {
Object objIActMag, objActMagNative;
Class clzIActMag = Class.forName("android.app.IActivityManager");
Class clzActMagNative = Class
.forName("android.app.ActivityManagerNative");
Method mtdActMagNative$getDefault = clzActMagNative
.getDeclaredMethod("getDefault");
// IActivityManager iActMag = ActivityManagerNative.getDefault();
objIActMag = mtdActMagNative$getDefault.invoke(clzActMagNative);
// Configuration config = iActMag.getConfiguration();
Method mtdIActMag$getConfiguration = clzIActMag
.getDeclaredMethod("getConfiguration");
Configuration config = (Configuration) mtdIActMag$getConfiguration
.invoke(objIActMag);
config.locale = locale;
// iActMag.updateConfiguration(config);
// 此处�?��声明权限:android.permission.CHANGE_CONFIGURATION
// 会重新调�?onCreate();
Class[] clzParams = { Configuration.class };
Method mtdIActMag$updateConfiguration = clzIActMag
.getDeclaredMethod("updateConfiguration", clzParams);
mtdIActMag$updateConfiguration.invoke(objIActMag, config);
} catch (Exception e) {
e.printStackTrace();
}
}
// ningbiao
/**
* @Title: openFloderEn
* @Description: 从文件管理器中打开某一个文件夹
* @param String
* name
* @param
* @param
* @return
* @throws UiObjectNotFoundException
*/
public void openFloderEn(String name) throws UiObjectNotFoundException {
UiObject CheckedTextView = findByClassName("android.widget.CheckedTextView");
CheckedTextView.clickAndWaitForNewWindow();
UiObject storage = findByText(UiUtil
.readResResource("fileexplorer_text_external_storage"));
if (!storage.exists()) {
storage = findByText(UiUtil
.readResResource("fileexplorer_text_internal_storage"));
}
storage.clickAndWaitForNewWindow();
UiScrollable scrollable = new UiScrollable(new UiSelector().resourceId(
"com.sprd.fileexplorer:id/detailed_file_list").scrollable(true));
scrollable.setAsVerticalList();
UiObject file = findByText(name);
while (!file.exists()) {
boolean fling = scrollable.scrollForward();
if (fling == false) {
break;
}
}
if (file.exists()) {
file.clickAndWaitForNewWindow();
// sleep(2000);
} else {
System.out.println(name + "File is not exists!");
}
}
// ningbiao
/**
* @Title: findByPackageName
* @Description: 通过包名获取对象
* @param String
* packageName
* @param
* @param
* @return UiObject
* @throws
*/
public static UiObject findByPackageName(String packageName) {
return new UiObject(new UiSelector().packageName(packageName));
}
/**
* @Title: deleteFloderCamera
* @Description: 删除DCIM中的Camera文件夹
* @param String
* floderName
* @param String
* storageName
* @param
* @return
* @throws UiObjectNotFoundException
*/
public static void deleteFloderCamera(String floderName, String storageName)
throws UiObjectNotFoundException {
UiObject fileexplorer = findByPackageName("com.sprd.fileexplorer");
if (!fileexplorer.exists()) {
openApp(UiUtil.readResResource("fileexplorer_text_app_name"));
}
UiObject CheckedTextView = findByClassName("android.widget.CheckedTextView");
CheckedTextView.clickAndWaitForNewWindow();
UiObject storage = findByText(storageName);
if (!storage.exists()) {
storage = findByText(UiUtil
.readResResource("fileexplorer_text_external_storage"));
if (!storage.exists()) {
storage = findByText(UiUtil
.readResResource("fileexplorer_text_internal_storage"));
}
}
storage.clickAndWaitForNewWindow();
UiScrollable scrollable = new UiScrollable(new UiSelector().resourceId(
"com.sprd.fileexplorer:id/detailed_file_list").scrollable(true));
scrollable.setAsVerticalList();
UiObject file = findByText(floderName);
try {
scrollable.flingBackward();
scrollable.flingBackward();
} catch (Exception e) {
// TODO: handle exception
}
int i = 0;
while (!file.exists()) {
UiDevice.getInstance().pressDPadDown();
i++;
if (i == 50) {
break;
}
}
file = findByText(floderName);
if (file.exists()) {
UiDevice.getInstance().pressDPadDown();
UiUtil.Sleep(1000);
UiObject floder = findByText(floderName);
// longclick(floder);
floder.clickAndWaitForNewWindow();
UiUtil.Sleep(1000);
// delete Camera floder
scrollable = new UiScrollable(new UiSelector().resourceId(
"com.sprd.fileexplorer:id/detailed_file_list").scrollable(
true));
scrollable.setAsVerticalList();
file = findByText("Camera");
try {
scrollable.flingBackward();
scrollable.flingBackward();
} catch (Exception e) {
// TODO: handle exception
}
i = 0;
while (!file.exists()) {
UiDevice.getInstance().pressDPadDown();
i++;
if (i == 50) {
break;
}
}
if (file.exists()) {
UiDevice.getInstance().pressDPadDown();
UiUtil.Sleep(1000);
longclick(file);
UiUtil.Sleep(1000);
UiObject delete = findByText(UiUtil
.readResResource("button_text_delete"));
delete.clickAndWaitForNewWindow();
UiObject confirm = findByText(UiUtil
.readResResource("button_text_ok"));
confirm.clickAndWaitForNewWindow();
UiUtil.Sleep(2000);
} else {
System.out.println(floderName + "Camera floder is not exists!");
}
} else {
System.out.println(floderName + "File is not exists!");
}
}
// ningbiao
/**
* @Title: destotyAll
* @Description: 清除所有后台程序
* @param
* @param
* @param
* @return
* @throws UiObjectNotFoundException
*/
public void destotyAll() throws UiObjectNotFoundException {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
clearBackgroundApps();
} else {
try {
UiDevice.getInstance().pressRecentApps();
UiObject recent_sprdramopt_view = new UiObject(
new UiSelector()
.resourceId("com.android.systemui:id/recent_sprdramopt_view"));
if (recent_sprdramopt_view.exists()) {
recent_sprdramopt_view.clickAndWaitForNewWindow();
}
goHome();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// ningbiao
/**
* @Title: execCommand
* @Description: 执行命令
* @param String
* command
* @param
* @param
* @return
* @throws IOException
*/
public static void execCommand(String command) throws IOException {
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec(command);
try {
if (proc.waitFor() != 0) {
System.err.println("exit value = " + proc.exitValue());
}
BufferedReader in = new BufferedReader(new InputStreamReader(
proc.getInputStream()));
StringBuffer stringBuffer = new StringBuffer();
String line = null;
while ((line = in.readLine()) != null) {
stringBuffer.append(line + " ");
}
System.out.println(stringBuffer.toString());
} catch (InterruptedException e) {
System.err.println(e);
} finally {
try {
proc.destroy();
} catch (Exception e2) {
}
}
}
// ningbiao
public static String readResResource(String tagname) {
return readResWithLocale(RES_RESOURCE, tagname);
}
/**
* @Title: readResWithLocale
* @Description: 通过tag,获取资源文件中(xml)的内容
* @param int res
* @param String
* tagname
* @param
* @return String
* @throws
*/
public static String readResWithLocale(int res, String tagname) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
Locale locale = getCurretnLocale();
String filename = null;
if (res == RES_CONFIG) {
filename = RES_CONFIG_FILE;
} else if (res == RES_RESOURCE) {
if (locale.equals(Locale.ENGLISH) || locale.equals(Locale.UK)
|| locale.equals(Locale.US)) {
filename = RES_RESOURCE_FILE_EN;
} else if (locale.equals(Locale.CHINA)
|| locale.equals(Locale.CHINESE)) {
filename = RES_RESOURCE_FILE;
} else {
filename = RES_RESOURCE_FILE_EN;
}
} else {
return null;
}
try {
String folder = RES_CONFIG_FOLER_CASE;
if (!new File("/data/local/tmp/" + folder).exists()) {
folder = ".";
}
DocumentBuilder builder = dbf.newDocumentBuilder();
Document doc = builder.parse("file:///data//local//tmp//" + folder
+ "//" + filename);
doc.normalize();
NodeList node = doc.getElementsByTagName(tagname);
String result = node.item(0).getTextContent();
return result;
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
}
// ningbiao
/**
* @Title: getCurretnLocale
* @Description: 切换手机默认语言
* @param
* @param
* @param
* @return
* @throws
*/
public static Locale getCurretnLocale() {
try {
Object objIActMag, objActMagNative;
Class clzIActMag = Class.forName("android.app.IActivityManager");
Class clzActMagNative = Class
.forName("android.app.ActivityManagerNative");
Method mtdActMagNative$getDefault = clzActMagNative
.getDeclaredMethod("getDefault");
// IActivityManager iActMag = ActivityManagerNative.getDefault();
objIActMag = mtdActMagNative$getDefault.invoke(clzActMagNative);
// Configuration config = iActMag.getConfiguration();
Method mtdIActMag$getConfiguration = clzIActMag
.getDeclaredMethod("getConfiguration");
Configuration config = (Configuration) mtdIActMag$getConfiguration
.invoke(objIActMag);
return config.locale;
} catch (Exception e) {
e.printStackTrace();
}
return Locale.ENGLISH;
}
// ningbiao
/**
* @Title: setDefaultSimCard
* @Description: 设置默认卡(短信/通话/数据链接/视频通话)
* @param SIM_SELECT_TYPE
* selectType
* @param CALL_SIM_TYPE
* simType
* @param boolean alwaysPrompt
* @return
* @throws UiObjectNotFoundException
*/
public static void setDefaultSimCard(SIM_SELECT_TYPE selectType,
CALL_SIM_TYPE simType, boolean alwaysPrompt)
throws UiObjectNotFoundException {
goHome();
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
try {
openApp(UiUtil.readResResource("ui_text_setting"));
enterSetChild(UiUtil.readResResource("settings_text_sim_cards"));
String resStr = null;
if (selectType == SIM_SELECT_TYPE.CALL) {
resStr = "settings_text_calls_setting";
} else if (selectType == SIM_SELECT_TYPE.MMS) {
resStr = "settings_text_message_setting";
} else {
return;
}
System.out.print("resStr=" + resStr);
UiObject mDialog = UiUtil.findByText(UiUtil
.readResResource(resStr));
if (mDialog.exists()) {
mDialog.clickAndWaitForNewWindow();
}
UiUtil.Sleep(1000);
if (alwaysPrompt) {
resStr = UiUtil
.readResResource("settings_text_ask_every_time");
UiObject obj = UiUtil.findByText(resStr);
obj.clickAndWaitForNewWindow();
} else {
UiCollection collextion = new UiCollection(
new UiSelector()
.resourceId("android:id/select_dialog_listview"));
int instance = 1;
if (simType == CALL_SIM_TYPE.SIM1) {
instance = 1;
} else if (simType == CALL_SIM_TYPE.SIM2) {
instance = 2;
}
System.out.print("instance:" + instance + "\n");
UiObject obj = collextion
.getChild(new UiSelector()
.resourceId(
"com.android.settings:id/default_subscription_off")
.instance(instance));
System.out.print("obj:" + obj.exists() + "\n");
if (obj.exists()) {
obj.clickAndWaitForNewWindow();
}
}
goHome();
} catch (Exception e) {
e.printStackTrace();
}
} else {
try {
openApp(UiUtil.readResResource("ui_text_setting"));
enterSetChild(UiUtil.readResResource("settings_text_mulitsim"));
String resStr = null;
if (selectType == SIM_SELECT_TYPE.CALL) {
resStr = "settings_text_mulitsim_voice";
} else if (selectType == SIM_SELECT_TYPE.DATACONNECT) {
resStr = "settings_text_mulitsim_dataconnect";
} else if (selectType == SIM_SELECT_TYPE.VIDEOCALL) {
resStr = "settings_text_mulitsim_video";
} else if (selectType == SIM_SELECT_TYPE.MMS) {
resStr = "settings_text_mulitsim_mms";
} else {
return;
}
System.out.print("resStr=" + resStr);
UiObject dialBtn = UiUtil.findByText(UiUtil
.readResResource(resStr));
// Fix for JRX test case.
if (!dialBtn.exists()) {
if (selectType == SIM_SELECT_TYPE.CALL) {
resStr = "settings_text_mulitsim_voice_call";
} else if (selectType == SIM_SELECT_TYPE.DATACONNECT) {
resStr = "settings_text_mulitsim_dataconnect";
} else if (selectType == SIM_SELECT_TYPE.VIDEOCALL) {
resStr = "settings_text_mulitsim_video_call";
} else if (selectType == SIM_SELECT_TYPE.MMS) {
resStr = "settings_text_mulitsim_mms_call";
} else {
return;
}
dialBtn = UiUtil.findByText(UiUtil.readResResource(resStr));
}
dialBtn.clickAndWaitForNewWindow();
UiUtil.Sleep(1000);
if (alwaysPrompt) {
resStr = UiUtil
.readResResource("settings_text_mulitsim_always_prompt");
} else {
resStr = UiUtil.readResResource("settings_text_sim")
+ ((simType == CALL_SIM_TYPE.SIM1) ? "1" : "2");
}
UiObject obj = UiUtil.findByText(resStr);
if (!obj.exists()) {
UiObject select_dialog_listview = findByResourceId("android:id/select_dialog_listview");
if (select_dialog_listview.exists()) {
// sim1 is index 0,sim2 is index 1;
int instance = alwaysPrompt ? 2
: (simType == CALL_SIM_TYPE.SIM1 ? 0 : 1);
UiCollection collextion = new UiCollection(
new UiSelector()
.packageName("com.android.settings")
.className(
"android.widget.RelativeLayout")
.index(instance));
UiObject mRadioButton = collextion
.getChild(new UiSelector()
.className("android.widget.RadioButton"));
if (!mRadioButton.isChecked()) {
mRadioButton.clickAndWaitForNewWindow();
}
}
} else {
obj.clickAndWaitForNewWindow();
}
goHome();
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
}
}
// ningbiao
/**
* @Title: enterSetChild
* @Description: 通过名字,进入列表中某一项
* @param String
* setName
* @param
* @param
* @return
* @throws UiObjectNotFoundException
*/
public static void enterSetChild(String setName)
throws UiObjectNotFoundException {
UiScrollable setList = UiUtil
.findScrollableByResource("android:id/list");
System.out.print("enterSetChild setList.exists" + setList.exists()
+ "\n");
if (!setList.exists()) {
setList = UiUtil.findScrollableByClass("android.widget.ScrollView");
}
setList.setAsVerticalList();
UiObject searchItem = new UiObject(new UiSelector().text(setName));
while (!searchItem.exists()) {
boolean scroll = setList.scrollForward();
UiUtil.checkPoint("no found the searchItem", (scroll == true));
}
searchItem.clickAndWaitForNewWindow();
}
// ningbiao
/**
* @Title: getRandomString
* @Description: 产生一个随机的字符串
* @param int length
* @param
* @param
* @return String
* @throws
*/
public static String getRandomString(int length) {
String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Random random = new Random();
StringBuffer buf = new StringBuffer();
for (int i = 0; i < length; i++) {
int num = random.nextInt(62);
buf.append(str.charAt(num));
}
return buf.toString();
}
/**
* @Title: loginfo
* @Description: 输出LOG
* @param String
* tag
* @param String
* info
* @param
* @return
* @throws UiObjectNotFoundException
*/
public static void loginfo(String tag, String info) {
System.out.println(TAG + ":" + info + "\n");
Log.d(TAG + tag, info);
}
/**
* @Title: loginfo
* @Description: 输出LOG
* @param String
* tag
* @param String
* info
* @param UiObjectNotFoundException
* e
* @return
* @throws UiObjectNotFoundException
*/
public static void loginfo(String tag, String info,
UiObjectNotFoundException e) {
int num = e.getStackTrace().length;
for (int i = 0; i < num; i++) {
loginfo(tag,
e.getStackTrace()[i].getClassName() + "."
+ e.getStackTrace()[i].getMethodName() + "("
+ e.getStackTrace()[i].getFileName() + ":"
+ e.getStackTrace()[i].getLineNumber() + ")");
}
}
// ningbiao
/**
* @Title: clickObjectByText
* @Description: 通过Text查找并点击对象
* @param
* @param
* @param
* @return
* @throws UiObjectNotFoundException
*/
public void clickObjectByText(String text) throws UiObjectNotFoundException {
UiObject object = findByText(text);
checkPoint("clickObjectByText fail", object.exists());
object.clickAndWaitForNewWindow();
}
public void clickObjectByDes(String text) throws UiObjectNotFoundException {
UiObject object = findByDesc(text);
checkPoint("clickObjectByDes fail", object.exists());
object.clickAndWaitForNewWindow();
}
/**
* @Title: clickObjectByID
* @Description: 通过ID查找并点击对象
* @param
* @param
* @param
* @return
* @throws UiObjectNotFoundException
*/
public void clickObjectByID(String resourceID)
throws UiObjectNotFoundException {
UiObject object = findById(resourceID);
checkPoint("clickObjectByID fail", object.exists());
object.clickAndWaitForNewWindow();
}
/**
* @Title: clickObjectByClassName
* @Description: 通过Text查找并点击对象
* @param
* @param
* @param
* @return
* @throws UiObjectNotFoundException
*/
public void clickObjectByClassName(String className)
throws UiObjectNotFoundException {
UiObject object = findByClassName(className);
checkPoint("text object is not exists", object.exists());
object.clickAndWaitForNewWindow();
}
// click if object exists
/**
* @Title: clickObjectByTextIfExists
* @Description: 通过Text查找并点击对象(对象存在)
* @param
* @param
* @param
* @return
* @throws UiObjectNotFoundException
*/
public void clickObjectByTextIfExists(String text)
throws UiObjectNotFoundException {
UiObject object = findByText(text);
if (object.exists()) {
object.clickAndWaitForNewWindow();
}
}
/**
* @Title: clickObjectByIDIfExists
* @Description: 通过ID查找并点击对象(对象存在)
* @param
* @param
* @param
* @return
* @throws UiObjectNotFoundException
*/
public void clickObjectByIDIfExists(String resourceID)
throws UiObjectNotFoundException {
UiObject object = findById(resourceID);
if (object.exists()) {
object.clickAndWaitForNewWindow();
}
}
/**
* @Title: clickObjectByClassNameIfExists
* @Description: 通过类名查找并点击对象(对象存在)
* @param
* @param
* @param
* @return
* @throws UiObjectNotFoundException
*/
public void clickObjectByClassNameIfExists(String className)
throws UiObjectNotFoundException {
UiObject object = findByClassName(className);
if (object.exists()) {
object.clickAndWaitForNewWindow();
}
}
// click if object exists end.
/**
* @Title: clickJustOnceButton
* @Description: 点击Just once按钮
* @param
* @param
* @param
* @return
* @throws UiObjectNotFoundException
*/
public void clickJustOnceButton() throws UiObjectNotFoundException {
if (checkObjectExistsByText(readResResource("ui_text_just_once"))) {
loginfo(TAG, "Has just once button,click!");
clickObjectByText(readResResource("ui_text_just_once"));
}
}
/**
* @Title: clickAlwaysButton
* @Description: 点击always按钮
* @param
* @param
* @param
* @return
* @throws UiObjectNotFoundException
*/
public void clickAlwaysButton() throws UiObjectNotFoundException {
clickObjectByText(readResResource("ui_text_always"));
}
/**
* @Title: checkObjectExistsByID
* @Description: 通过对象的资源Id,判断对象是否存在
* @param resourceId
* @param
* @param
* @return
* @throws UiObjectNotFoundException
*/
public static boolean checkObjectExistsByID(String resourceId)
throws UiObjectNotFoundException {
UiObject object = findById(resourceId);
return object.exists();
}
public static boolean checkObjectExistsByIDAndText(String resourceId,
String text) throws UiObjectNotFoundException {
UiObject object = findByResourceIdAndText(resourceId, text);
return object.exists();
}
/**
* @Title: checkObjectExistsByText
* @Description: 通过Text中的字符,判断对象是否存在
* @param text
* @param
* @param
* @return
* @throws UiObjectNotFoundException
*/
public static boolean checkObjectExistsByText(String text)
throws UiObjectNotFoundException {
UiObject object = findByText(text);
return object.exists();
}
/**
* @Title: checkObjectExistsByTextContains
* @Description: 通过Text中包含的字符,判断对象是否存在
* @param text
* @param
* @param
* @return
* @throws UiObjectNotFoundException
*/
public static boolean checkObjectExistsByTextContains(String text)
throws UiObjectNotFoundException {
UiObject object = findByTextContains(text);
return object.exists();
}
/**
* @Title: checkObjectExistsByTextDesc
* @Description: 通过Desc中包含的字符,判断对象是否存在
* @param text
* @param
* @param
* @return
* @throws UiObjectNotFoundException
*/
public static boolean checkObjectExistsByTextDesc(String text)
throws UiObjectNotFoundException {
UiObject object = findByDesc(text);
return object.exists();
}
/**
* @Title: checkObjectExistsByPackage
* @Description: 通过包名,判断对象是否存在
* @param text
* @param
* @param
* @return
* @throws UiObjectNotFoundException
*/
public static boolean checkObjectExistsByPackage(String packageName)
throws UiObjectNotFoundException {
UiObject object = findByPackageName(packageName);
return object.exists();
}
/**
* @Title: connectMobileData
* @Description: 进入设置打开数据链接
* @param
* @param
* @param
* @return
* @throws UiObjectNotFoundException
*/
public void connectMobileData() throws UiObjectNotFoundException {
goHome();
openApp(UiUtil.readResResource("ui_text_setting"));
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
enterSetChild(UiUtil.readResResource("settings_text_sim_cards"));
} else {
enterSetChild(UiUtil.readResResource("settings_text_mulitsim"));
}
UiObject universal_switch = findByIdIndex(
"com.android.settings:id/universal_switch", 1);
boolean checked = universal_switch.isChecked();
loginfo(TAG, "connectMobileData checked=" + checked);
if (!checked) {
universal_switch.clickAndWaitForNewWindow();
}
}
/**
* @Title: UiUtil
* @Description: 从垂直滚动listview中按名称查找控件
* @param scrollId
* @param name
* @return
* @throws UiObjectNotFoundException
* @throws
*/
public UiObject findByTextAsVerticalScroll(String scrollId, String name)
throws UiObjectNotFoundException {
// UiScrollable scrollView = new UiScrollable(new UiSelector().resourceId(scrollId).scrollable(true));
UiScrollable scrollView = new UiScrollable(new UiSelector().resourceId(scrollId));
scrollView.setAsVerticalList();
UiObject object = findByText(name);
int i = 0;
while (!object.exists()) {
scrollView.scrollForward();
i++;
if (i == 50) {
break;
}
}
return object;
}
// ningbiao
/**
* @Title: addWatcher
* @Description: 添加监听器
* @param watcherName
* @param watcherObject
* @param conditionObject
* @return
* @throws
*/
public void addWatcher(final String watcherName,
final UiObject watcherObject, final UiObject conditionObject) {
try {
UiDevice.getInstance().registerWatcher(watcherName,
new UiWatcher() {
public boolean checkForCondition() {
// TODO Auto-generated method stub
if (watcherObject.exists()) {
try {
loginfo(TAG, "watcherName:" + watcherName);
if (conditionObject.exists()
&& conditionObject.isEnabled()) {
conditionObject
.clickAndWaitForNewWindow();
}
} catch (UiObjectNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
loginfo(TAG, "addWatcher!", e);
return false;
}
sleep(2000);
return true;
} else {
return false;
}
}
});
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
loginfo(TAG, "addWatcher!");
}
}
/**
* @Title: addWatcherCheckable
* @Description: 添加勾选框监听器
* @param watcherName
* @param watcherObject
* @param conditionObject
* @return
* @throws
*/
public void addWatcherCheckable(String watcherName,
final UiObject watcherObject, final UiObject conditionObject) {
try {
UiDevice.getInstance().registerWatcher(watcherName,
new UiWatcher() {
public boolean checkForCondition() {
// TODO Auto-generated method stub
if (watcherObject.exists()) {
try {
if (conditionObject.isCheckable()
&& !conditionObject.isChecked()) {
conditionObject
.clickAndWaitForNewWindow();
}
} catch (UiObjectNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
loginfo(TAG, "addWatcher!", e);
return false;
}
return true;
} else {
return false;
}
}
});
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
loginfo(TAG, "addWatcher!");
}
}
/**
* @Title: realeseWatcher
* @Description: 取消监听器
* @param watcherName
* @return
* @throws
*/
public void realeseWatcher(String watcherName) {
UiDevice.getInstance().removeWatcher(watcherName);
}
public static String getSDPath(){
File sdDir = null;
boolean sdCardExist = Environment.getExternalStorageState()
.equals(android.os.Environment.MEDIA_MOUNTED); //判断sd卡是否存在
if (sdCardExist)
{
sdDir = Environment.getExternalStorageDirectory();//获取根目录
}
loginfo(TAG, "sd card dir = "+sdDir.toString());
return sdDir.toString();
}
public void swipe(SWIPEDIRECTION direction) {
int xLocation;
int yLocation;
xLocation = UiDevice.getInstance().getDisplayWidth();
yLocation = UiDevice.getInstance().getDisplayHeight() / 2;
switch (direction) {
case LEFT:
UiDevice.getInstance().swipe(xLocation - 10, yLocation, 10,
yLocation, 10);
sleep(2000);
break;
case RIGHT:
UiDevice.getInstance().swipe(10, yLocation, xLocation - 10,
yLocation, 10);
sleep(2000);
break;
default:
break;
}
}
}
0 0
- uiautomator中一些常用的方法
- UiAutoMator一些常用的方法
- osworkflow中 常用的一些方法
- java中常用的一些方法
- java中常用的一些方法
- js中一些常用的基本方法
- java中常用的一些方法
- js中常用的一些方法收集
- JAVA中一些常用的方法
- c++中一些常用的方法
- 。net中一些常用的类方法
- java中常用的一些方法
- Java中常用的一些方法
- Java 中常用的一些小方法
- js中常用的一些方法
- js、jQuery中常用的一些方法
- jquery中常用的一些方法
- 线程中一些常用方法的分析
- shell之磁盘容量检查
- android布局实践(一)home界面
- github---watch、fork、star
- IOS开发-使用Storyboard进行界面跳转及传值
- 深入浅出Cocoa之Bonjour网络编程
- uiautomator中一些常用的方法
- 深入理解Hadoop集群和网络
- 欢迎使用CSDN-markdown编辑器
- Apache Rewrite配置
- 权限冲突无法安装
- centos min wget的使用
- 性能测试基本指标浅谈
- std::min and std::max
- yarn 日志聚集配置