How to simulate a touch event in Android? How to simulate a touch event in Android? android android

How to simulate a touch event in Android?


Valentin Rocher's method works if you've extended your view, but if you're using an event listener, use this:

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 objectlong 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 viewview.dispatchTouchEvent(motionEvent);

For more on obtaining a MotionEvent object, here is an excellent answer: Android: How to create a MotionEvent?


Here is a monkeyrunner script that sends touch and drags to an application. I have been using this to test that my application can handle rapid repetitive swipe gestures.

# 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 programfrom com.android.monkeyrunner import MonkeyRunner, MonkeyDevice# Connects to the current devicedevice = MonkeyRunner.waitForConnection()# A swipe left from (x1, y) to (x2, y) in 2 stepsy = 400x1 = 100x2 = 300start = (x1, y)end = (x2, y)duration = 0.2steps = 2pause = 0.2for 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)


use adb Shell Commands to simulate the touch event

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