Android Debug Bridge

Android Debug Bridge (adb) is a versatile command line tool that lets you communicate with an emulator instance or connected Android-powered device. It is a client-server program that includes three components:
A client, which runs on your development machine. You can invoke a client from a shell by issuing an adb command. Other Android tools such as the ADT plugin and DDMS also create adb clients.
A server, which runs as a background process on your development machine. The server manages communication between the client and the adb daemon running on an emulator or device.
A daemon, which runs as a background process on each emulator or device instance.
You can find the adb tool in <sdk>/platform-tools/.
When you start an adb client, the client first checks whether there is an adb server process already running. If there isn't, it starts the server process. When the server starts, it binds to local TCP port 5037 and listens for commands sent from adb clients—all adb clients use port 5037 to communicate with the adb server.
The server then sets up connections to all running emulator/device instances. It locates emulator/device instances by scanning odd-numbered ports in the range 5555 to 5585, the range used by emulators/devices. Where the server finds an adb daemon, it sets up a connection to that port. Note that each emulator/device instance acquires a pair of sequential ports — an even-numbered port for console connections and an odd-numbered port for adb connections. For example:
Emulator 1, console: 5554
Emulator 1, adb: 5555
Emulator 2, console: 5556
Emulator 2, adb: 5557 ...
As shown, the emulator instance connected to adb on port 5555 is the same as the instance whose console listens on port 5554.
Once the server has set up connections to all emulator instances, you can use adb commands to control and access those instances. Because the server manages connections to emulator/device instances and handles commands from multiple adb clients, you can control any emulator/device instance from any client (or from a script).
The sections below describe the commands that you can use to access adb capabilities and manage the state of an emulator/device. Note that if you are developing Android applications in Eclipse and have installed the ADT plugin, you do not need to access adb from the command line. The ADT plugin provides a transparent integration of adb into the Eclipse IDE. However, you can still use adb directly as necessary, such as for debugging.
Issuing adb Commands
You can issue adb commands from a command line on your development machine or from a script. The usage is:
adb [-d|-e|-s <serialNumber>] <command>
When you issue a command, the program invokes an adb client. The client is not specifically associated with any emulator instance, so if multiple emulators/devices are running, you need to use the -d option to specify the target instance to which the command should be directed. For more information about using this option, see Directing Commands to a Specific Emulator/Device Instance.
Querying for Emulator/Device Instances
Before issuing adb commands, it is helpful to know what emulator/device instances are connected to the adb server. You can generate a list of attached emulators/devices using the devices command:
adb devices
In response, adb prints this status information for each instance:
Serial number — A string created by adb to uniquely identify an emulator/device instance by its console port number. The format of the serial number is <type>-<consolePort>. Here's an example serial number: emulator-5554
State — The connection state of the instance may be one of the following:
offline — the instance is not connected to adb or is not responding.
device — the instance is now connected to the adb server. Note that this state does not imply that the Android system is fully booted and operational, since the instance connects to adb while the system is still booting. However, after boot-up, this is the normal operational state of an emulator/device instance.
no device — there is no emulator/device connected.
The output for each instance is formatted like this:
[serialNumber] [state]
Here's an example showing the devices command and its output:
$ adb devices
List of devices attached
emulator-5554  device
emulator-5556  device
emulator-5558  device
Directing Commands to a Specific Emulator/Device Instance
If multiple emulator/device instances are running, you need to specify a target instance when issuing adb commands. To so so, use the -s option in the commands. The usage for the -s option is:
adb -s <serialNumber><command>
As shown, you specify the target instance for a command using its adb-assigned serial number. You can use the devices command to obtain the serial numbers of running emulator/device instances.
Here is an example:
adb -s emulator-5556 install helloWorld.apk
Note that, if you issue a command without specifying a target emulator/device instance using -s, adb generates an error.
Installing an Application
You can use adb to copy an application from your development computer and install it on an emulator/device instance. To do so, use the install command. With the command, you must specify the path to the .apk file that you want to install:
adb install <path_to_apk>
For more information about how to create an .apk file that you can install on an emulator/device instance, see Building and Running
Note that, if you are using the Eclipse IDE and have the ADT plugin installed, you do not need to use adb (or aapt) directly to install your application on the emulator/device. Instead, the ADT plugin handles the packaging and installation of the application for you.
Forwarding Ports
You can use the forward command to set up arbitrary port forwarding — forwarding of requests on a specific host port to a different port on an emulator/device instance. Here's how you would set up forwarding of host port 6100 to emulator/device port 7100:
adb forward tcp:6100 tcp:7100
You can also use adb to set up forwarding to named abstract UNIX domain sockets, as illustrated here:
adb forward tcp:6100 local:logd
Copying Files to or from an Emulator/Device Instance
You can use the adb commands pull and push to copy files to and from an emulator/device instance's data file. Unlike the install command, which only copies an .apk file to a specific location, the pull and push commands let you copy arbitrary directories and files to any location in an emulator/device instance.
To copy a file or directory (recursively) from the emulator or device, use
adb pull <remote><local>
To copy a file or directory (recursively) to the emulator or device, use
adb push <local><remote>
In the commands, <local> and <remote> refer to the paths to the target files/directory on your development machine (local) and on the emulator/device instance (remote).
Here's an example:
adb push foo.txt /sdcard/foo.txt
Listing of adb Commands
The table below lists all of the supported adb commands and explains their meaning and usage.
Category
Command
Description
Comments
Options
-d
Direct an adb command to the only   attached USB device.
Returns an error if more than one USB device is attached.
-e
Direct an adb command to the only   running emulator instance.
Returns an error if more than one emulator instance is running.
-s <serialNumber>
Direct an adb command a specific emulator/device instance, referred to by its adb-assigned serial number (such as "emulator-5556").
If not specified, adb generates an error.
General
devices
Prints a list of all attached emulator/device instances.
See Querying for Emulator/Device Instances for more information.
help
Prints a list of supported adb commands.

version
Prints the adb version number.

Debug
logcat [<option>] [<filter-specs>]
Prints log data to the screen.

bugreport
Prints dumpsys, dumpstate, and logcat data to the screen, for the purposes of bug reporting.

jdwp
Prints a list of available JDWP processes on a given device.
You can use the forward jdwp:<pid> port-forwarding specification to connect to a specific JDWP process. For example:
adb forward tcp:8000 jdwp:472
jdb -attach localhost:8000
Data
install <path-to-apk>
Pushes an Android application (specified as a full path to an .apk file) to the data file of an emulator/device.

pull <remote> <local>
Copies a specified file from an emulator/device instance to your development computer.

push <local> <remote>
Copies a specified file from your development computer to an emulator/device instance.

Ports and Networking
forward <local> <remote>
Forwards socket connections from a specified local port to a specified remote port on the emulator/device   instance.
Port specifications can use these schemes:
tcp:<portnum>
local:<UNIX domain socket name>
dev:<character device name>
jdwp:<pid>
ppp <tty> [parm]...
Run PPP over USB.
<tty> — the tty for PPP stream. For example dev:/dev/omap_csmi_ttyl.
[parm]... — zero or more PPP/PPPD options, such as defaultroute, local, notty, etc.
Note that you should not automatically start a PPP connection.
Scripting
get-serialno
Prints the adb instance serial number string.
See Querying for Emulator/Device Instances for more information.
get-state
Prints the adb state of an emulator/device instance.
wait-for-device
Blocks execution until the device is online — that is, until the instance state is device.
You can prepend this command to other adb commands, in which case adb will wait until the emulator/device instance is connected before issuing the other commands. Here's an example:
adb wait-for-device shell getprop
Note that this command does notcause adb to wait until the entire system is fully booted. For that reason, you should not prepend it to other commands that require a fully booted system. As an example, the install requires the Android package manager, which is available only after the system is fully booted. A command such as
adb wait-for-device install <app>.apk
would issue the install command as soon as the emulator or device instance connected to the adb server, but before the Android system was fully booted, so it would result in an error.
Server
start-server
Checks whether the adb server process is running and starts it, if not.

kill-server
Terminates the adb server process.

Shell
shell
Starts a remote shell in the target emulator/device instance.
See Issuing Shell Commands for more information.
shell [<shellCommand>]
Issues a shell command in the target emulator/device instance and then exits the remote shell.
Issuing Shell Commands
Adb provides an ash shell that you can use to run a variety of commands on an emulator or device. The command binaries are stored in the file system of the emulator or device, in this location:
/system/bin/...
You can use the shell command to issue commands, with or without entering the adb remote shell on the emulator/device.
To issue a single command without entering a remote shell, use the shell command like this:
adb [-d|-e|-s {<serialNumber>}] shell <shellCommand>
To drop into a remote shell on a emulator/device instance, use the shell command like this:
adb [-d|-e|-s {<serialNumber>}] shell
When you are ready to exit the remote shell, use CTRL+D or exit to end the shell session.
The sections below provide more information about shell commands that you can use.
Examining sqlite3 Databases from a Remote Shell
From an adb remote shell, you can use the sqlite3 command-line program to manage SQLite databases created by Android applications. The sqlite3 tool includes many useful commands, such as .dump to print out the contents of a table and .schema to print the SQL CREATE statement for an existing table. The tool also gives you the ability to execute SQLite commands on the fly.
To use sqlite3, enter a remote shell on the emulator instance, as described above, then invoke the tool using the sqlite3 command. Optionally, when invoking sqlite3 you can specify the full path to the database you want to explore. Emulator/device instances store SQLite3 databases in the folder /data/data/<package_name>/databases/.
Here's an example:
$ adb -s emulator-5554 shell
# sqlite3 /data/data/com.example.google.rss.rssexample/databases/rssitems.db
SQLite version 3.3.12
Enter ".help" for instructions
.... enter commands, then quit...
sqlite> .exit
Once you've invoked sqlite3, you can issue sqlite3 commands in the shell. To exit and return to the adb remote shell, use exit or CTRL+D.
UI/Application Exerciser Monkey
The Monkey is a program that runs on your emulator or device and generates pseudo-random streams of user events such as clicks, touches, or gestures, as well as a number of system-level events. You can use the Monkey to stress-test applications that you are developing, in a random yet repeatable manner.
The simplest way to use the monkey is with the following command, which will launch your application and send 500 pseudo-random events to it.
$ adb shell monkey -v -p your.package.name 500
For more information about command options for Monkey, see the complete UI/Application Exerciser Monkey documentation page.
Other Shell Commands
The table below lists several of the adb shell commands available. For a complete list of commands and programs, start an emulator instance and use the adb -help command.
adb shell ls /system/bin
Help is available for most of the commands.
Shell Command
Description
Comments
dumpsys
Dumps system data to the screen.
The Dalvik Debug Monitor Server (DDMS) tool offers integrated debug environment that you may find easier to use.
dumpstate
Dumps state to a file.
logcat [<option>]... [<filter-spec>]...
Enables radio logging and prints output to the screen.
dmesg
Prints kernel debugging messages to the screen.
start
Starts (restarts) an emulator/device instance.

stop
Stops execution of an emulator/device instance.

Enabling logcat Logging
The Android logging system provides a mechanism for collecting and viewing system debug output. Logs from various applications and portions of the system are collected in a series of circular buffers, which then can be viewed and filtered by the logcat command.
You can use the logcat command to view and follow the contents of the system's log buffers. The general usage is:
[adb] logcat [<option>] ... [<filter-spec>] ...
You can use the logcat command from your development computer or from a remote adb shell in an emulator/device instance. To view log output in your development computer, you use
$ adblogcat
and from a remote adb shell you use
# logcat
See Reading and Writing Logs for complete information about logcat commend options and filter specifications.
Stopping the adb Server
In some cases, you might need to terminate the adb server process and then restart it. For example, if adb does not respond to a command, you can terminate the server and restart it and that may resolve the problem.
To stop the adb server, use the kill-server. You can then restart the server by issuing any adb command.
Except as noted, this content is licensed under Creative Commons Attribution 2.5. For details and restrictions, see the Content License.
About Android  |  Legal  |  Support

monkeyrunner
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:
Multiple device control: The monkeyrunner API can apply one or more test suites across multiple devices or emulators. You can physically attach all the devices or start up all the emulators (or both) at once, connect to each one in turn programmatically, and then run one or more tests. You can also start up an emulator configuration programmatically, run one or more tests, and then shut down the emulator.

Functional testing: monkeyrunner can run an automated start-to-finish test of an Android application. You provide input values with keystrokes or touch events, and view the results as screenshots.
Regression testing - monkeyrunner can test application stability by running an application and comparing its output screenshots to a set of screenshots that are known to be correct.
Extensible automation - Since monkeyrunner is an API toolkit, you can develop an entire system of Python-based modules and programs for controlling Android devices. Besides using the monkeyrunner API itself, you can use the standard Python os and subprocess modules to call Android tools such as Android Debug Bridge.
You can also add your own classes to the monkeyrunner API. This is described in more detail in the section Extending monkeyrunner with plugins.
The monkeyrunner tool uses Jython, a 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
fromcom.android.monkeyrunner 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.
device.installPackage('myproject/bin/MyApplication.apk')

# sets a variable with the package's internal name
package = 'com.example.android.myapplication'

# sets a variable with the name of an Activity in the package
activity = 'com.example.android.myapplication.MainActivity'

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

# Runs the component
device.startActivity(component=runComponent)

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

# Takes a screenshot
result = device.takeSnapshot()

# Writes the screenshot to a file
result.writeToFile('myproject/shot1.png','png')

The monkeyrunner API
The monkeyrunner API is contained in three modules in the package com.android.monkeyrunner:
MonkeyRunner: A class of utility methods for monkeyrunner programs. This class provides a method for connecting monkeyrunner to a device or emulator. It also provides methods for creating UIs for a monkeyrunner program and for displaying the built-in help.
MonkeyDevice: Represents a device or emulator. This class provides methods for installing and uninstalling packages, starting an Activity, and sending keyboard or touch events to an application. You also use this class to run test packages.
MonkeyImage: Represents a screen capture image. This class provides methods for capturing screens, converting bitmap images to various formats, comparing two MonkeyImage objects, and writing an image to a file.
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:
fromcom.android.monkeyrunner 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 help.py <format><outfile>
The arguments are:
<format> is either text for plain text output or html for HTML output.
<outfile> is a path-qualified name for the output file.
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 the main monkeyrunner classes MonkeyDevice, MonkeyImage, and MonkeyRunner in com.android.monkeyrunner (see Themonkeyrunner API).
Note that plugins do not give you access to the Android SDK. You can't import packages such as com.android.app. 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}">
<manifest>
<attribute name="MonkeyRunnerStartupRunner" value="com.myapp.myplugin"/>
</manifest>
</jar>

To get access to monkeyrunner's runtime environment, the startup class can implement com.google.common.base.Predicate<PythonInterpreter>. For example, this class sets up some variables in the default namespace:
PROg
packagecom.android.example;

importcom.google.common.base.Predicate;
importorg.python.util.PythonInterpreter;

public class Main implements Predicate<PythonInterpreter> {
    @Override
publicboolean apply(PythonInterpreteranInterpreter) {

        /*
        * Examples of creating and initializing variables in the monkeyrunnerenvironment'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;
    }
}

Comments

Popular posts from this blog

Online Selenium Training With Real Time Scenario

Online Tricentis Tosca Automation Training with Real Time Scenarios

Online Training for Manual/Functional