104

如何在手动提供 X 和 Y 坐标的同时使用 Android 模拟触摸事件?

4

7 回答 7

113

如果您扩展了视图,Valentin Rocher 的方法可以工作,但如果您使用的是事件侦听器,请使用:

view.setOnTouchListener(new OnTouchListener()
{
    public boolean onTouch(View v, MotionEvent event)
    {
        Toast toast = Toast.makeText(
            getApplicationContext(), 
            "View touched", 
            Toast.LENGTH_LONG
        );
        toast.show();

        return true;
    }
});


// Obtain MotionEvent object
long downTime = SystemClock.uptimeMillis();
long eventTime = SystemClock.uptimeMillis() + 100;
float x = 0.0f;
float y = 0.0f;
// List of meta states found here: developer.android.com/reference/android/view/KeyEvent.html#getMetaState()
int metaState = 0;
MotionEvent motionEvent = MotionEvent.obtain(
    downTime, 
    eventTime, 
    MotionEvent.ACTION_UP, 
    x, 
    y, 
    metaState
);

// Dispatch touch event to view
view.dispatchTouchEvent(motionEvent);

有关获取 MotionEvent 对象的更多信息,这是一个很好的答案:Android:如何创建 MotionEvent?

于 2011-08-09T18:52:05.417 回答
24

这是一个将触摸和拖动发送到应用程序的 monkeyrunner 脚本。我一直在使用它来测试我的应用程序是否可以处理快速重复的滑动手势。

# This is a monkeyrunner jython script that opens a connection to an Android
# device and continually sends a stream of swipe and touch gestures.
#
# See http://developer.android.com/guide/developing/tools/monkeyrunner_concepts.html
#
# usage: monkeyrunner swipe_monkey.py
#

# Imports the monkeyrunner modules used by this program
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice

# Connects to the current device
device = MonkeyRunner.waitForConnection()

# A swipe left from (x1, y) to (x2, y) in 2 steps
y = 400
x1 = 100
x2 = 300
start = (x1, y)
end = (x2, y)
duration = 0.2
steps = 2
pause = 0.2

for i in range(1, 250):
    # Every so often inject a touch to spice things up!
    if i % 9 == 0:
        device.touch(x2, y, 'DOWN_AND_UP')
        MonkeyRunner.sleep(pause)
    # Swipe right
    device.drag(start, end, duration, steps)
    MonkeyRunner.sleep(pause)
    # Swipe left
    device.drag(end, start, duration, steps)
    MonkeyRunner.sleep(pause)
于 2011-01-19T00:13:02.337 回答
21

使用 adb Shell 命令模拟触摸事件

adb shell input tap x y 

and also 

adb shell sendevent /dev/input/event0 3 0 5 
adb shell sendevent /dev/input/event0 3 1 29 
于 2014-03-12T12:39:40.457 回答
1

你应该试一试新的monkeyrunner。也许这可以解决你的问题。您将键码放入其中进行测试,也许触摸事件也是可能的。

于 2010-12-09T08:10:31.810 回答
1

如果我清楚地理解,您想以编程方式执行此操作。然后,您可以使用 的onTouchEvent方法,并使用您需要的坐标View创建一个。MotionEvent

于 2010-12-09T08:11:49.360 回答
0

使用 Monkey Script 时,我注意到 DispatchPress(KEYCODE_BACK) 没有做任何真正糟糕的事情。在许多情况下,这是因为 Activity 不使用 Key 事件。解决这个问题的方法是依次使用猴子脚本和 adb shell 输入命令的组合。

1 使用猴子脚本提供了一些很好的时序控制。为活动等待一定的秒数,这是一个阻塞的 adb 调用。
2 最后发送 adb shell input keyevent 4 将结束正在运行的 APK。

例如

adb shell monkey -p com.my.application -v -v -v -f /sdcard/monkey_script.txt 1
adb shell input keyevent 4

于 2013-01-25T04:25:49.307 回答
-6

MotionEvent 仅通过触摸屏幕生成。

于 2010-12-10T04:18:33.123 回答