如何在Android中模拟触摸事件?

ind*_*ira 97 android gesture-recognition adb

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

azd*_*dev 108

如果你扩展了你的视图,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);
Run Code Online (Sandbox Code Playgroud)

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

  • 很好的答案,但作为 Android 初学者,OnTouchListener 使我感到困惑。我现在意识到监听器不是模拟所必需的。唯一需要的是代码后半部分的 MotionEvent。 (2认同)
  • @tudor - 仅模拟真实的触摸.'downTime`将是用户触摸屏幕的时间,而在这种情况下`eventTime`将是用户抬起手指(`ACTION_UP`)的时间.如果两者都相同,我不确定它是否仍然有用.您可以测试并发布结果. (2认同)

小智 22

这是一个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)
Run Code Online (Sandbox Code Playgroud)


Arj*_*ash 20

使用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 
Run Code Online (Sandbox Code Playgroud)

  • 嘿,如果想使用 adb 命令模拟捏缩放,并且我有捏缩放的坐标,该怎么办 (2认同)

key*_*fer 1

你应该尝试一下新的跑猴者。也许这可以解决您的问题。你把按键代码放进去测试一下,也许触摸事件也是可能的。