Android – Automating Testing and Store Listing Screenshots with Monkeyrunner

In this tutorial we’ll be talking about Monkeyrunner and automating tasks such as preparing screenshots for Google Play Store listings.

Monkeyrunner is a high level scripting language that is capable of automating tasks such as;

  • Installing/uninstalling apps
  • Taking screenshots and saving them to your local machine
  • Sending touch events i.e. performing gestures, pressing buttons, dragging and scrolling
  • Inputting text

There are three classes in the Monkeyrunner framework these are;

  1. MonkeyRunner – Connect to devices or emulators
  2. MonkeyDevice – Represents the device you are connected to. Allows you to perform touch events, apk installations, start activities
  3. MonkeyImage – Represents the raw image captured from the device and allows you to compare images for testing

In order to run a Monkeyrunner script you need to use the monkeyrunner compiler available in the android-sdk/tools directory, rather than python to run your python code.


In here you’ll have an executable moneyrunner which you’ll need to use to run your python scripts.

Go ahead and create a new python file, lets call it, place it anywhere you’d like. Let’s start by connecting to the device, installing your APK, taking a screenshot and saving the screenshot to our current directory.

You’ll need to tell MonkeyRunner where your apk file is so that the can install the apk. You need to run your app on a device at least once for the IDE to generate you an apk file!

You can find your APK file in the following locations:
– projectFolder/yourNamespace/bin/your.apk
Android Studio
– projectFolder/yourNamespace/build/outputs/apk/your.apk

Create a py file and name it – it should look like the following;

from import MonkeyRunner, MonkeyDevice
# Connects to the first device available through the adb tool
device = MonkeyRunner.waitForConnection()
# install the APK
# declare your package name
package = 'com.your.application'
# declare your activity that you want to start
activity = 'com.your.application.MainActivity'
# prepare the whole package + activity string
activityToRun = package + '/' + activity
# start the activity above
# take a screenshot
screenshot = device.takeSnapshot()
# Writes the screenshot to a file

Place your APK file in the same directory as your py script, move into your androidsdk/tools directory and run your file in terminal.

cd into the <androidSDK>/tools
./monkeyrunner /your/path/to/

Now check out the <androidsdk>/tools folder and you should have a screenshot1.png.

MonkeyRunner Screenshot

You can also automate gestures on the phone as well as button presses, more on this in the next post.

Using the device object call press and pass in the keycode along with UP, DOWN or DOWN_AND_UP to simulate the gesture you want.'KEYCODE_MENU', MonkeyDevice.DOWN_AND_UP)

You can find the complete list of keycodes here –