我们查看Activity的任务栈通常这样使用:adb shell dumpsys activity activities (常见adb命令),但在Android代码如何实现adb命令调用呢?
答案是:Runtime.getRuntime.exec("dumpsys activity activities")
示例1、input tap x y 模拟点击 屏幕,生成 down-up事件 ,例如 input tap 300 400; 这个是 像素值
exeOrderOnTouchEvent(1200, 2000);
public String orderStr(float X, float Y) {
return String.format("input tap %.2f %.2f", X, Y);
}
示例2:input swipe x1 y1 x2 y2 模拟滑动 屏幕。例如 input swipe 250 250 300 300
exeOrderOnSwipeEvent(1200,1200,100,100);
public String swipeStr(float X1, float Y1,float X2, float Y2) {
return String.format("input swipe %.2f %.2f %.2f %.2f", X1, Y1,X2, Y2);
}
示例3:打印进程信息,不过滤任何条件
BufferedReader reader = null;
String content = "";
try {
//("ps -P|grep bg")执行失败,PC端adb shell ps -P|grep bg执行成功
//Process process = Runtime.getRuntime().exec("ps -P|grep tv");
//-P 显示程序调度状态,通常是bg或fg,获取失败返回un和er
// Process process = Runtime.getRuntime().exec("ps -P");
//打印进程信息,不过滤任何条件
Process process = Runtime.getRuntime().exec("ps");
reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
StringBuffer output = new StringBuffer();
int read;
char[] buffer = new char[4096];
while ((read = reader.read(buffer)) > 0) {
output.append(buffer, 0, read);
}
reader.close();
content = output.toString();
} catch (IOException e) {
e.printStackTrace();
}
示例4:dumpsys activity activities 指令返回错误内容
try {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("dumpsys activity activities");
InputStream stderr = proc.getErrorStream();
InputStreamReader isr = new InputStreamReader(stderr);
BufferedReader br = new BufferedReader(isr);
String line = null;
System.out.println("<error></error>");
while ((line = br.readLine()) != null)
System.out.println(line);
System.out.println("");
int exitVal = proc.waitFor();
System.out.println("Process exitValue: " + exitVal);
} catch (Throwable t) {
t.printStackTrace();
}