本人在使用monkey进行测试的时候,发现monkey参数里面--pct-appswitch参数并不好用,随机性比较大,所以想自己来控制启动APP的次数和间隔。之前通过批处理命令bat和shell脚本都实现过,但是现在要做成一个jar的工具包,只能写在一个多线程类里,随便把校验WiFi开关状态的方法也写在了一起。分享代码,供大家参考。
代码语言:javascript复制package monkeytest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import source.Common;
public class StartApp extends Thread {
public boolean MKEY = true;//线程开关
public static boolean WIFISTATUS = true;// WiFi状态开关,默认开
@Override
public void run() {
while (MKEY) {
Common.getInstance().sleep(60 * 1000);
keepWifiONorOFF(WIFISTATUS);
startJuziApp();
}
}
/**
* 启动橘子APP
*/
public void startJuziApp() {
if (Monkey.package_name.contains("happyjuzi")) {
execCmdAdb("adb shell am start -n com.happyjuzi.apps.juzi/.SplashActivity");
} else if (Monkey.package_name.contains("article.news")) {
execCmdAdb("adb shell am start -n com.ss.android.article.news/.activity.SplashBadgeActivity");// 今日头条
}
}
/**
* 保持WiFi状态的方法
*
* @param status
* 当前WiFi的期望状态
*/
public void keepWifiONorOFF(boolean status) {
if (status & wifiIsOn()) {// 判断WiFi状态是否跟预期状态一致
closeOrOpenWifi();
}
}
/**
* wifi是否打开
*
* @return 开打true,没打开false
*/
private boolean wifiIsOn() {
String cmd = "adb shell ifconfig wlan0";
System.out.println("执行:" cmd);
String OSname = System.getProperty("os.name");
try {
Process p = null;
if (OSname.contains("Mac")) {
p = Runtime.getRuntime().exec(Common.ADB_PATH cmd);
} else {
p = Runtime.getRuntime().exec("cmd /c " cmd);
}
// 正确输出流
InputStream input = p.getInputStream();// 创建并实例化输入字节流
BufferedReader reader = new BufferedReader(new InputStreamReader(input));// 先通过inputstreamreader进行流转化,在实例化bufferedreader,接收内容
String line = "";
while ((line = reader.readLine()) != null) {// 循环读取
if (line.contains("RUNNING")) {
return true;
}
}
reader.close();// 此处reader依赖于input,应先关闭
input.close();
} catch (IOException e) {
Common.getInstance().output("执行" cmd "失败!");
e.printStackTrace();
}
return false;
}
/**
* 开关WiFi
*/
public void closeOrOpenWifi() {
try {
Runtime.getRuntime().exec(Common.ADB_PATH "adb shell am start -n run.wifibutton/.WifiButtonActivity")
.waitFor();
} catch (InterruptedException | IOException e) {
Common.getInstance().output("WIFI开关异常!", e);
}
}
/**
* 结束线程方法
*/
public void stopThread() {
this.MKEY = false;
}
/**
* 执行cmd命令
*
* @param cmd
* 命令
*/
public static void execCmdAdb(String cmd) {
System.out.println("正在执行:" cmd);
String OSname = System.getProperty("os.name");
try {
if (OSname.contains("Mac")) {
Runtime.getRuntime().exec(Common.ADB_PATH cmd);
} else {
Runtime.getRuntime().exec("cmd /c " cmd);
}
} catch (IOException e) {
System.out.println("执行" cmd "失败!");
e.printStackTrace();
}
}
}回台回复“WiFi”获取控制WiFi的APP