【发布时间】:2014-11-13 00:44:09
【问题描述】:
是否可以通过代码在屏幕上的特定点(例如 (x,y))生成假触摸?我的活动上有一个按钮,我不想通过触摸屏点击它?有什么方法可以实现吗?
【问题讨论】:
-
我确信一定有,因为您可能知道有一个名为“Monkey”的程序来测试您的应用程序...尝试谷歌搜索“猴子如何点击屏幕?”
标签: android touchscreen
是否可以通过代码在屏幕上的特定点(例如 (x,y))生成假触摸?我的活动上有一个按钮,我不想通过触摸屏点击它?有什么方法可以实现吗?
【问题讨论】:
标签: android touchscreen
这个方法应该可以帮到你。
http://developer.android.com/reference/android/view/View.html#performClick()
myButton.performClick();
【讨论】:
以下代码会生成触摸事件,就像屏幕真的被触摸一样。
注意:仅限 root 设备
public class Tap {
private static final String SU = "su", TAG = Tap.class.getSimpleName(),
COMMAND = "/system/bin/input tap %d %d ", ASCII = "ASCII";
public Tap() {
}
public void tap(int x1, int y1) {
TapTask t = new TapTask(x1, y1);
t.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
private class TapTask extends AsyncTask<Void, Void, Void> {
private int x1, y1;
public TapTask(int x1, int y1) {
this.x1 = x1;
this.y1 = y1;
}
protected Void doInBackground(Void... args) {
try {
Process sh = Runtime.getRuntime().exec(SU, null, null);
OutputStream os = sh.getOutputStream();
os.write((String.format(COMMAND, x1,y1)).getBytes(ASCII));
os.flush();
os.close();
sh.waitFor();
Log.i(TAG,String.format("tap %d %d ",x1,y1));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
}
【讨论】: