# 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
and so on...

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 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).

Note: When you connect a device running Android 4.2.2 or higher to your computer, the system shows a dialog asking whether to accept an RSA key that allows debugging through this computer. This security mechanism protects user devices because it ensures that USB debugging and other adb commands cannot be executed unless you're able to unlock the device and acknowledge the dialog. This requires that you have adb version 1.0.31 (available with SDK Platform-tools r16.0.1 and higher) in order to debug on a device running Android 4.2.2 or higher.

## Syntax

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>


If there's only one emulator running or only one device connected, the adb command is sent to that device by default. If multiple emulators are running and/or multiple devices are attached, you need to use the -d-e, or -s option to specify the target device to which the command should be directed.

## Commands

The table below lists all of the supported adb commands and explains their meaning and usage.

Table 1. Available adb commands

Category Command Description Comments
Target Device -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"). See Directing Commands to a Specific Emulator/Device Instance.
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 dumpsysdumpstate, andlogcat 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 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 exampledev:/dev/omap_csmi_ttyl.
• [parm]... — zero or more PPP/PPPD options, such asdefaultroutelocal,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 not cause 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.

## 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 must specify a target instance when issuing adb commands. To do 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 devicescommand to obtain the serial numbers of running emulator/device instances. For example:

adb -s emulator-5556 install helloWorld.apk

Note that, if you issue a command without specifying a target emulator/device instance while multiple devices are available, adb generates an error.

If you have multiple devices available (hardware or emulated), but only one is an emulator, simply use the -e option to send commands to the emulator. Likewise if there's multiple devices but only one hardware device attached, use the -doption to send commands to the hardware device.

## 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. Unlike theinstall 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 (and its sub-directories) from the emulator or device, use

adb pull <remote> <local>

To copy a file or directory (and its sub-directories) 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). For example:

adb push foo.txt /sdcard/foo.txt

## Issuing Shell Commands

Adb provides a Unix shell that you can use to run a variety of commands on an emulator or connected device. The command binaries are stored in the file system of the emulator or device, at /system/bin/...

Two of the most common command tools are activity manager (am) and package manager (pm).

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 <shell_command>

Or enter a remote shell on an emulator/device like this:

adb [-d|-e|-s <serialNumber>] shell

When you are ready to exit the remote shell, press CTRL+D or type exit.

### Using activity manager (am)

Within an adb shell, you can issue commands with the activity manager (am) tool to perform various system actions, such as start an activity, force-stop a process, broadcast an intent, modify the device screen properties, and more. While in a shell, the syntax is:

am <command>


You can also issue an activity manager command directly from adb without entering a remote shell. For example:

adb shell am start -a android.intent.action.VIEW


Table 2. Available activity manager commands

Command Description
start [options] <INTENT> Start an Activity specified by <INTENT>.

Options are:

• -D: Enable debugging.
• -W: Wait for launch to complete.
• --start-profiler <FILE>: Start profiler and send results to<FILE>.
• -P <FILE>: Like --start-profiler, but profiling stops when the app goes idle.
• -R: Repeat the activity launch <COUNT> times. Prior to each repeat, the top activity will be finished.
• -S: Force stop the target app before starting the activity.
• --opengl-trace: Enable tracing of OpenGL functions.
• --user <USER_ID> | current: Specify which user to run as; if not specified, then run as the current user.
startservice [options] <INTENT> Start the Service specified by <INTENT>.

Options are:

• --user <USER_ID> | current: Specify which user to run as; if not specified, then run as the current user.
force-stop <PACKAGE> Force stop everything associated with <PACKAGE> (the app's package name).
kill [options] <PACKAGE> Kill all processes associated with <PACKAGE> (the app's package name). This command kills only processes that are safe to kill and that will not impact the user experience.

Options are:

• --user <USER_ID> | all | current: Specify user whose processes to kill; all users if not specified.
kill-all Kill all background processes.
broadcast [options] <INTENT> Issue a broadcast intent.

Options are:

• [--user <USER_ID> | all | current]: Specify which user to send to; if not specified then send to all users.
instrument [options] <COMPONENT> Start monitoring with an Instrumentation instance. Typically the target <COMPONENT> is the form<TEST_PACKAGE>/<RUNNER_CLASS>.

Options are:

• -r: Print raw results (otherwise decode<REPORT_KEY_STREAMRESULT>). Use with [-e perf true] to generate raw output for performance measurements.
• -e <NAME> <VALUE>: Set argument <NAME> to <VALUE>. For test runners a common form is -e <testrunner_flag> <value>[,<value>...].
• -p <FILE>: Write profiling data to <FILE>.
• -w: Wait for instrumentation to finish before returning. Required for test runners.
• --no-window-animation: Turn off window animations while running.
• --user <USER_ID> | current: Specify which user instrumentation runs in; current user if not specified.
profile start <PROCESS> <FILE> Start profiler on <PROCESS>, write results to <FILE>.
profile stop <PROCESS> Stop profiler on <PROCESS>.
dumpheap [options] <PROCESS> <FILE> Dump the heap of <PROCESS>, write to <FILE>.

Options are:

• --user [<USER_ID>|current]: When supplying a process name, specify user of process to dump; uses current user if not specified.
• -n: Dump native heap instead of managed heap.
set-debug-app [options] <PACKAGE> Set application <PACKAGE> to debug.

Options are:

• -w: Wait for debugger when application starts.
• --persistent: Retain this value.
clear-debug-app Clear the package previous set for debugging with set-debug-app.
monitor [options] Start monitoring for crashes or ANRs.

Options are:

• --gdb: Start gdbserv on the given port at crash/ANR.
screen-compat [on|off] <PACKAGE> Control screen compatibility mode of <PACKAGE>.

display-size [reset|<WxH>] Override emulator/device display size. This command is helpful for testing your app across different screen sizes by mimicking a small screen resolution using a device with a large screen, and vice versa.

Example:
am display-size 1280x800

display-density <dpi> Override emulator/device display density. This command is helpful for testing your app across different screen densities on high-density screen environment using a low density screen, and vice versa.

Example:
am display-density 480

to-uri <INTENT> Print the given intent specification as a URI.
to-intent-uri <INTENT> Print the given intent specification as an intent: URI.

### Using package manager (pm)

Within an adb shell, you can issue commands with the package manager (pm) tool to perform actions and queries on application packages installed on the device. While in a shell, the syntax is:

pm <command>


You can also issue a package manager command directly from adb without entering a remote shell. For example:

adb shell pm uninstall com.example.MyApp


Table 3. Available package manager commands.

Command Description
list packages [options] <FILTER> Prints all packages, optionally only those whose package name contains the text in <FILTER>.

Options:

• -f: See their associated file.
• -d: Filter to only show disabled packages.
• -e: Filter to only show enabled packages.
• -s: Filter to only show system packages.
• -3: Filter to only show third party packages.
• -i: See the installer for the packages.
• -u: Also include uninstalled packages.
• --user <USER_ID>: The user space to query.
list permission-groups Prints all known permission groups.
list permissions [options] <GROUP> Prints all known permissions, optionally only those in<GROUP>.

Options:

• -g: Organize by group.
• -f: Print all information.
• -s: Short summary.
• -d: Only list dangerous permissions.
• -u: List only the permissions users will see.
list instrumentation List all test packages.

Options:

• -f: List the APK file for the test package.
• <TARGET_PACKAGE>: List test packages for only this app.
list features Prints all features of the system.
list libraries Prints all the libraries supported by the current device.
list users Prints all users on the system.
path <PACKAGE> Print the path to the APK of the given <PACKAGE>.
install [options] <PATH> Installs a package (specified by <PATH>) to the system.

Options:

• -l: Install the package with forward lock.
• -r: Reinstall an exisiting app, keeping its data.
• -t: Allow test APKs to be installed.
• -i <INSTALLER_PACKAGE_NAME>: Specify the installer package name.
• -s: Install package on the shared mass storage (such as sdcard).
• -f: Install package on the internal system memory.
• -d: Allow version code downgrade.
uninstall [options] <PACKAGE> Removes a package from the system.

Options:

• -k: Keep the data and cache directories around after package removal.
clear <PACKAGE> Deletes all data associated with a package.
enable <PACKAGE_OR_COMPONENT> Enable the given package or component (written as "package/class").
disable <PACKAGE_OR_COMPONENT> Disable the given package or component (written as "package/class").
disable-user [options] <PACKAGE_OR_COMPONENT>

Options:

• --user <USER_ID>: The user to disable.
grant <PACKAGE_PERMISSION> Grant permissions to applications. Only optional permissions the application has declared can be granted.
revoke <PACKAGE_PERMISSION> Revoke permissions to applications. Only optional permissions the application has declared can be revoked.
set-install-location <LOCATION> Changes the default install location. Location values:
• 0: Auto—Let system decide the best location.
• 1: Internal—install on internal device storage.
• 2: External—install on external media.

Note: This is only intended for debugging; using this can cause applications to break and other undesireable behavior.

get-install-location Returns the current install location. Return values:
• 0 [auto]: Lets system decide the best location
• 1 [internal]: Installs on internal device storage
• 2 [external]: Installs on external media
set-permission-enforced <PERMISSION> [true|false] Specifies whether the given permission should be enforced.
trim-caches <DESIRED_FREE_SPACE> Trim cache files to reach the given free space.
create-user <USER_NAME> Create a new user with the given <USER_NAME>, printing the new user identifier of the user.
remove-user <USER_ID> Remove the user with the given <USER_IDENTIFIER>, deleting all data associated with that user
get-max-users Prints the maximum number of users supported by the device.

### 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 thesqlite3 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
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 launches your application and sends 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 Monkeydocumentation page.

### Other shell commands

For a list of all the available shell programs, use the following command:

adb shell ls /system/bin

Help is available for most of the commands.

Table 4 lists some of the more common adb shell commands.

Table 4. Some other adb shell 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 system and app 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

adb logcat

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 command. You can then restart the server by issuing any other adb command.

# 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
and so on...

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 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).

Note: When you connect a device running Android 4.2.2 or higher to your computer, the system shows a dialog asking whether to accept an RSA key that allows debugging through this computer. This security mechanism protects user devices because it ensures that USB debugging and other adb commands cannot be executed unless you're able to unlock the device and acknowledge the dialog. This requires that you have adb version 1.0.31 (available with SDK Platform-tools r16.0.1 and higher) in order to debug on a device running Android 4.2.2 or higher.

## Syntax

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>


If there's only one emulator running or only one device connected, the adb command is sent to that device by default. If multiple emulators are running and/or multiple devices are attached, you need to use the -d-e, or -s option to specify the target device to which the command should be directed.

## Commands

The table below lists all of the supported adb commands and explains their meaning and usage.

Table 1. Available adb commands

Category Command Description Comments
Target Device -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"). See Directing Commands to a Specific Emulator/Device Instance.
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 dumpsysdumpstate, andlogcat 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 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 exampledev:/dev/omap_csmi_ttyl.
• [parm]... — zero or more PPP/PPPD options, such asdefaultroutelocal,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 not cause 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.

## 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 must specify a target instance when issuing adb commands. To do 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 devicescommand to obtain the serial numbers of running emulator/device instances. For example:

adb -s emulator-5556 install helloWorld.apk

Note that, if you issue a command without specifying a target emulator/device instance while multiple devices are available, adb generates an error.

If you have multiple devices available (hardware or emulated), but only one is an emulator, simply use the -e option to send commands to the emulator. Likewise if there's multiple devices but only one hardware device attached, use the -doption to send commands to the hardware device.

## 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. Unlike theinstall 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 (and its sub-directories) from the emulator or device, use

adb pull <remote> <local>

To copy a file or directory (and its sub-directories) 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). For example:

adb push foo.txt /sdcard/foo.txt

## Issuing Shell Commands

Adb provides a Unix shell that you can use to run a variety of commands on an emulator or connected device. The command binaries are stored in the file system of the emulator or device, at /system/bin/...

Two of the most common command tools are activity manager (am) and package manager (pm).

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 <shell_command>

Or enter a remote shell on an emulator/device like this:

adb [-d|-e|-s <serialNumber>] shell

When you are ready to exit the remote shell, press CTRL+D or type exit.

### Using activity manager (am)

Within an adb shell, you can issue commands with the activity manager (am) tool to perform various system actions, such as start an activity, force-stop a process, broadcast an intent, modify the device screen properties, and more. While in a shell, the syntax is:

am <command>


You can also issue an activity manager command directly from adb without entering a remote shell. For example:

adb shell am start -a android.intent.action.VIEW


Table 2. Available activity manager commands

Command Description
start [options] <INTENT> Start an Activity specified by <INTENT>.

Options are:

• -D: Enable debugging.
• -W: Wait for launch to complete.
• --start-profiler <FILE>: Start profiler and send results to<FILE>.
• -P <FILE>: Like --start-profiler, but profiling stops when the app goes idle.
• -R: Repeat the activity launch <COUNT> times. Prior to each repeat, the top activity will be finished.
• -S: Force stop the target app before starting the activity.
• --opengl-trace: Enable tracing of OpenGL functions.
• --user <USER_ID> | current: Specify which user to run as; if not specified, then run as the current user.
startservice [options] <INTENT> Start the Service specified by <INTENT>.

Options are:

• --user <USER_ID> | current: Specify which user to run as; if not specified, then run as the current user.
force-stop <PACKAGE> Force stop everything associated with <PACKAGE> (the app's package name).
kill [options] <PACKAGE> Kill all processes associated with <PACKAGE> (the app's package name). This command kills only processes that are safe to kill and that will not impact the user experience.

Options are:

• --user <USER_ID> | all | current: Specify user whose processes to kill; all users if not specified.
kill-all Kill all background processes.
broadcast [options] <INTENT> Issue a broadcast intent.

Options are:

• [--user <USER_ID> | all | current]: Specify which user to send to; if not specified then send to all users.
instrument [options] <COMPONENT> Start monitoring with an Instrumentation instance. Typically the target <COMPONENT> is the form<TEST_PACKAGE>/<RUNNER_CLASS>.

Options are:

• -r: Print raw results (otherwise decode<REPORT_KEY_STREAMRESULT>). Use with [-e perf true] to generate raw output for performance measurements.
• -e <NAME> <VALUE>: Set argument <NAME> to <VALUE>. For test runners a common form is -e <testrunner_flag> <value>[,<value>...].
• -p <FILE>: Write profiling data to <FILE>.
• -w: Wait for instrumentation to finish before returning. Required for test runners.
• --no-window-animation: Turn off window animations while running.
• --user <USER_ID> | current: Specify which user instrumentation runs in; current user if not specified.
profile start <PROCESS> <FILE> Start profiler on <PROCESS>, write results to <FILE>.
profile stop <PROCESS> Stop profiler on <PROCESS>.
dumpheap [options] <PROCESS> <FILE> Dump the heap of <PROCESS>, write to <FILE>.

Options are:

• --user [<USER_ID>|current]: When supplying a process name, specify user of process to dump; uses current user if not specified.
• -n: Dump native heap instead of managed heap.
set-debug-app [options] <PACKAGE> Set application <PACKAGE> to debug.

Options are:

• -w: Wait for debugger when application starts.
• --persistent: Retain this value.
clear-debug-app Clear the package previous set for debugging with set-debug-app.
monitor [options] Start monitoring for crashes or ANRs.

Options are:

• --gdb: Start gdbserv on the given port at crash/ANR.
screen-compat [on|off] <PACKAGE> Control screen compatibility mode of <PACKAGE>.

display-size [reset|<WxH>] Override emulator/device display size. This command is helpful for testing your app across different screen sizes by mimicking a small screen resolution using a device with a large screen, and vice versa.

Example:
am display-size 1280x800

display-density <dpi> Override emulator/device display density. This command is helpful for testing your app across different screen densities on high-density screen environment using a low density screen, and vice versa.

Example:
am display-density 480

to-uri <INTENT> Print the given intent specification as a URI.
to-intent-uri <INTENT> Print the given intent specification as an intent: URI.

### Using package manager (pm)

Within an adb shell, you can issue commands with the package manager (pm) tool to perform actions and queries on application packages installed on the device. While in a shell, the syntax is:

pm <command>


You can also issue a package manager command directly from adb without entering a remote shell. For example:

adb shell pm uninstall com.example.MyApp


Table 3. Available package manager commands.

Command Description
list packages [options] <FILTER> Prints all packages, optionally only those whose package name contains the text in <FILTER>.

Options:

• -f: See their associated file.
• -d: Filter to only show disabled packages.
• -e: Filter to only show enabled packages.
• -s: Filter to only show system packages.
• -3: Filter to only show third party packages.
• -i: See the installer for the packages.
• -u: Also include uninstalled packages.
• --user <USER_ID>: The user space to query.
list permission-groups Prints all known permission groups.
list permissions [options] <GROUP> Prints all known permissions, optionally only those in<GROUP>.

Options:

• -g: Organize by group.
• -f: Print all information.
• -s: Short summary.
• -d: Only list dangerous permissions.
• -u: List only the permissions users will see.
list instrumentation List all test packages.

Options:

• -f: List the APK file for the test package.
• <TARGET_PACKAGE>: List test packages for only this app.
list features Prints all features of the system.
list libraries Prints all the libraries supported by the current device.
list users Prints all users on the system.
path <PACKAGE> Print the path to the APK of the given <PACKAGE>.
install [options] <PATH> Installs a package (specified by <PATH>) to the system.

Options:

• -l: Install the package with forward lock.
• -r: Reinstall an exisiting app, keeping its data.
• -t: Allow test APKs to be installed.
• -i <INSTALLER_PACKAGE_NAME>: Specify the installer package name.
• -s: Install package on the shared mass storage (such as sdcard).
• -f: Install package on the internal system memory.
• -d: Allow version code downgrade.
uninstall [options] <PACKAGE> Removes a package from the system.

Options:

• -k: Keep the data and cache directories around after package removal.
clear <PACKAGE> Deletes all data associated with a package.
enable <PACKAGE_OR_COMPONENT> Enable the given package or component (written as "package/class").
disable <PACKAGE_OR_COMPONENT> Disable the given package or component (written as "package/class").
disable-user [options] <PACKAGE_OR_COMPONENT>

Options:

• --user <USER_ID>: The user to disable.
grant <PACKAGE_PERMISSION> Grant permissions to applications. Only optional permissions the application has declared can be granted.
revoke <PACKAGE_PERMISSION> Revoke permissions to applications. Only optional permissions the application has declared can be revoked.
set-install-location <LOCATION> Changes the default install location. Location values:
• 0: Auto—Let system decide the best location.
• 1: Internal—install on internal device storage.
• 2: External—install on external media.

Note: This is only intended for debugging; using this can cause applications to break and other undesireable behavior.

get-install-location Returns the current install location. Return values:
• 0 [auto]: Lets system decide the best location
• 1 [internal]: Installs on internal device storage
• 2 [external]: Installs on external media
set-permission-enforced <PERMISSION> [true|false] Specifies whether the given permission should be enforced.
trim-caches <DESIRED_FREE_SPACE> Trim cache files to reach the given free space.
create-user <USER_NAME> Create a new user with the given <USER_NAME>, printing the new user identifier of the user.
remove-user <USER_ID> Remove the user with the given <USER_IDENTIFIER>, deleting all data associated with that user
get-max-users Prints the maximum number of users supported by the device.

### 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 thesqlite3 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
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 launches your application and sends 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 Monkeydocumentation page.

### Other shell commands

For a list of all the available shell programs, use the following command:

adb shell ls /system/bin

Help is available for most of the commands.

Table 4 lists some of the more common adb shell commands.

Table 4. Some other adb shell 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 system and app 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

adb logcat

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 command. You can then restart the server by issuing any other adb command.

# 1.   概述

Android Debug Bridge (adb) 是一个android开发人员必会的多功能的调试工具，如它的名字一样，它在开发者和目标机器之间，架起了一座bridge。

DDMS：Dalvik Debug Monitor Service

Jdwp： Java Debug Wire Protocol

### 2.2.1. 启动流程

int main(int argc, char **argv)

{

return adb_commandline(argc - 1, argv + 1); / /运行PC端，用于命令发送

#else

if((argc > 1) && (!strcmp(argv[1],"recovery"))) {

adb_device_banner = "recovery"; // recover模式

recovery_mode = 1;

}

start_device_log();

#endif

}

## 2.3.   adb server

b，实现PC与设备/模拟器之间的数据拷贝。

## 2.4.   adb client

c、server查找当前连接的emulator/device

d、server接收到来自client请求

e、server处理请求，将本地处理不了的请求发给emulator/device

h、server讲结果发回给client

如下图：

Adb server 和 client 连接流程

## 2.5.   DDMS

DDMS 的全称是Dalvik Debug Monitor Service。DDMS为IDE和Emultor(or GPhone)架起来了一座桥梁。Developer可以通过DDMS看到目标机器上运行的进程/线程状态：可以让Eclipse程序连接到开发机上运行；可以看进程的heap信息、logcat信息、进程分配内存情况；为测试设备截屏，广播状态信息、模拟电话呼叫、接收SMS、虚拟地理坐标等等。

DDMS 的工作原理：

DDMS监听第一个终端App进程的端口为8600，APP进程将分配8601，如果有更多终端或者更多APP进程将按照这个顺序依次类推。DDMS通过8700端口（”base port”）接收所有终端的指令。

DDMS选项卡：

（1）Device选项卡

Device中罗列了Emulator中所有的进程，选项卡右上角那一排按钮分别为：调试进程、更新进程、更新进程堆栈信息、停止某个进程，最后一个图片按钮是抓取Emulator目前的屏幕。当你选中某个进程，并按下调试进程按钮时，如果eclipse中有这个进程的代码，那就可以进行源代码级别的调试。有点像gdb attach。图片抓取按钮可以把当前android的显示桌面抓到你的机器上，也是非常有用。

（3）Heap选项卡

（4）File Explorer选项卡

（5）Emulator Control选项卡

## 2.6.   Jdwp

jdwp(java debug wire protocol)是dalvik VM的一个线程，可以建立在adb（usb连接）或者tcp/ip（socket）基础上，与DDMS或debugger进行通信。

dalvik/vm/jdwp

frameworks/base/core/jni

java虚拟机初始化后，或者每次“zygote fork”出一个新进程时，会启动jdwp线程。

# 3.   ADB 通信

1、 成功，回复四字节串“OKAY”，后面跟的内容根据不同的命令而不同。

2、 失败，回复四字节串“FAIL”，然后跟四字节的十六进制长度，以及失败原因。

3、 对于host:version，回复4个字节的十六进制字串，代表server的内部版本号。

### 3.2.1. Transport

1、 USB transports。通过USB方式和物理设备通信。

2、 Local transports。通过本机的TCP连接方式和模拟器通信。

transport-usb

used for switching transport to the only USB transport

transport-local

used for switching transport to the only local transport

transport-any

used for switching transport to the only transport

 property_get("service.adb.tcp.port", value, ""); if (!value[0])  property_get("persist.adb.tcp.port", value, ""); if (sscanf(value, "%d", &port) == 1 && port > 0) {  // listen on TCP port specified by service.adb.tcp.port property  local_init(port); } else if (access("/dev/android_adb", F_OK) == 0) {  // listen on USB  usb_init(); } else {  // listen on default port  local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT); }

3，device和PC必须在同一网段内(能互相ping通)。

### 3.2.2. 协议

struct message {

unsigned command;           // command identifier constant

unsigned arg0;                // remote file descriptor

unsigned arg1;                // local file descriptor

unsigned data_length;      // payload length

unsigned data_crc32;       // checksum of data payload

unsigned magic;              // command ^ 0xffffffff

};

struct apacket

{

apacket *next;

unsigned len;

unsigned char *ptr;

amessage msg;

};

（标识符"local-id" 和 "remote-id"是相对而言，是对于消息的收发角色而定）

CONNECT(version, maxdata, "system-identity-string")

OPEN(local-id, 0, "destination")

WRITE(0, remote-id, "data")

CLOSE(local-id, remote-id, "")

SYNC(online, sequence, "")

--- amessage command 类型：（代码见：adb.h）--

#define A_SYNC 0x434e5953

#define A_CNXN 0x4e584e43

#define A_OPEN 0x4e45504f

#define A_OKAY 0x59414b4f

#define A_CLSE 0x45534c43

#define A_WRTE 0x45545257

A_SYNC

A_CNXN:send CNXN SIG to device/emulator after receive SYNC

A_OPEN: open local service socket

A_CLSE: close socket

A_WRTE: write to remote socket

adb [-d|-e|-s <serialNumber>] <command>

offline — 未连接或未响应

[serialNumber] [state]

$adb devices List of devices attached emulator-5554 device emulator-5556 device emulator-5558 device 如果没有模拟器或物理设备在运行，该状态返回的是no device。 操作指定的模拟器或物理设备 如果有多个模拟器或手机正在运行，当使用adb命令的时候就需要指定目标设备，这可以通过使用-s选项参数实现，用法是： adb -s <serialNumber> <command> 即可以在adb命令中使用序列号指定特定的目标，前文已经提到的devices命令可以实现查询设备的序列号信息。 例如： adb -s emulator-5556 install helloWorld.apk 需要注意的是，如果使用了-s而没有指定设备的话，adb会报错。 安装应用程序 可以使用adb从开发用电脑中复制应用程序并且安装到模拟器或手机上，使用install命令即可，在这个命令中，必须指定待安装的.apk文件的路径： adb install <path_to_apk> 如果使用了安装有ADT插件的Eclipse开发环境，就不需要直接使用adb或aapt命令来安装应用程序了，ADT插件可以自动完成这些操作。 关于创建可安装的应用的更多信息，请参见Android Asset Packaging Tool (aapt). 转发端口 可以使用forward 命令转发端口 — 将特定端口上的请求转发到模拟器或物理设备的不同的端口上。下例是从6100端口转到7100端口： adb forward tcp:6100 tcp:7100 也可以使用UNIX命名的socket标识： adb forward tcp:6100 local:logd 在TCP网络编程中，Client的Socket(C)如果调用Connect()成功，就说明已经和Server端的Socket(S)连接上，可以通讯了。但是如果使用adb forward做端口映射，就不一样了。端口映射的实质是，让ADB-server作为一个switcher转发ADB-client的数据包，送给 adbd，adbd再发给设备端的对应端口。因此一旦建立了映射，就相当于ADB-server开始监听这个目标端口。而此时如果有C去尝试 Connect这个端口，是一定会成功的，因为与C连接的是ADB-server，而非真正的设备上的目标程序。这就出现了，即使Connect()成功，却完全无法知道究竟是否成功连接到S。 因此，判断真正连接成功的方法，只有轮询收发握手数据包。程序中约定好事先做个交互：C发送一个数据包，等待S回复;C如果收到了S的回复包，说明连通;如果接收超时，则认为没有连通。在没有连通的情况下，需要重新建立Socket，并Connect()，然后再尝试握手。 与模拟器或手机传输文件 可以使用adb的 pull 和 push 命令从模拟器或物理设备中复制文件，或者将文件复制到模拟器或物理设备中。与 install 命令不同，它仅能复制.apk文件到特定的位置， pull 和 push 命令可以复制任意文件夹和文件到模拟器或物理设备的任何位置。 从模拟器或手机中复制一个文件或文件夹（递归的）使用： adb pull <remote> <local> 复制一个文件或文件夹（递归的）到模拟器或物理设备中使用： adb push <local> <remote> 在这个命令中<local>和<remote>引用的是文件或文件夹的路径，在开发用电脑上的是local，在模拟器或物理设备上的是remote。 例如： adb push foo.txt /sdcard/foo.txt adb命令列表 下表列出了所有adb支持的命令及其说明：  类别 命令 说明 备注 可选项 -d 命令仅对USB设备有效 如果有多个USB设备就会返回错误 -e 命令仅对运行中的模拟器有效 如果有多个运行中的模拟器就会返回错误 -s 命令仅对adb关联的特定序列号的模拟器或手机有效(例如 "emulator-5556"). 如果不指定设备就会返回错误 一般项 devices 输出所有关联的模拟器或手机设备列表 参见 Querying for Emulator/Device Instances以获得更多信息。 help 输出adb支持的命令 version 输出adb的版本号 调试项 logcat [ ## 5.2. 执行Shell命令 Adb提供了shell来在模拟器或物理设备上运行各种各样的命令，这些命令的二进制形式存在于这个路径中： /system/bin/... 无论是否进入adb远程shell，都可以使用 shell 命令来执。 在未进入远程shell的情况下可以按下述格式执行单条命令： adb [-d|-e|-s {<serialNumber>}] shell <shellCommand> 启动远程shell使用下面的格式： adb [-d|-e|-s {<serialNumber>}] shell 退出远程shell时使用CTRL+D 或 exit 终止会话。 从远程shell检查sqlite3 数据库 通过远程shell，可以使用sqlite3命令行程序来管理由应用程序创建的SQLite数据库。 sqlite3 工具包含很多有用的命令，例如 .dump 用于输出表格的内容，.schema 用于为已经存在的表输出 SQL CREATE 语句。 并且该工具也提供了联机执行SQLite命令的能力。 使用 sqlite3时，向前文描述的那样进入模拟器的远程shell，然后使用sqlite3 命令。也可以在调用 sqlite3时指定数据库的全路径。SQLite3数据库存储在/data/data/<package_name>/databases/路径下。 示例:$ adb -s emulator-5554 shell

SQLite version 3.3.12

Enter ".help" for instructions

.... enter commands, then quit...

sqlite> .exit

一旦运行了 sqlite3，就可以使用 sqlite3 命令，退出并返回远程shell可以使用 exit 或 CTRL+D。

Monkey是运行于模拟器或手机上的一个程序，通过生成伪随机的大量的系统级的用户事件流来模拟操作，包括单击、触摸、手势等。从而为正在开发中的应用程序通过随机响应进行压力测试。

最简单使用monkey的方式是通过下面的命令行，它可以运行指定的应用程序并向其发送500个伪随机事件。

$adb shell monkey -v -p your.package.name 500 关于monkey更多的选项及详细信息，请参见UI/Application Exerciser Monkey 还有一个monkeyrunner。monkeyrunner工具提供了一个API，使用此API写出的程序可以在Android代码之外控制Android设备和模拟器。具体可见：http://developer.android.com/guide/developing/tools/monkeyrunner_concepts.html 其他Shell命令 下表列出了很多有效的adb shell命令，完整的列表可以通过启动模拟器并且使用adb –help命令获取。 adb shell ls /system/bin 帮助对于大部分命令是有效的。  Shell 命令 描述 备注 dumpsys 在屏幕上显示系统数据 The Dalvik Debug Monitor Service(DDMS) 工具提供了更易于使用的智能的调试环境。 dumpstate 将状态输出到文件 logcat [ ## 5.3. 使用logcat查看日志 Android日志系统提供了从众多应用程序和系统程序中收集和查看调试信息的机制，这些信息被收集到一系统循环缓冲区中，可以 logcat 命令查看和过滤。 使用 logcat 命令 查看和跟踪系统日志缓冲区的命令logcat的一般用法是： [adb] logcat [<option>] ... [<filter-spec>] ... 下文介绍过滤器和命令选项，详细内容可参见Listing of logcat Command Options 可以在开发机中通过远程shell的方式使用logcat命令查看日志输出：$ adb logcat

# logcat

每一条日志消息都有一个标记和优先级与其关联。

V — 明细 (最低优先级)

D — 调试

I — 信息

W — 警告

E — 错误

F — 严重错误

S — 无记载 (最高优先级，没有什么会被记载)

I/ActivityManager(  585): Starting activity: Intent { action=android.intent.action...}

adb logcat ActivityManager:I MyApp:D *:S

export ANDROID_LOG_TAGS="ActivityManager:I MyApp:D *:S"

日志消息在标记和优先级之外还有很多元数据字段，这些字段可以通过修改输出格式来控制输出结果， -v 选项加上下面列出的内容可以控制输出字段：

brief — 显示优先级/标记和原始进程的PID (默认格式)

process — 仅显示进程PID

tag — 仅显示优先级/标记

raw — 显示原始的日志信息，没有其他的元数据字段

time — 显示日期，调用时间，优先级/标记，PID

long —显示所有的元数据字段并且用空行分隔消息内容

[adb] logcat [-v <format>]

Viewing Alternative Log Buffers

Android日志系统为日志消息保持了多个循环缓冲区，而且不是所有的消息都被发送到默认缓冲区，要想查看这些附加的缓冲区，可以使用-b 选项，以下是可以指定的缓冲区：

events — 查看事件相关的消息

main — 查看主缓冲区 (默认缓冲区)

-b 选项的用法：

[adb] logcat [-b <buffer>]

要想使用这种方式获得输出，需要停止运行中的模拟器或手机，然后使用命令 setprop 来允许输出重定位，示例如下：

$adb shell stop$ adb shell setprop log.redirect-stdio true

\$ adb shell start

Logcat命令选项列表

 选项 描述 -b  加载不同的缓冲区日志，例如 event 或radio。main 缓冲区是默认项，参见Viewing Alternative Log Buffers. -c 清空（刷新）所有的日志并且退出 -d 在屏幕上输出日志并退出 -f 将日志输出到文件，默认输出是stdout. -g 输出日志的大小 -n 设置最大的循环数据，默认是4，需要-r选项 -r 循环日志文件，默认是16，需要 -f 选项 -s 设置默认的过滤器为无输出 -v 设置输出格式，默认的是brief，支持的格式列表参见Controlling Log Output Format.

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客