IoTGateway/BSP/Android/Gettingstarted/ADB for development APK

From ESS-WIKI
Revision as of 08:38, 25 January 2017 by Liszt.kao (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Android Debug Bridge

In this document

  1. How adb works
  2. Enable adb debugging on your device
  3. Connect to a device over Wi-Fi
  4. Query for devices
  5. Send commands to a specific device
  6. Install an app
  7. Set up port forwarding
  8. Copy files to/from a device
  9. Stop the adb server
  10. adb commands reference
  11. Issue shell commands
    1. Call activity manager (am)
    2. Call package manager (pm)
    3. Take a screenshot
    4. Record a video
    5. Read ART profiles for apps
    6. Other shell commands

Android Debug Bridge (adb) is a versatile command line tool that lets you communicate with an emulator instance or connected Android device. It facilitates a variety of device actions, such as installing and debugging apps, and it provides access a Unix shell that you can use to run a variety of commands on an emulator or connected device. It is a client-server program that includes three components:

  • A client, which sends commands. The client runs on your development machine. You can invoke a client from a command-line terminal by issuing an adb command.
  • A daemon, which runs commands on a device. The daemon runs as a background process on each emulator or device instance.
  • A server, which manages communication between the client and the daemon. The server runs as a background process on your development machine.

adb is included in the Android SDK Platform-Tools package. You can download this package with the SDK Manager, which installs it at android_sdk/platform-tools/. Or if you want the standalone Android SDK Platform-Tools package, you can download it here.

How adb works

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

Enable adb debugging on your device

To use adb with a device connected over USB, you must enable USB debugging in the device system settings, under Developer options.

On Android 4.2 and higher, the Developer options screen is hidden by default. To make it visible, go to Settings > About phone and tap Build numberseven times. Return to the previous screen to find Developer options at the bottom.

On some devices, the Developer options screen may be located or named differently.

You can now connect your device with USB. You can verify that your device is connected by executing adb devices from the android_sdk/platform-tools/ directory. If connected, you'll see the device name listed as a "device."

Note: When you connect a device running Android 4.2.2 or higher, 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.

For more information about connecting to a device over USB, read Run Apps on a Hardware Device.

Connect to a device over Wi-Fi

adb is usually used over USB. However, it is also possible to use over Wi-Fi, as described here.

Connect your Android device and adb host computer to a common Wi-Fi network accessible to both. Beware that not all access points are suitable; you may need to use an access point whose firewall is configured properly to support adb.

Note: If you are attempting to connect to an Android Wear device, force it to connect to Wi-Fi by shutting off Bluetooth on the phone connected to it.

  1. Connect the device to the host computer with a USB cable.
  2. Set the target device to listen for a TCP/IP connection on port 5555.
    $ adb tcpip 5555
  1. Disconnect the USB cable from the target device.
  2. Find the IP address of the Android device. For example, on a Nexus device, you can find the IP address at Settings > About tablet (or About phone) > Status > IP address. Or, on an Android Wear device, you can find the IP address at Settings > Wi-Fi Settings > Advanced > IP address.
  3. Connect to the device, identifying it by IP address.
    $ adb connect <var>device_ip_address</var>
  1. Confirm that your host computer is connected to the target device:
    $ adb devices

List of devices attached <var>device_ip_address</var>:5555 device

You're now good to go!

If the adb connection is ever lost:

  1. Make sure that your host is still connected to the same Wi-Fi network your Android device is.
  2. Reconnect by executing the adb connect step again.
  3. Or if that doesn't work, reset your adb host:
    adb kill-server

Then start over from the beginning.

Query for devices

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-console-port. 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 is formatted like this:

List of devices attached
<var>serial_number</var> <var>state</var>

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

Send commands to a specific device

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 <var>serial_number</var> <var>command</var> 

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. 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 -d option to send commands to the hardware device.

Install an app

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 installcommand. With the command, you must specify the path to the APK file that you want to install:

adb install <var>path_to_apk</var>

For more information about how to create an APK file that you can install on an emulator/device instance, see Build and Run Your App.

Note that, if you are using Android Studio, you do not need to use adb (or aapt) directly to install your application on the emulator/device. Instead, Android Studio handles the packaging and installation of the application for you.

Set up port forwarding

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 

Copy files to/from a device

You can use the adb commands pull and push to copy files to and from an emulator/device instance. 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 (and its sub-directories) from the emulator or device, use

adb pull <var>remote</var> <var>local</var>

To copy a file or directory (and its sub-directories) to the emulator or device, use

adb push <var>local</var> <var>remote</var>

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

Stop the adb server

In some cases, you might need to terminate the adb server process and then restart it to resolve the problem (e.g., if adb does not respond to a command).

To stop the adb server, use the adb kill-server command. You can then restart the server by issuing any other adb command.

adb commands reference

You can issue adb commands from a command line on your development machine or from a script. The usage is:

adb [-d|-e|-s <var>serial_number</var>] <var>command</var>

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.

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 serial_number 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, 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 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:port_number
  • 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 defaultroutelocalnotty, 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 Issue shell commands for more information.
shell shell_command Issues a shell command in the target emulator/device instance and then exits the remote shell.

Issue shell commands

You can use the shell command to issue device commands through adb, 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 <var>serial_number</var>] shell <var>shell_command</var>

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

adb [-d|-e|-s <var>serial_number</var>] shell

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

The shell command binaries are stored in the file system of the emulator or device, at /system/bin/.

Call 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 <var>command</var>

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 [optionsintent Start an Activity specified by intent.

See the Specification for intent arguments.

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 count: 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 [optionsintent Start the Service specified by intent.

See the Specification for intent arguments.

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 [optionspackage 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 [optionsintent Issue a broadcast intent.

See the Specification for intent arguments.

Options are:

  • [--user user_id | all | current]: Specify which user to send to; if not specified then send to all users.
instrument [optionscomponent 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_flagvalue[,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 [optionsprocess 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 [optionspackage 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|widthxheight] 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.

See the Specification for intent arguments.

to-intent-uri intent Print the given intent specification as an intent: URI.

See the Specification for intent arguments.

Specification for intent arguments

For activity manager commands that take a intent argument, you can specify the intent with the following options:

Call 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 <var>command</var>

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 [optionsfilter 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 [optionsgroup 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 [options] 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 [optionspath Installs a package (specified by path) to the system.

Options:

  • -l: Install the package with forward lock.
  • -r: Reinstall an existing 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.
  • -g: Grant all permissions listed in the app manifest.
uninstall [optionspackage 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 [optionspackage_or_component

Options:

  • --user user_id: The user to disable.
grant package_name permission Grant a permission to an app. On devices running Android 6.0 (API level 23) and higher, may be any permission declared in the app manifest. On devices running Android 5.1 (API level 22) and lower, must be an optional permission defined by the app.
revoke package_name permission Revoke a permission from an app. On devices running Android 6.0 (API level 23) and higher, may be any permission declared in the app manifest. On devices running Android 5.1 (API level 22) and lower, must be an optional permission defined by the app.
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_id, deleting all data associated with that user
get-max-users Prints the maximum number of users supported by the device.

Take a screenshot

The screencap command is a shell utility for taking a screenshot of a device display. While in a shell, the syntax is:

screencap <var>filename</var>

To use the screencap from the command line, type the following:

$ adb shell screencap /sdcard/screen.png

Here's an example screenshot session, using the adb shell to capture the screenshot and the pull command to download the file from the device:


$ adb shell
shell@ $ screencap /sdcard/screen.png
shell@ $ exit
$ adb pull /sdcard/screen.png

Record a video

The screenrecord command is a shell utility for recording the display of devices running Android 4.4 (API level 19) and higher. The utility records screen activity to an MPEG-4 file.

Note: Audio is not recorded with the video file.

A developer can use this file to create promotional or training videos. While in a shell, the syntax is:

screenrecord [<var>options</var>] <var>filename</var>

To use screenrecord from the command line, type the following:

$ adb shell screenrecord /sdcard/demo.mp4

Stop the screen recording by pressing Control + C, otherwise the recording stops automatically at three minutes or the time limit set by --time-limit.

To begin recording your device screen, run the screenrecord command to record the video. Then, run the pull command to download the video from the device to the host computer. Here's an example recording session:


$ adb shell
shell@ $ screenrecord --verbose /sdcard/demo.mp4
(press Control + C to stop)
shell@ $ exit
$ adb pull /sdcard/demo.mp4

The screenrecord utility can record at any supported resolution and bit rate you request, while retaining the aspect ratio of the device display. The utility records at the native display resolution and orientation by default, with a maximum length of three minutes.

There are some known limitations of the screenrecord utility that you should be aware of when using it:

  • Some devices may not be able to record at their native display resolution. If you encounter problems with screen recording, try using a lower screen resolution.
  • Rotation of the screen during recording is not supported. If the screen does rotate during recording, some of the screen is cut off in the recording.

Table 4. screenrecord options

Options Description
--help Displays command syntax and options
--size widthxheight Sets the video size: 1280x720. The default value is the device's native display resolution (if supported), 1280x720 if not. For best results, use a size supported by your device's Advanced Video Coding (AVC) encoder.
--bit-rate rate Sets the video bit rate for the video, in megabits per second. The default value is 4Mbps. You can increase the bit rate to improve video quality, but doing so results in larger movie files. The following example sets the recording bit rate to 6Mbps:
screenrecord --bit-rate 6000000 /sdcard/demo.mp4
--time-limit time Sets the maximum recording time, in seconds. The default and maximum value is 180 (3 minutes).
--rotate Rotates the output 90 degrees. This feature is experimental.
--verbose Displays log information on the command-line screen. If you do not set this option, the utility does not display any information while running.

Read ART profiles for apps

Starting in Android 7.0 (API level 24) the Android Runtime (ART) collects execution profiles for installed apps, which are used to optimize app performance. You might want to examine the collected profiles to understand which methods are determined to be frequently executed and which classes are used during app startup.

To produce a text form of the profile information, use the command:

$ adb shell cmd package dump-profiles <var>package</var>

To retrieve the file produced, use:

$ adb pull /data/misc/profman/<var>package</var>.txt

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 5 lists some of the more common adb shell commands.

Table 5. Some other adb shell commands

Shell Command Description Comments
dumpsys Dumps system data to the screen. The Dalvik Debug Monitor Server (DDMS) tool offers an 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.  

<footer>

</footer>