Button Pressing Emulation On Android

From DAVE Developer's Wiki
Jump to: navigation, search
Info Box
Android-logo.jpg Applies to Android


Introduction[edit | edit source]

Sometimes, during the development phases, real hardware buttons are not available, causing bad interaction with the Android interface. It would help to have an emulator to send events as button pressing to the Android system, and it's here that the monkeyrunner tool shows its usefulness.

Setting up monkeyrunner[edit | edit source]

You can run monkeyrunner from your host machine when the ADB connection with the device is established. The monkeyrunner command is found in the tools/ subdirectory of your SDK directory. Launching monkeyrunner, you can both activate a script or the interactive shell. For more information, please refer to Running monkeyrunner.

Emulating key pressing[edit | edit source]

Once the connection is established, you can run monkeyrunner from your PC and enter the commands from the interactive shell. As an example, the following sequence emulates the "HOME" button pressing down:

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

# Connects to the current device, returning a MonkeyDevice object
device = MonkeyRunner.waitForConnection(10,"emulator-5554")

# Presses the Home button
device.press('KEYCODE_HOME',MonkeyDevice.DOWN_AND_UP)

Please refer to the MonkeyDevice and KeyEvent documentation for further information.