Android之代码实现adb shell命令

我们查看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();
}

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值