Skip to content

Android 模拟点击

ythy edited this page Sep 30, 2017 · 5 revisions

重点

  1. 需要root
  2. adb shell 指令

指令

点击指令: input tap x y

代码

 private void execShellCmd(String cmd){
    OutputStream outputStream = null;
    DataOutputStream dataOutputStream = null;
    Process process = null;
    try {
        process =  Runtime.getRuntime().exec("su");
		// 获取输出流
        outputStream = process.getOutputStream();
		dataOutputStream = new DataOutputStream(
				outputStream);
		dataOutputStream.writeBytes(cmd);
		dataOutputStream.flush();
        dataOutputStream.close();
        outputStream.close();
	} catch (Throwable t) {
	    t.printStackTrace();
            mClickThreadCount = 0;
	}finally {
            try {
                process.getOutputStream().close();
                process.getErrorStream().close();
                process.getInputStream().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

 execShellCmd("input tap 40 100");

要点

  1. 获取点击坐标时 浮动窗口的坐标是减去状态栏的 , 所以计算 input tap 坐标时,Y值要加上状态栏高度。
  2. 重要! 执行完shell命令, finally 中必须将Process所有的输入输出流close掉,否则会报错:java.io.IOException: Too many open files, linux系统的文件句柄数超限错误
Clone this wiki locally