Ir al contenido

Más visitados

Visitados recientemente



The monkeyrunner tool provides an API for writing programs that control an Android device or emulator from outside of Android code. With monkeyrunner, you can write a Python program that installs an Android application or test package, runs it, sends keystrokes to it, takes screenshots of its user interface, and stores screenshots on the workstation. The monkeyrunner tool is primarily designed to test applications and devices at the functional/framework level and for running unit test suites, but you are free to use it for other purposes.

The monkeyrunner tool is not related to the UI/Application Exerciser Monkey, also known as the monkey tool. The monkey tool runs in an adb shell directly on the device or emulator and generates pseudo-random streams of user and system events. In comparison, the monkeyrunner tool controls devices and emulators from a workstation by sending specific commands and events from an API.

The monkeyrunner tool provides these unique features for Android testing:

The monkeyrunner tool uses Jython, an implementation of Python that uses the Java programming language. Jython allows the monkeyrunner API to interact easily with the Android framework. With Jython you can use Python syntax to access the constants, classes, and methods of the API.

A Simple monkeyrunner Program

Here is a simple monkeyrunner program that connects to a device, creating a MonkeyDevice object. Using the MonkeyDevice object, the program installs an Android application package, runs one of its activities, and sends key events to the activity. The program then takes a screenshot of the result, creating a MonkeyImage object. From this object, the program writes out a .png file containing the screenshot.

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

# Connects to the current device, returning a MonkeyDevice object
device = MonkeyRunner.waitForConnection()

# Installs the Android package. Notice that this method returns a boolean, so you can test
# to see if the installation worked.

# sets a variable with the package's internal name
package = ''

# sets a variable with the name of an Activity in the package
activity = ''

# sets the name of the component to start
runComponent = package + '/' + activity

# Runs the component

# Presses the Menu button'KEYCODE_MENU', MonkeyDevice.DOWN_AND_UP)

# Takes a screenshot
result = device.takeSnapshot()

# Writes the screenshot to a file

The monkeyrunner API

The monkeyrunner API is contained in three modules in the package

In a Python program, you access each class as a Python module. The monkeyrunner tool does not import these modules automatically. To import a module, use the Python from statement:

from import <module>

where <module> is the class name you want to import. You can import more than one module in the same from statement by separating the module names with commas.

Running monkeyrunner

You can either run monkeyrunner programs from a file, or enter monkeyrunner statements in an interactive session. You do both by invoking the monkeyrunner command which is found in the tools/ subdirectory of your SDK directory. If you provide a filename as an argument, the monkeyrunner command runs the file's contents as a Python program; otherwise, it starts an interactive session.

The syntax of the monkeyrunner command is

monkeyrunner -plugin <plugin_jar> <program_filename> <program_options>

Table 1 explains the flags and arguments.

Table 1. monkeyrunner flags and arguments.

Argument Description
-plugin <plugin_jar> (Optional) Specifies a .jar file containing a plugin for monkeyrunner. To learn more about monkeyrunner plugins, see Extending monkeyrunner with plugins. To specify more than one file, include the argument multiple times.
<program_filename> If you provide this argument, the monkeyrunner command runs the contents of the file as a Python program. If the argument is not provided, the command starts an interactive session.
<program_options> (Optional) Flags and arguments for the program in <program_file>.

monkeyrunner Built-in Help

You can generate an API reference for monkeyrunner by running:

monkeyrunner <format> <outfile>

The arguments are:

Extending monkeyrunner with Plugins

You can extend the monkeyrunner API with classes you write in the Java programming language and build into one or more .jar files. You can use this feature to extend the monkeyrunner API with your own classes or to extend the existing classes. You can also use this feature to initialize the monkeyrunner environment.

To provide a plugin to monkeyrunner, invoke the monkeyrunner command with the -plugin <plugin_jar> argument described in table 1.

In your plugin code, you can import and extend the main monkeyrunner classes MonkeyDevice, MonkeyImage, and MonkeyRunner in (see The monkeyrunner API).

Note that plugins do not give you access to the Android SDK. You can't import packages such as This is because monkeyrunner interacts with the device or emulator below the level of the framework APIs.

The plugin startup class

The .jar file for a plugin can specify a class that is instantiated before script processing starts. To specify this class, add the key MonkeyRunnerStartupRunner to the .jar file's manifest. The value should be the name of the class to run at startup. The following snippet shows how you would do this within an ant build script:

<jar jarfile="myplugin" basedir="${build.dir}">
<attribute name="MonkeyRunnerStartupRunner" value="com.myapp.myplugin"/>

To get access to monkeyrunner's runtime environment, the startup class can implement<PythonInterpreter>. For example, this class sets up some variables in the default namespace:


import org.python.util.PythonInterpreter;

public class Main implements Predicate<PythonInterpreter> {
    public boolean apply(PythonInterpreter anInterpreter) {

        * Examples of creating and initializing variables in the monkeyrunner environment's
        * namespace. During execution, the monkeyrunner program can refer to the variables "newtest"
        * and "use_emulator"
        anInterpreter.set("newtest", "enabled");
        anInterpreter.set("use_emulator", 1);

        return true;
Utilizamos cookies para registrar tus preferencias de idioma y visualización de este sitio web.

Recibe novedades y consejos para desarrolladores de Android que te ayudarán a alcanzar el éxito en Google Play.

* Campos obligatorios

¡Ya está!

Seguir a Google Developers en WeChat

¿Quieres navegar por el sitio web en ?

Has solicitado que la página aparezca en , pero tu idioma preferido en este sitio web es el .

¿Quieres cambiar tu preferencia de idioma y navegar por este sitio web en ? Si prefieres dejarlo para más tarde, usa el menú de idioma que se encuentra en la parte inferior de cada página web.

Para esta clase se necesita un nivel de API o superior

La documentación está oculta porque el nivel de API que has seleccionado para ella es . Cambia el nivel de API de la documentación en el selector situado encima del menú de navegación de la izquierda.

Para obtener más información sobre cómo especificar el nivel de API que requiere tu aplicación, lee el artículo Supporting Different Platform Versions (Compatibilidad con diferentes versiones de la plataforma).

Take a short survey?
Help us improve the Android developer experience. (April 2018 — Developer Survey)