Migrate to Studio

从 Eclipse 迁移至 Android Studio

本文内容

  1. Android Studio 基础知识
  2. 迁移先决条件
  3. 将项目导入 Android Studio
  4. 后续步骤

将项目迁移至 Android Studio 需要适应新的项目结构、构建系统和 IDE 功能。 为了简化迁移过程，Android Studio 提供了导入工具，您可以将现有代码快速移至 Android Studio 项目和基于 Gradle 的构建文件。

Android Studio 基础知识

在准备迁移至 Android Studio 时您需要了解以下关键区别。

项目和模块组织

Android Studio 基于 IntelliJ IDEA IDE。 如需了解 IDE 基础知识，例如导航、代码自动完成和键盘快捷键，请参阅探索 Android Studio。

Android Studio 不使用工作区，因此各个项目在单独的 Android Studio 窗口中打开。 Android Studio 将代码组织到项目中，其中包含从应用源代码到构建配置和测试代码等定义 Android 应用的所有信息。每个项目包含一个或多个模块，您可以将项目分成独立的功能单元。模块可独立构建、测试和调试。

如需了解有关 Android Studio 项目和模块的详细信息，请参阅项目概览。

基于 Gradle 的构建系统

Android Studio 的构建系统基于 Gradle，并使用以 Groovy 语法编写的构建配置文件，以便于扩展和自定义。

如需了解有关使用和配置 Gradle 的详细信息，请参阅配置构建。

依赖关系

在 Android Studio 中，库依赖关系使用依赖关系声明，对于具有 Maven 坐标的已知本地源代码和二进制库，则使用 Maven 依赖关系。如需了解详细信息，请参阅配置构建变体。

测试代码

通过使用 Eclipse ADT，可在不同的项目中编写仪器测试，并通过清单文件中的 <instrumentation> 元素进行集成。Android Studio 在项目的主源代码集中提供 androidTest/ 目录，因此您可以在同一项目视图中轻松添加和维护仪器测试代码。 Android Studio 在项目的主源代码集中还提供了 test/ 目录，用于本地 JVM 测试。

迁移先决条件

在将您的应用迁移到 Android Studio 前，请浏览以下步骤，确保您的项目已做好转换的准备，同时确认 Android Studio 中有您需要的工具配置：

在 Eclipse ADT 中：

  • 确保 Eclipse ADT 根目录包含 AndroidManifest.xml 文件。 此外，根目录必须包含 Eclipse 的 .project 和 .classpath 文件或 res/ 和 src/ 目录。
  • 构建您的项目，以确保导入时保存并包含了最新的工作区和项目更新。
  • 在需要导入的 project.properties 或.classpath 文件中注释掉对 Eclipse ADT 工作区库文件的任何引用。 您可以在导入后在 build.gradle 文件中添加这些引用。 如需了解详细信息，请参阅配置构建。
  • 记录工作区目录、路径变量和任何实际路径映射可能会有所帮助，这些内容可用于指定任何未解析的相对路径、路径变量和链接的资源引用。Android Studio 允许您在导入过程中手动指定任何未解析的路径。

在 Android Studio 中：

  • 如果您尚未安装，点击此处下载 Android Studio。 如果您已经安装了 Android Studio，请点击 Help > Check for Updates（在 Mac 上，点击 Android Studio > Check for Updates），验证其是否是最新的稳定版本。
  • 因为 Android Studio 无法迁移任何第三方 Eclipse ADT 插件，请记下您在 Eclipse 中使用的任何第三方插件。 您可以查看 Android Studio 中的相同功能，或在 IntelliJ Android Studio 插件存储库中搜索兼容的插件。 使用 File > Settings > Plugins 菜单选项管理 Android Studio 中的插件。
  • 如果您计划在防火墙后面运行 Android Studio，则必须为 Android Studio 和 SDK 管理器设置代理。 Android Studio 设置向导同步、第三方库访问、访问远程存储库、Gradle 初始化和同步以及 Android Studio 版本更新需要互联网连接。如需了解详细信息，请参阅代理设置。

将项目导入 Android Studio

您应根据现有 Eclipse ADT 项目的结构确定其导入方式：

  • 如果您在 Eclipse ADT 中有多个关联项目共享同一个工作区，请将第一个项目作为项目导入，然后添加随后的关联项目作为该项目中的模块。
  • 如果您的 Eclipse ADT 项目在同一个工作区中共享依赖关系，但并不关联，请将每个 Eclipse ADT 项目作为独立的项目逐个导入 Android Studio。在导入过程中 Android Studio 将在新创建的项目之间维持这些共享的依赖关系。

作为项目导入：

  1. 启动 Android Studio，并关闭任何打开的 Android Studio 项目。
  2. 在 Android Studio 菜单中点击 File > New > Import Project。
    • 或在“Welcome”屏幕中点击 Import project (Eclipse ADT, Gradle, etc.)。
  3. 选择包含 AndroidManifest.xml 文件的 Eclipse ADT 项目文件夹，并点击 Ok。

  4. 选择目标文件夹，并点击 Next。

  5. 选择导入选项，并点击 Finish。

  6. 导入过程中会提示您将任何库和项目依赖关系迁移到 Android Studio，并将依赖关系声明添加到 build.gradle 文件。如需了解有关此过程的详细信息，请参阅创建 Android 库。

    导入过程中还将用 Maven 依赖关系替换具有已知 Maven 坐标的任何已知源代码库、二进制库和 JAR 文件，因此您无需手动保留这些依赖关系。导入选项还允许您输入工作区目录和任何实际路径映射，以处理任何未解析的相对路径、路径变量和链接的资源引用。

  1. Android Studio 导入应用并显示项目导入摘要。 查看摘要，了解项目重组和导入过程的详细信息。

将项目从 Eclipse ADT 导入 Android Studio 后，Android Studio 中的每个应用模块文件夹都包含该模块的完整源代码集，包括 src/main/ 和src/androidTest/目录、资源、构建文件以及 Android 清单。在开始应用开发前，您应解决项目导入摘要中显示的所有问题，确保项目重组和导入过程成功完成。

作为模块导入：

  1. 启动 Android Studio，并打开想要添加模块的项目。
  2. 在 Android Studio 菜单中点击 File > New > Import Module。
  3. 选择包含 AndroidManifest.xml 文件的 Eclipse ADT 项目文件夹，并点击 Ok。
  4. 如果需要，可修改模块名称，并点击 Next。
  5. 导入过程中会提示您将任何库和项目依赖关系迁移到 Android Studio，并将依赖关系声明添加到 build.gradle 文件。如需了解有关迁移库和项目依赖关系的详细信息，请参阅创建 Android 库。导入过程中还将用 Maven 依赖关系替换具有已知 Maven 坐标的任何已知源代码库、二进制库和 JAR 文件，因此您无需手动保留这些依赖关系。导入选项还允许您输入工作区目录和任何实际路径映射，以处理任何未解析的相对路径、路径变量和链接的资源引用。
  6. 点击 Finish。

验证导入的项目

完成导入过程后，使用 Android Studio 的 Build 和 Run 菜单选项构建您的项目，并验证输出。若项目未正确构建，请检查以下设置：

  • 打开 SDK 管理器（点击 Android Studio 中的“Android SDK Manager”按钮或 Tools > Android > SDK Manager），验证您安装的工具版本是否匹配 Eclipse 项目的设置。Android Studio 从您导入的 Eclipse 项目继承 SDK 管理器和 JDK 设置。
  • 要验证其他 Android Studio 设置，请点击 File > Project Structure 并检查以下设置：
    • 在 SDK Location 项下，验证 Android Studio 是否可以访问正确的 SDK、NDK 和 JDK 位置和版本。
    • 在 Project 项下，验证 Gradle 版本、Android 插件版本和相关存储库。
    • 在 Modules 项下，验证应用和模块设置，例如签署配置和库依赖关系。
  • 如果您的项目依赖另一个项目，则确保在应用模块文件夹中的 build.gradle 文件中正确定义该依赖关系。如需了解有关定义依赖关系的详细信息，请参阅配置构建变体。

如果在检查这些设置后，在 Android Studio 中构建和运行项目时仍出现异常问题，请考虑修改 Eclipse ADT 项目并重新开始导入过程。

注： 将 Eclipse ADT 项目导入 Android Studio 将创建一个新的 Android Studio 项目，不会影响现有 Eclipse ADT 项目。

后续步骤

根据您的项目和工作流程，您可能想要阅读更多有关使用版本控制、管理依赖关系、签署和打包应用或配置和更新 Android Studio 的信息。

若要开始使用 Android Studio，请阅读探索 Android Studio。

配置版本控制

Android Studio 支持多个版本控制系统，包括 Git、GitHub、CVS、Mercurial、Subversion 和 Google Cloud Source Repositories。

在将您的应用导入 Android Studio 后，使用 Android Studio VCS 菜单选项启用对所需版本控制系统的 VCS 支持、创建存储库、导入新文件至版本控制以及执行其他版本控制操作：

  1. 在 Android Studio VCS 菜单中点击 Enable Version Control Integration。
  2. 从下拉菜单中选择要与项目根目录关联的版本控制系统，然后点击 OK。 此时，VCS 菜单将根据您选择的系统显示多个版本控制选项。

注： 您还可以使用 File > Settings > Version Control 菜单选项设置和修改版本控制设置。

如需了解有关使用版本控制的详细信息，请参阅 IntelliJ 版本控制参考。

Android 支持存储库和 Google Play 服务存储库

虽然 Eclipse ADT 使用 Android 支持库和 Google Play 服务库，但在导入过程中 Android Studio 会用 Android 支持存储库和 Google 存储库替换这些库，以便继续使用兼容的功能并支持新的 Android 功能。Android Studio 使用已知的 Maven 坐标将这些依赖关系添加为 Maven 依赖关系，因此不需要手动更新这些依赖关系。

在 Eclipse 中，要使用支持库，您必须针对想要使用的每个支持库在开发环境中修改项目的类路径依赖关系。在 Android Studio 中，无需将库源代码复制到您自己的项目中，您只需声明依赖关系，即可自动下载库并将其合并到您的项目中。 这包括在构建时自动合并到资源、清单条目、ProGuard 排除规则和自定义 Lint 规则。 如需了解有关依赖关系的详细信息，请参阅配置构建变体。

应用签署

如果您的应用在 Eclipse ADT 中使用调试证书，Android Studio 将继续引用该证书。 或者，调试配置使用 Android Studio 生成的一个调试密钥库和一个默认密钥，二者密码均已知，调试密钥库位于 $HOME/.android/debug.keystore 中。

当您从 Android Studio 运行或调试您的项目时，调试构建类型将自动使用此调试配置。在构建用于发布的应用时，Android Studio 会应用在 Eclipse ADT 中使用的发布证书。 如果在导入过程中未找到发布证书，则将发布签署配置添加到 build.gradle 文件，或使用 Build > Generate Signed APK 菜单选项打开 Generate Signed APK Wizard。如需了解签署应用的详细信息，请参阅签署您的应用。

调整 Android Studio 的最大堆内存

默认情况下，Android Studio 的最大堆内存为 1280MB。 如果您要处理较大的项目，或您的系统有大量 RAM 可用，您可以通过在 Android Studio 的 VM 选项中增加最大堆内存来提高性能。

如需了解有关配置 Android Studio 设置的详细信息，请参阅配置 Android Studio 和配置 Android Studio。

软件更新

Android Studio 与 Gradle 插件、构建工具和 SDK 工具分开更新。 您可以指定想要使用的 Android Studio 版本。

默认情况下，在有新稳定版本发布时 Android Studio 将自动更新，但您可以选择更频繁地进行更新，也可以接收预览版或测试版。

如需了解有关更新 Android Studio 以及使用预览版和测试版的详细信息，请参阅保持更新。

来源： https://developer.android.com/studio/intro/migrate.html


Configure the IDE

配置 Android Studio

本文内容

  1. 代理设置

Android Studio 提供诸多向导和模板，可用于验证系统要求（例如 Java 开发工具包 (JDK) 和可用内存）和配置默认设置（例如优化的默认 Android Virtual Device (AVD) 模拟和更新的系统映像）。本文件介绍了您可能想要使用的其他配置设置，以便您自定义对 Android Studio 的使用方式。

有关模拟器和设备设置与使用的特定文档，请参阅管理虚拟设备、使用硬件设备和 OEM USB 驱动程序。

代理设置

代理作为 HTTP 客户端和 Web 服务器之间的中间连接点，可提高互联网连接的安全性和隐私性。

要支持在防火墙后面运行 Android Studio，需要为 Android Studio IDE 和 SDK 管理器设置代理。使用 Android Studio IDE HTTP 代理设置页面设置 Android Studio 的 HTTP 代理。SDK 管理器有单独的 HTTP 代理设置页面。

若从命令行或在未安装 Android Studio 的设备（例如持续性集成服务器）上运行 Android Gradle 插件，则应在 Gradle 构建文件中设置代理。

注：在初始安装 Android Studio 程序包后，可以通过互联网访问或脱机运行 Android Studio。但是，Android Studio 设置向导同步、第三方库访问、访问远程存储库、Gradle 初始化和同步以及 Android Studio 版本更新需要互联网连接。

设置 Android Studio 代理

Android Studio 支持 HTTP 代理设置，因此您可以在防火墙后面或使用安全网络运行 Android Studio。要在 Android Studio 中设置 HTTP 代理，请执行以下操作：

  1. 在主菜单中选择 File > Settings > Appearance & Behavior -- System Settings -- HTTP Proxy。
  2. 在 Android Studio 中，打开“IDE Settings”对话框。
    • 在 Windows 和 Linux 系统中，选择 File > Settings > IDE Setting -- HTTP Proxy。
    • 在 Mac 系统中，选择 Android Studio > Preferences > IDE Setting -- HTTP Proxy。
    此时将出现 HTTP Proxy 页面。
  3. 选择 auto-detection 使用自动配置 URL 配置代理设置，或选择 manual 手动输入每一项设置。有关这些设置的详细说明，请参阅 HTTP 代理。
  4. 点击 Apply 以启用代理设置。

Android Gradle 插件 HTTP 代理设置

若从命令行或在未安装 Android Studio 的设备上运行 Android 插件，则应在 Gradle 构建文件中设置 Android Gradle 插件代理。

对于应用程序特定的 HTTP 代理设置，请根据各应用程序模块的要求在 build.gradle 文件中设置代理。

apply plugin: 'com.android.application'

android {
    ...

    defaultConfig {
        ...
        systemProp.http.proxyHost=proxy.company.com
        systemProp.http.proxyPort=443
        systemProp.http.proxyUser=userid
        systemProp.http.proxyPassword=password
        systemProp.http.auth.ntlm.domain=domain
    }
    ...
}

对于整个项目的 HTTP 代理设置，应在 gradle/gradle.properties 文件中设置代理。

# Project-wide Gradle settings.
...

systemProp.http.proxyHost=proxy.company.com
systemProp.http.proxyPort=443
systemProp.http.proxyUser=username
systemProp.http.proxyPassword=password
systemProp.http.auth.ntlm.domain=domain

systemProp.https.proxyHost=proxy.company.com
systemProp.https.proxyPort=443
systemProp.https.proxyUser=username
systemProp.https.proxyPassword=password
systemProp.https.auth.ntlm.domain=domain

...

有关使用 Gradle 属性进行代理设置的信息，请参阅 Gradle 用户指南。

注：在使用 Android Studio 时，Android Studio IDE HTTP 代理设置页面中的设置将重写 gradle.properties 文件中的 HTTP 代理设置。

SDK 管理器 HTTP 代理设置

SDK 管理器代理设置可启用代理互联网访问，以便从 SDK 管理器软件包进行 Android 软件包和库更新。

要设置 SDK 管理器的代理互联网访问，请启动 SDK 管理器并打开 SDK 管理器页面。

  • 在 Windows 系统中，从菜单栏选择 Tools > Options。
  • 在 Mac 和 Linux 系统中，从系统菜单栏选择 Tools > Options。

此时出现 Android SDK Manager 页面。输入设置并点击 Apply。

来源： https://developer.android.com/studio/intro/studio-config.html


Keyboard Shortcuts

Android Studio includes keyboard shortcuts for many common actions. Table 1 shows the default keyboard shortcuts by operating system.

Note: In addition to the default keymaps in table 1 below, you can select from a number of preset keymaps or create a custom keymap. For more about customizing your keyboard shortcuts, see Configure Custom Keymaps, below.

Table 1. Default keyboard shortcuts for Windows/Linux and Mac operating systems.

Description | Windows/Linux | Mac
General
Save all | Control + S | Command + S
Synchronize | Control + Alt + Y | Command + Option + Y
Maximize/minimize editor | Control + Shift + F12 | Control + Command + F12
Add to favorites | Alt + Shift + F | Option + Shift + F
Inspect current file with current profile | Alt + Shift + I | Option + Shift + I
Quick switch scheme | Control + ` (backquote) | Control + ` (backquote)
Open settings dialogue | Control + Alt + S | Command + , (comma)
Open project structure dialog | Control + Alt + Shift + S | Command + ; (semicolon)
Switch between tabs and tool window | Control + Tab | Control + Tab
Navigating and Searching Within Studio
Search everything (including code and menus) | Press Shift twice | Press Shift twice
Find | Control + F | Command + F
Find next | F3 | Command + G
Find previous | Shift + F3 | Command + Shift + G
Replace | Control + R | Command + R
Find action | Control + Shift + A | Command + Shift + A
Search by symbol name | Control + Alt + Shift + N | Command + Option + O
Find class | Control + N | Command + O
Find file (instead of class) | Control + Shift + N | Command + Shift + O
Find in path | Control + Shift + F | Command + Shift + F
Open file structure pop-up | Control + F12 | Command + F12
Navigate between open editor tabs | Alt + Right/Left Arrow | Control + Right/Left Arrow
Jump to source | F4 / Control + Enter | F4 / Command + Down Arrow
Open current editor tab in new window | Shift + F4 | Shift + F4
Recently opened files pop-up | Control + E | Command + E
Recently edited files pop-up | Control + Shift + E | Command + Shift + E
Go to last edit location | Control + Shift + Backspace | Command + Shift + Backspace
Close active editor tab | Control + F4 | Command + W
Return to editor window from a tool window | Esc | Esc
Hide active or last active tool window | Shift + Esc | Shift + Esc
Go to line | Control + G | Command + L
Open type hierarchy | Control + H | Control + H
Open method hierarchy | Control + Shift + H | Command + Shift + H
Open call hierarchy | Control + Alt + H | Control + Option + H
Writing Code
Generate code (getters, setters, constructors, hashCode/equals, toString, new file, new class) | Alt + Insert | Command + N
Override methods | Control + O | Control + O
Implement methods | Control + I | Control + I
Surround with (if...else / try...catch / etc.) | Control + Alt + T | Command + Option + T
Delete line at caret | Control + Y | Command + Backspace
Collapse/expand current code block | Control + minus/plus | Command + minus/plus
Collapse/expand all code blocks | Control + Shift + minus/plus | Command + Shift + minus/plus
Duplicate current line or selection | Control + D | Command + D
Basic code completion | Control + Space | Control + Space
Smart code completion (filters the list of methods and variables by expected type) | Control + Shift + Space | Control + Shift + Space
Complete statement | Control + Shift + Enter | Command + Shift + Enter
Quick documentation lookup | Control + Q | Control + J
Show parameters for selected method | Control + P | Command + P
Go to declaration (directly) | Control + B or Control + Click | Command + B or Command + Click
Go to implementations | Control + Alt + B | Command + Alt + B
Go to super-method/super-class | Control + U | Command + U
Open quick definition lookup | Control + Shift + I | Command + Y
Toggle project tool window visibility | Alt + 1 | Command + 1
Toggle bookmark | F11 | F3
Toggle bookmark with mnemonic | Control + F11 | Option + F3
Comment/uncomment with line comment | Control + / | Command + /
Comment/uncomment with block comment | Control + Shift + / | Command + Shift + /
Select successively increasing code blocks | Control + W | Option + Up
Decrease current selection to previous state | Control + Shift + W | Option + Down
Move to code block start | Control + [ | Option + Command + [
Move to code block end | Control + ] | Option + Command + ]
Select to the code block start | Control + Shift + [ | Option + Command + Shift + [
Select to the code block end | Control + Shift + ] | Option + Command + Shift + ]
Delete to end of word | Control + Delete | Option + Delete
Delete to start of word | Control + Backspace | Option + Backspace
Optimize imports | Control + Alt + O | Control + Option + O
Project quick fix (show intention actions and quick fixes) | Alt + Enter | Option + Enter
Reformat code | Control + Alt + L | Command + Option + L
Auto-indent lines | Control + Alt + I | Control + Option + I
Indent/unindent lines | Tab/Shift + Tab | Tab/Shift + Tab
Smart line join | Control + Shift + J | Control + Shift + J
Smart line split | Control + Enter | Command + Enter
Start new line | Shift + Enter | Shift + Enter
Next/previous highlighted error | F2 / Shift + F2 | F2 / Shift + F2
Build and Run
Build | Control + F9 | Command + F9
Build and run | Shift + F10 | Control + R
Debugging
Debug | Shift + F9 | Control + D
Step over | F8 | F8
Step into | F7 | F7
Smart step into | Shift + F7 | Shift + F7
Step out | Shift + F8 | Shift + F8
Run to cursor | Alt + F9 | Option + F9
Evaluate expression | Alt + F8 | Option + F8
Resume program | F9 | Command + Option + R
Toggle breakpoint | Control + F8 | Command + F8
View breakpoints | Control + Shift + F8 | Command + Shift + F8
Refactoring
Copy | F5 | F5
Move | F6 | F6
Safe delete | Alt + Delete | Command + Delete
Rename | Shift + F6 | Shift + F6
Change signature | Control + F6 | Command + F6
Inline | Control + Alt + N | Command + Option + N
Extract method | Control + Alt + M | Command + Option + M
Extract variable | Control + Alt + V | Command + Option + V
Extract field | Control + Alt + F | Command + Option + F
Extract constant | Control + Alt + C | Command + Option + C
Extract parameter | Control + Alt + P | Command + Option + P
Version Control / Local History
Commit project to VCS | Control + K | Command + K
Update project from VCS | Control + T | Command + T
View recent changes | Alt + Shift + C | Option + Shift + C
Open VCS popup | Alt + ` (backquote) | Control + V

Configure Custom Keymaps

You can choose from a number of preset keymaps or modify a preset keymap to create a new custom keymap in the keymap settings for Android Studio.

To open the keymap settings, click File > Settings > Keymap (on Mac, File > Properties > Keymap).

Figure 1. The Android Studio keymap settings window.

  1. Keymaps dropdown: Delect the desired keymap from this menu to switch between preset keymaps.
  2. Actions list: Right click on an action to modify it. You can add additional keyboard shortcuts for the action, add mouse shortcuts to associate an action with a mouse click, or remove current shortcuts. If you are using a preset keymap, modifying an action’s shortcuts will automatically create a copy of the keymap and add your modifications to the copy.
  3. Copy button: Select a keymap from the dropdown menu to use as a starting point, and click Copy to create a new custom keymap. You can modify the keymap name and shortcuts.
  4. Reset button: Select a keymap from the dropdown menu and click Reset to revert it to its original configuration.
  5. Search box: Type here to search for a keyboard shortcut by the action name.
  6. Search by Shortcut: Click Find Actions by Shortcut and type a shortcut to search for actions by shortcut.
    来源： https://developer.android.com/studio/intro/keyboard-shortcuts.html


Update the IDE and Tools

更新 IDE 和 SDK 工具

本文内容

  1. 更新 IDE 和变更渠道
  2. 使用 SDK 管理器更新您的工具
    1. 推荐的软件包
    2. 编辑或添加 SDK 工具网站

安装 Android Studio 后，您可以通过自动更新和 Android SDK 管理器轻松更新 Android Studio IDE 和 Android SDK 工具。

更新 IDE 和变更渠道

若有可用的 IDE 更新，Android Studio 将通过小气泡对话框通知您，您也可以点击 Help > Check for Update（在 Mac 中，点击 Android Studio > Check for Updates）手动检查更新。

您可以通过以下发布渠道获取 Android Studio 更新：

  • Canary 版渠道：此渠道发布前沿版本，大约每周更新一次。虽然这些版本存在较多的错误，但已经过测试，我们希望为您提供抢先体验的机会，以便您尝试新功能和提供反馈。此渠道不推荐用于生产开发。
  • 开发版渠道：此渠道发布已通过所有内部测试的精选 Canary 版本。
  • 测试版渠道：此渠道发布基于稳定的 Canary 版本的候选版本，以便在进入稳定版渠道前获得反馈。
  • 稳定版渠道：官方稳定版本，可在 developer.android.com/studio 下载。

默认情况下，Android Studio 从稳定版渠道提供更新。如果您想要尝试其他版本的 Android Studio（统称为预览版渠道），您可以选择从其中一个渠道接收更新。

如需变更更新渠道，请执行以下操作：

  1. 点击 File > Settings（在 Mac 中，点击 Android Studio > Preferences），打开 Preferences 窗口。
  2. 在左侧面板中，点击 Appearance & Behavior > System Settings > Updates。
  3. 确保已选中 Automatically check for updates，然后从下拉列表中选择一个渠道（见图 1）。
  4. 点击 Apply 或 OK。

图 1.Android Studio 更新首选项

如果您想要在生产 Android 项目中仍然使用稳定版本的同时试用预览版渠道（Canary、开发或测试版），您可以从 tools.android.com 下载相应的预览版本，安全地安装另一个版本的 Android Studio。

使用 SDK 管理器更新您的工具

Android SDK 管理器提供 SDK 工具、平台和开发应用所需的其他组件。

要打开 SDK 管理器，请点击 Tools > Android > SDK Manager 或点击工具栏中的 SDK Manager [image] 。

已安装的软件包如有更新，其旁边的复选框中会显示短划线 [image] 。

  • 要更新项目或安装新项目，请点击复选框，其将显示钩形符号。
  • 如需卸载软件包，请点击以清除复选框。

待下载的更新在左侧列中以下载图标 [image] 表示。待执行的删除以红十字 [image] 表示。

要更新所选的软件包，请点击 Apply 或 OK，然后同意所有许可协议。

图 2.Android SDK 管理器

推荐的软件包

您应特别考虑 SDK Tools 选项卡中的以下工具：

Android SDK 构建工具
必备。包含构建 Android 应用的工具。请参阅 SDK 构建工具发行说明。
Android SDK 平台工具
必备。包含 Android 平台所需的各种工具，包括 adb 工具。
Android SDK 工具
必备。包含基本工具，例如 Android Emulator 和 ProGuard。请参阅 SDK 工具发行说明。
Android 支持存储库
推荐。包含支持库的本地 Maven 存储库，该存储库提供了一组丰富的 API，这些 API 兼容大多数版本的 Android。该工具是 Android Wear、Android TV 和 Google Cast 等产品的必备工具。如需了解详细信息，请阅读支持库。
Google 存储库
推荐。包含 Google 库的本地 Maven 存储库，该存储库可为您的应用提供各种功能和服务，包括 Firebase、Google 地图、游戏成就和排行榜等。

在 SDK Platforms 选项卡中，您还必须安装至少一个版本的 Android 平台。每个版本均提供多种不同的软件包。如需仅下载所需版本，请点击版本名称旁的复选框。

要查看各 Android 平台所有可用的软件包，请点击窗口底部的 Show Package Details。各版本的平台中均提供以下软件包：

Android SDK 平台
必备。您的开发环境中必须至少有一个平台，您方可编译应用。为了在最新设备上提供最佳用户体验，请使用最新版本的平台作为构建目标。您的应用仍然可以在旧版系统上运行，但您必须以最新版本为目标构建应用，以便在安装最新版本 Android 的设备上运行应用时能够使用新功能。
Intel 或 ARM 系统映像
推荐。运行 Android Emulator 需要系统映像。每个版本的平台均包含受支持的系统映像。您也可以在稍后从 AVD Manager 创建 Android Virtual Device (AVD) 时下载系统映像。根据开发计算机的处理器选择 Intel 或 ARM。

注：如果您计划使用 Google Play 服务的 API，则必须使用 Google API 系统映像。

以上列表并不详尽，您可以添加其他网站，以便从第三方网站下载更多软件包。

在某些情况下，SDK 软件包可能需要另一个工具的特定最低修订版。如果存在这种情况，SDK 管理器将发出警告通知您，并将依赖项添加到您的下载列表。

提示：您还可以自定义 build.gradle 文件，使每个项目均使用特定的构建链和编译选项。如需了解详细信息，请参阅配置 Gradle 构建。

编辑或添加 SDK 工具网站

要管理 Android Studio 检查 Android 工具和第三方工具更新的 SDK 网站，请点击 SDK Update Sites 选项卡。您可以添加其他提供自有工具的网站，然后从这些网站下载软件包。

例如，某个移动运营商或设备制造商可能会为其自有基于 Android 系统的设备提供额外的 API 库。要使用他们的库开发应用，您可以在 SDK Update Sites选项卡中将其 SDK 工具 URL 添加到 SDK 管理器，以安装他们的 Android SDK 软件包。

如果运营商或设备制造商在其网站上提供了 SDK 加载项存储库文件，请按照下列步骤将其网站添加到 Android SDK 管理器：

  1. 点击 SDK Update Sites 选项卡。
  2. 点击窗口底部的 Add [image] 。
  3. 输入第三方网站的名称和 URL，然后点击 OK。
  4. 确保已选中 Enabled 列中相应的复选框。
  5. 点击 Apply 或 OK。

该网站提供的所有 SDK 软件包都将视情况显示在 SDK Platforms 或 SDK Tools 选项卡中。

来源： https://developer.android.com/studio/intro/update.html


Developer Workflow Basics

The workflow to develop an app for Android is conceptually the same as other app platforms. However, to efficiently build a well-designed app for Android, you need some specialized tools. The following list provides an overview of the process to build an Android app and includes links to some Android Studio tools you should use during each phase of development.

  1. Set up your workspace

    This is the phase you probably already finished: Install Android Studio and create a project.

    For a walkthrough with Android Studio that teaches some Android development fundamentals, also check out the guide to Building Your First App.

  2. Write your app

    Now you can get to work. Android Studio includes a variety of tools and intelligence to help you work faster, write quality code, design a UI, and create resources for different device types. For more information about the tools and features available, see Write Your App.

  3. Build and run

    During this phase, you build your project into a debuggable APK package that you can install and run on the emulator or an Android-powered device. For more information about how to run your code, see Build and Run Your App.

    You can also begin customizing your build. For example, you can create build variantsthat produce different types of APKs from the same project, and shrink your code and resources to make your APK file smaller. For an introduction to customizing your build, see Configure Your Build.

  4. Debug, profile, and test

    This is the iterative phase in which you continue writing your app but with a focus on eliminating bugs and optimizing app performance. Of course, creating tests will help you in those endeavors.

    For information about basic debugging tasks, read Debug Your App and Write and View Logs.

    To view and analyze various performance metrics such as memory usage, network traffic, CPU impact, and more, use Android Monitor.

    And for an introduction to building tests, see Test Your App.

  5. Publish

    When you're ready to release your app to users, there are just a few more things to consider, such as versioning your app and signing it with a key. For more information, see the Publishing Overview.

    来源： https://developer.android.com/studio/workflow.html


Projects Overview

In this document

  1. Modules
  2. Project Files
  3. Project Structure Settings

A project in Android Studio contains everything that defines your workspace for an app, from source code and assets, to test code and build configurations. When you start a new project, Android Studio creates the necessary structure for all your files and makes them visible in the Project window on the left side of the IDE (click View > Tool Windows > Project). This page provides an overview of the key components inside your project.

Modules

A module is a collection of source files and build settings that allow you to divide your project into discrete units of functionality. Your project can have one or many modules and one module may use another module as a dependency. Each module can be independently built, tested, and debugged.

Additional modules are often useful when creating code libraries within your own project or when you want to create different sets of code and resources for different device types, such as phones and wearables, but keep all the files scoped within the same project and share some code.

You can add a new module to your project by clicking File > New > New Module.

Android Studio offers a few distinct types of module:

Android app module
Provides a container for your app's source code, resource files, and app level settings such as the module-level build file and Android Manifest file. When you create a new project, the default module name is "app".

In the Create New Module window, Android Studio offers the following app modules:

  • Phone & Tablet Module
  • Android Wear Module
  • Android TV Module
  • Glass Module

They each provide essential files and some code templates that are appropriate for the corresponding app or device type.

For more information on adding a module, read Add a Module for a New Device.

Library module
Provides a container for your reusable code, which you can use as a dependency in other app modules or import into other projects. Structurally, a library module is the same as an app module, but when built, it creates a code archive file instead of an APK, so it can't be installed on a device.

In the Create New Module window, Android Studio offers the following library modules:

  • Android Library: This type of library can contain all file types supported in an Android project, including source code, resources, and manifest files. The build result is an Android Archive (AAR) file that you can add as a dependency for your Android app modules.
  • Java Library: This type of library can contain only Java source files. The build result is an Java Archive (JAR) file that you can add as a dependency for your Andriod app modules or other Java projects.
Google Cloud module
Provides a container for your Google Cloud backend code. This module adds the required code and dependencies for a Java App Engine backend that uses simple HTTP, Cloud Endpoints, and Cloud Messaging to connect to your app. You can develop your backend to provide cloud services your app needs.

Using Android Studio to create and develop your Google Cloud module lets you manage app code and backend code in the same project. You can also run and test your backend code locally, and use Android Studio to deploy your Google Cloud module.

For more information on adding a Google Cloud module, see Adding an App Engine Java Servlet Module. For more information on running and deploying a Google Cloud module, see Running, Testing, and Deploying the Backend.

Some people also refer to modules as sub-projects and that's okay, because Gradle also refers to modules as projects. For example, when you create a library module and want to add it as a dependency to your Android app module, you must declare it as follows:

dependencies {
  compile project(':my-library-module')
}

Project Files

By default, Android Studio displays your project files in the Android view. This view does not reflect the actual file hierarchy on disk, but is organized by modules and file types to simplify navigation between key source files of your project, hiding certain files or directories that are not commonly used. Some of the structural changes compared to the structure on disk include the following:

  • Shows all the project's build-related configuration files in a top-level Gradle Script group.
  • Shows all manifest files for each module in a module-level group (when you have different manifest files for different product flavors and build types).
  • Shows all alternative resource files in a single group, instead of in separate folders per resource qualifier. For example, all density versions of your launcher icon are visible side-by-side.

Within each Android app module, files are shown in the following groups:

manifests
Contains the AndroidManifest.xml file.
java
Contains the Java source code files, separated by package names, including JUnit test code.
res
Contains all non-code resources, such as XML layouts, UI strings, and bitmap images, divided into corresponding sub-directories. For more information about all possible resource types, see Providing Resources.

The Android Project View

To see the actual file structure of the project including all files hidden from the Android view, select Projectfrom the dropdown at the top of the Project window.

When you select Project view, you can see a lot more files and directories. The most important of which are the following:

module-name/
build/
Contains build outputs.
libs/
Contains private libraries.
src/
Contains all code and resource files for the module in the following subdirectories:
androidTest/
Contains code for instrumentation tests that run on an Android device. For more information, see the Android Test documentation.
main/
Contains the "main" sourceset files: the Android code and resources shared by all build variants (files for other build variants reside in sibling directories, such as src/debug/ for the debug build type).
AndroidManifest.xml
Describes the nature of the application and each of its components. For more information, see the AndroidManifest.xmldocumentation.
java/
Contains Java code sources.
jni/
Contains native code using the Java Native Interface (JNI). For more information, see the Android NDK documentation.
gen/
Contains the Java files generated by Android Studio, such as your R.java file and interfaces created from AIDL files.
res/
Contains application resources, such as drawable files, layout files, and UI string. See Application Resources for more information.
assets/
Contains file that should be compiled into an .apk file as-is. You can navigate this directory in the same way as a typical file system using URIs and read files as a stream of bytes using the AssetManager . For example, this is a good location for textures and game data.
test/
Contains code for local tests that run on your host JVM.
build.gradle (module)
This defines the module-specific build configurations.
build.gradle (project)
This defines your build configuration that apply to all modules. This file is integral to the project, so you should maintain them in revision control with all other source code.

For information about other build files, see Configure Your Build.

Project Structure Settings

To change various settings for your Android Studio project, open the Project Structure dialog by clicking File > Project Structure. It contains the following sections:

  • SDK Location: Sets the location of the JDK, Android SDK, and Android NDK that your project uses.
  • Project: Sets the version for Gradle and the Android plugin for Gradle, and the repository location name.
  • Developer Services: Contains settings for Android Studio add-in components from Google or other third parties. See Developer Services, below.
  • Modules: Allows you to edit module-specific build configurations, including the target and minimum SDK, the app signature, and library dependencies. See Modules, below.

Developer Services

The Developer Services section of the Project Structure dialog box contains configuration pages for several services that you can be use with your app. This section contains the following pages:

  • AdMob: Allows you to turn on Google's AdMob component, which helps you understand your users and show them tailored advertisements.
  • Analytics: Allows you to turn on Google Analytics, which helps you measure user interactions with your app across various devices and environments.
  • Authentication: Allows users to use Google Sign-In to sign in to your app with their Google accounts.
  • Cloud: Allows you to turn on Firebase cloud-based services for your app.
  • Notifications: Allows you to use Google Cloud Messaging to communicate between your app and your server.

Turning on any of these services may cause Android Studio to add necessary dependencies and permissions to your app. Each configuration page lists these and other actions that Android Studio takes if you enable the associated service.

Modules

The Modules settings section lets you change configuration options for each of your project's modules. Each module's settings page is divided into the following tabs:

  • Properties: Specifies the versions of the SDK and build tools to use to compile the module.
  • Signing: Specifies the certificate to use to sign your APK.
  • Flavors: Lets you create multiple build flavors, where each flavor specifies a set of configuration settings, such as the module's minimum and target SDK version, and the version code and version name. For example, you might define one flavor that has a minimum SDK of 15 and a target SDK of 21, and another flavor that has a minimum SDK of 19 and a target SDK of 23.
  • Build Types: Lets you create and modify build configurations, as described in Configuring Gradle Builds. By default, every module has debug andrelease build types, but you can define more as needed.
  • Dependencies: Lists the library, file, and module dependencies for this module. You can add, modify, and delete dependencies from this pane. For more information about module dependencies, see Configuring Gradle Builds.
    来源： https://developer.android.com/studio/projects/index.html


Create a Project

  1. Step 1: Create a New Project
  2. Step 2: Select Form Factors and API Level
  3. Step 3: Add an Activity
  4. Step 4: Configure Your Activity
  5. Step 5: Develop Your App

A project in Android Studio contains one or more modules that keep your code organized into discrete units of functionality. This page shows how to start a new project.

Android Studio makes it easy to create Android apps for various form factors, such as phone, tablet, TV, Wear, and Google Glass. The New Project wizard lets you choose the form factors for your app and populates the project structure with everything you need to get started.

For more information about the Android project structure and module types, read Projects Overview. For more information on adding a module for a new device to an existing project, read Add a Module for a New Device.

Step 1: Create a New Project

If you didn't have a project opened, Android Studio shows the Welcome screen. To create a new project, click Start a New Android Studio project.

If you had a project opened, Android Studio shows the development environment. To create a new project, click File > New > New Project.

The next window lets you configure the name of your app, the package name, and the location of your project.

Figure 1. The Configure your new project screen.

Enter the values for your project then click Next.

Step 2: Select Form Factors and API Level

The next window lets you select the form factors supported by your app, such as phone, tablet, TV, Wear, and Google Glass. The selected form factors become the app modules within the project. For each form factor, you can also select the API Level for that app. To get more information, click Help me choose.

Figure 2. Chart of the current Android version distributions, shown when you click Help me choose.

The Android Platform Distribution window shows the distribution of mobile devices running each version of Android, as shown in figure 2. Click on an API level to see a list of features introduced in the corresponding version of Android. This helps you choose the minimum API Level that has all the features that your apps needs, so you can reach as many devices as possible. Then click OK.

Figure 3. The Target Android Devices screen.

Then, on the Target Android Devices Window, once you've selected your form factors and API versions, click Next.

Step 3: Add an Activity

The next screen lets you select an activity type to add to your app, as shown in figure 4. This screen displays a different set of activities for each of the form factors you selected earlier.

Figure 4. The Add an Activity screen for a mobile form factor.

Choose an activity type then click Next.

Note: If you choose "Add No Activity", click Finish to create the project.

Step 4: Configure Your Activity

The next screen lets you configure the activity to add to your app, as shown in figure 5.

Figure 5. The Customize the Activity screen.

Enter the activity name, the layout name, and the activity title. Then click Finish.

Step 5: Develop Your App

Android Studio creates the default structure for your project and opens the development environment. If your app supports more than one form factor, Android Studio creates a module folder with complete source files for each of them as shown in figure 6.

Figure 6. Project structure for a newly created app.

Now you are ready to develop your app. For more information, see the following links:

  • Training Lessons
  • Add a Module for a New Device

来源： https://developer.android.com/studio/projects/create-project.html


Add a Module for a New Device

  1. Create a New Module
  2. Import a Module
  3. Next Steps

Modules provide a container for your app's source code, resource files, and app level settings such as the module-level build file and Android manifest file. Each module can be independently built, tested, and debugged.

Android Studio uses modules to make it easy to add new devices to your project. By following a few simple steps in Android Studio, you can create a module to contain code that's specific to a device type, such as Android Wear or Android TV. Android Studio automatically creates module directories, such as source and resource directories, and a default build.gradle file appropriate for the device type. Also, Android Studio creates device modules with recommended build configurations, such as using the Leanback library for Android TV modules.

This page describes how to add a new module for a specific device.

Android Studio also makes it easy to add a library or Google Cloud module to your project. For details on creating a library module, see Create a Library Module. For details on creating a Google Cloud module, see Adding an App Engine Java Servlet Module.

Create a New Module

To add a new module to your project for a new device, proceed as follows:

  1. Click File > New > New Module.
  2. In the New Module window that appears, Android Studio offers the following device modules:
    • Phone & Tablet Module
    • Android Wear Module
    • Android TV Module
    • Glass Module
    Select the module for the device you want, then click Next.
  3. In the Configure your new module window, enter the following details:
    • Application Name: This name is used as the title of your app launcher icon for the new module.
    • Module Name: This text is used as the name of the folder where your source code and resources files are visible.
    • Package Name: This is the Java namespace for the code in your module and is added as the package attribute in module's Android manifest file.
    • Minimum required SDK: This setting indicates the lowest version of the Android platform that the app module supports. This value sets theminSdkVersion attribute in the build.gradle file, which you can edit later.

    Then click Next.

  4. Depending on which device module you selected, the following page displays a selection of appropriate code templates you can select to use as your main activity. Click an activity template you want to start with then click Next. If you don't need an activity, click Add No Activity then click Finish and you're done.
  5. If you chose an activity template, the next page contains several input fields related to the activity template you chose, such as the class name and layout name. Complete the form then click Finish.

Android Studio creates all the necessary files for the new module, and syncs the project with the new module gradle files. Adding a module for a new device also adds any required dependencies for the target device to the module's build file.

Once the Gradle project sync completes, the new module appears in the Project window on the left. If you don't see the new module folder, make sure it's displaying the Android view.

Import a Module

To import an existing module into your project, proceed as follows:

  1. Click File > New > Import Module.
  2. In the Source directory box, type or select the directory of the module(s) that you want to import:
    • If you are importing one module, indicate its root directory.
    • If you are importing multiple modules from a project, indicate the project folder. For each module inside the folder, a box appears and indicates theSource location and Module name. Make sure the Import box is checked for each module that you want to import.
    If your module(s) have other dependencies, they will be listed to import under Additional required modules.
  3. Type your desired module name(s) in the Module name field(s).
  4. Click Finish.

Once the module is imported, it appears in the Project window on the left.

Next Steps

Once you've added a new module, you can modify the module code and resources, configure module build settings, and build the module. You can also run and debug the module like any other app.

  • To learn about build settings for a module, see The Module-level Build File.
  • To build and run a specific module, see Select and build a different module.

You'll also want to add code and resources to properly support the new device. For more information about how to develop app modules for different device types, see the corresponding documentation:

  • For Android Wear modules: Creating and Running a Wearable App
  • For Android TV modules: Get Started with TV Apps
  • For Glass modules: GDK Quick Start

As you develop your new module, you might create device independent code that is already duplicated in a different app module. Instead of maintaining duplicate code, consider moving the shared code to a library module and adding the library as a dependency to your app modules. For more information on creating a library module and adding it as a dependency, see Create an Android Library.

来源： https://developer.android.com/studio/projects/add-app-module.html


Create an Android Library

  1. Create a Library Module
  2. Add Your Library as a Dependency
  3. Development Considerations

An Android library is structurally the same as an Android app module. It can include everything needed to build an app, including source code, resource files, and an Android manifest. However, instead of compiling into an APK that runs on a device, an Android library compiles into an Android Archive (AAR) file that you can use as a dependency for an Android app module.

A library module is useful in the following situations:

  • When you're building multiple apps that use some of the same components, such as activities, services, or UI layouts.
  • When you're building an app that exists in multiple APK variations, such as a free and paid version and you need the same core components in both.

In either case, simply move the files you want to reuse into a library module then add the library as a dependency for each app module. This page teaches you how to do both.

Create a Library Module

To create a new library module in your project, proceed as follows:

  1. Click File > New > New Module.
  2. In the Create New Module window that appears, click Android Library, then click Next.

    There's also an option to create a Java Library, which builds a traditional JAR file. While a JAR file is useful for many projects—especially when you want to share code with other platforms—it does not allow you to include Android resources or manifest files, which is very useful for code reuse in Android projects. So this guide focuses on creating Android libraries.

  3. Give your library a name and select a minimum SDK version for the code in the library, then click Finish.

Once the Gradle project sync completes, the library module appears in the Project panel on the left. If you don't see the new module folder, make sure it's displaying the Android view.

Convert an app module to a library module

If you have an existing app module with all the code you want to reuse, you can turn it into a library module as follows:

  1. Open the build.gradle file for the existing app module. At the top, you should see the following:
    apply plugin: 'com.android.application'
  2. Change the plugin assignment as shown here:

    apply plugin: 'com.android.library'
  3. Click Sync Project with Gradle Files.

That's it. The entire structure of the module remains the same, but it now operates as an Android library and the build will now create an AAR file instead of an APK.

Add Your Library as a Dependency

To use your Android library's code in another app module, proceed as follows:

  1. Add the library to your project in one of two ways (if you created the library module within the same project, then it's already there and you can skip this step):
    • Add the compiled AAR (or JAR) file:
      1. Click File > New Module.
      2. Click Import .JAR/.AAR Package then click Next.
      3. Enter the location of the AAR or JAR file then click Finish.
    • Import the library module to your project:
      1. Click File > New > Import Module.
      2. Enter the location of the library module directory then click Finish.

      The library module is copied to your project, so you can actually edit the library code. If you want to maintain a single version of the library code, then this is probably not what you want and you should instead import the compiled AAR file as described above.

  2. Make sure the library is listed at the top of your settings.gradle file, as shown here for a library named "my-library-module":
    include ':app', ':my-library-module'
  3. Open the app module's build.gradle file and add a new line to the dependencies block as shown in the following snippet:
    dependencies {
        compile project    (":my-library-module")
    }
  4. Click Sync Project with Gradle Files.

In this example above, the Android library module named my-library- module becomes build dependency for the module in which the build.gradle file resides.

Any code and resources in the Android library is now accessible to your app module, and the library AAR file is bundled into your APK at build time.

However, if you want to share your AAR file separately, you can find it in project-name/module-name/build/outputs/aar/ and you can regenerate it by clicking Build > Make Project.

Development Considerations

As you develop your library modules and dependent apps, be aware of the following behaviors and limitations.

Once you have added references to library modules to your Android app module, you can set their relative priority. At build time, the libraries are merged with the app one at a time, starting from the lowest priority to the highest.

  • Resource merge conflicts

    The build tools merge resources from a library module with those of a dependent app module. If a given resource ID is defined in both modules, the resource from the app is used.

    If conflicts occur between multiple AAR libraries, then the resource from the library listed first in the dependencies list (toward the top of thedependencies block) is used.

    To avoid resource conflicts for common resource IDs, consider using a prefix or other consistent naming scheme that is unique to the module (or is unique across all project modules).

  • A library module can include a JAR library

    You can develop a library module that itself includes a JAR library; however you need to manually edit the dependent app modules's build path and add a path to the JAR file.

  • A library module can depend on an external JAR library

    You can develop a library module that depends on an external library. (for example, the Maps external library). In this case, the dependent app must build against a target that includes the external library (for example, the Google APIs Add-On). Note also that both the library module and the dependent app must declare the external library in their manifest files, in a <uses- library> element.

  • Library modules cannot include raw assets

    The tools do not support the use of raw asset files (saved in the assets/ directory) in a library module. Any asset resources used by an app must be stored in the assets/ directory of the app module itself.

  • The app module's minSdkVersion must be equal to or greater than the version defined by the library

    A library is compiled as part of the dependent app module, so the APIs used in the library module must be compatible with the platform version that the app module supports.

  • Each library module creates its own R class

    When you build the dependent app modules, library modules are compiled into an AAR file then added to the app module. Therefore, each library has its own R class, named according to the library's package name. The R class generated from main module and the library module is created in all the packages that are needed including the main module's package and the libraries' packages.

  • Library modules may include their own ProGuard configuration file

    You can enable code shrinking on your library by adding a ProGuard configuration file to your library that includes its ProGuard directives. The build tools embed this file within the generated AAR file for the library module. When you add the library to an app module, the library's ProGuard file gets appended to the ProGuard configuration file (proguard.txt) of the app module.

    By embedding a ProGuard file in your library module, you ensure that app modules that depend on your library do not have to manually update their ProGuard files to use your library. When ProGuard runs on the Android app module, it uses the directives from both the app module and the library so you should not run ProGuard on the library alone.

    To specify the name of your library's configuration file, add it to the consumerProguardFiles method, inside the defaultConfig block of your library'sbuild.gradle file. For example, the following snippet sets lib-proguard-rules.txt as the library's ProGuard configuration file:

    android {
    defaultConfig {
        consumerProguardFiles 'lib-proguard-rules.txt'
    }
    ...
}

    By default, the app module uses the library's release build, even when using the app module's debug build type. To use a different build type from the library, select the correct build variant for your library module in the Build Variants window when building your app. You can also declare dependencies within the buildTypes block of the app's build.gradle file.

    To ensure that your library's ProGuard rules do not apply unwanted shrinking side effects to app modules, only include rules that disable ProGuard features that do not work with your library. Rules that attempt to aid developers can conflict with the existing code in an app module or its other libraries and therefore should not be included. For example, your library's ProGuard file can specify what code needs to be kept during an app module's minification.

    Note: The Jack toolchain provides support for only some shrinking and obfuscation options with ProGuard.

    来源： https://developer.android.com/studio/projects/android-library.html


Add Code from a Template

  1. Application Templates
    1. BlankActivity Template
    2. Full Screen Activity Template
    3. Master Detail Flow Template
  2. Activity Templates
    1. Login Activity Template
    2. Settings Activity Template
  3. Other Templates

Android Studio provides code templates that help you create new projects with a certain design pattern or to add components to your existing project. The code templates follow the Android design and development guidelines to get you on the right track to creating a beautiful, functional application.

There are several types of Android code templates, which can create anything from an entire application down to specific application components. The main categories of code templates are as follows:

  • Application Templates
  • Activity Templates
  • Other Templates

The templates use support library objects if such objects are available. The support library objects make new features available on the widest range of platforms. For example, since the templates use the appcompat library, apps based on the templates use material design user interface principles even if they are running on older Android devices that do not directly support material design.

Application Templates

Application templates create basic Android application modules that you can immediately run and test on your Android device. These templates are available when you create a new Android module, though you can also use these templates to add new activities to an existing module.

To use Android application templates:

  1. In Android Studio, select File > New > Module.
  2. Enter the settings for your application, including Application Name, Company Domain, Package name, and minimum SDK, then click Next.
  3. Select an application template to use, then click Next. For example,
    • BlankActivity
    • FullScreenActivity
    • MasterDetailFlow
  4. Enter the settings for your activity, including Activity Name, layout Name, Title, and Menu Resource Name, then click Finish.

Note: The other activity template options also create applications, however these applications require further modification before they can be launched on an Android device.

Blank Activity Template

Example Description

The BlankActivity template with the Navigation Type: None option creates a simple application that follows the Android Design guidelines. Use this template to create a basic, minimal app as a starting point for your project.

This template includes:

  • ActionBar
  • Action overflow
  • Basic layout

The BlankActivity template with the Navigation Type: Tabs or Tabs + Swipe option creates an application with three sections based on the Fragment class and a tabbed user interface.

This template includes:

  • ActionBar for tab controls
  • Fragment objects for section content
  • Optional swipe gesture support based on the swipe view design pattern, which extendsFragmentPagerAdapter to manage section fragments

The BlankActivity template with the Navigation Type: Swipe Views + Title Strip option creates an application with three Fragment sections, a compact title strip header (known as Scrollable Tabs in the Android Designguide) and swipe navigation between the sections, based on the swipe view design pattern.

This template includes:

  • PagerTitleStrip for section titles
  • Fragment objects for section content
  • FragmentPagerAdapter to manage section fragments

The BlankActivity template with the Navigation Type: Dropdown option creates an application that extendsFragmentActivity, containing three Fragment sections, with an ActionBar using list mode navigation.

This template includes:

  • ActionBar for list mode navigation
  • Fragment objects for section content

Full Screen Activity Template

Example Description

This template provides an implementation of an activity which alternates between a primary, full screen view and a view with standard user interface controls, including the notification bar and application title bar. The full screen view is the default and a user can activate the standard view by touching the device screen.

This template includes:

  • SystemUiHider implementation that manages hiding of the system user interface using a version-compatible approach
  • Basic layout

Master Detail Flow Template

Example Description

This template creates an adaptive layout for a set of items and associated details. On a tablet device, the item list and item details are displayed on the same screen. On a smaller device, the list and details are displayed on separate screens.

Note: This template follows the recommendations of the Designing for Multiple Screens Android training.

This template includes:

  • Adaptive layout using alternative resource XML files
  • FragmentActivity, Fragment and ListFragment implementations

Activity Templates

Android activity templates provide options to add new activities to your existing application.

To use Android activity templates:

  1. Right click the project folder of the Android application where you want to add an activity.
  2. Select New > Other...
  3. Select Android > Android Activity, then click Next.
  4. Select an activity template, then follow the instructions to add it to your existing application.
    • LoginActivity
    • SettingsActivity
    • BlankActivity
    • FullScreenActivity
    • MasterDetailFlow

These templates create the same type of activity as they do when used as an application template, however the following templates create activities which are specifically intended to be used as part of an existing application.

Login Activity Template

Example Description

This activity template provides input fields and a sample implementation of an AsyncTask that asks users to login or register with their credentials.

This template includes:

  • Recommended user interface for requesting login information
  • AsyncTask implementation for handing network operations separately from the main user interface thread
  • Progress indicator during network operations

Settings Activity Template

Example Description

This template extends the PreferenceActivity class and uses an XML file to create preference settings. This template also demonstrates how to implement several data types for settings.

This template includes:

  • Activity extending PreferenceActivity
  • Preference values defined using XML files added to the res/xml/ directory of your project.

Other Templates

Android object templates provide options to add new components to your existing application, including the previously mentioned activities as well as the following additional items:

To use Android object templates:

  1. Right-click the module folder of the Android application where you want to add a code component.
  2. Select New
  3. Select the object type and template, then follow the instructions to add it to your existing application.
    • AIDL
    • Activity
    • Folder
    • Fragment
    • Google
    • Other
    • Service
    • UI Component
    • Wear
    • Widget
    • XML

来源： https://developer.android.com/studio/projects/templates.html


Write Your App

Android Studio includes tools for every stage of development, but what's most important is simply writing your app: writing the code, building layouts, creating images, and being productive along the way.

That's what this section is all about: the tools that help you write your app and write it quickly.

Coding Productivity

The following are just a few features to help you be more productive when coding.

Create custom code-completion templates

Live templates allow you to enter code snippets for fast insertion and completion of small chunks of code. To insert a live template, type the template abbreviation and press the Tab key. Android Studio inserts the code snippet associated with the template into your code.

For example, the newInstance abbreviation followed by Tab inserts the code for a new fragment instance with argument placeholders. Or type fbc to insert the findViewById() method along with cast and resource id syntax.

To see the list of supported live templates and customize them, click File > Settings > Editor > Live Templates.

Learn more about Live Templates.

Get quick fixes from Lint

Android Studio provides a code scanning tool called Lint to help you to identify and correct problems with the structural quality of your code, without executing the app or writing tests.

Every time you build your app, Android Studio runs Lint to check your source files for potential bugs and looks for optimization improvements in correctness, security, performance, usability, accessibility, and internationalization.

Learn more about Lint.

See documentation and resource details

You can view documentation for an API by placing the caret on the method/member/class name and pressing F1.

Information is also available for other resources, such as images and themes. For example, if you place the caret on the theme name in your Android manifest file and press F1, you can see the theme inheritance hierarchy and colors or images for the various attributes.

Quickly create new files

When you want to create a new file, click the desired directory in the Project window, then press Alt + Insert (Command + N on Mac). Android Studio shows a small window with a list of suggested file types, as appropriate for the selected directory.

Working with Resources

Android Studio includes the following features and tools to help you create and manage resource files.

Create images for all screen densities

Android Studio includes a tool called Vector Asset Studio that helps you create images that support each screen density. You can upload your own SVG file for editing or select from one of the many Google-provided material design icons. To get started, click File > New > Vector Asset.

Learn more about Vector Asset Studio.

Preview images and colors

When referencing images and icons in your code, a preview of the image appears in the left margin to help you verify the image or icon reference.

To view the full size image, click the thumbnail in the left margin. Or, place the caret on the inline reference to the asset and press F1 to see the image details, including all the alternative sizes.

Create new layouts

Android Studio offers an advanced layout editor that allows you to drag-and-drop widgets into your layout and preview your layout while editing the XML.

To get started, click the module where you want to add the layout, then click File > New > XML > Layout XML File.

Learn more about the Layout Editor.

Translate UI strings

The Translations Editor tool gives you a single view of all of your translated resources, making it easy to change or add translations, and even find missing translations without opening every version of the strings.xml file. You can even upload your strings file to order translation services.

To get started, right-click on any copy of your strings.xml file then click Open Translations Editor.

Learn more about the Translations Editor.

来源： https://developer.android.com/studio/write/index.html


Improve Your Code with Lint

In This Document

  1. Overview
  2. Running lint from Android Studio
  3. Running lint from the command-line
  4. Configuring lint
    1. Configuring Lint in Android Studio
    2. Configuring the lint file
    3. Configuring lint checking in Java and XML source files

See Also

  1. Using Android Annotations

In addition to testing that your Android application meets its functional requirements, it's important to ensure that your code has no structural problems. Poorly structured code can impact the reliability and efficiency of your Android apps and make your code harder to maintain. For example, if your XML resource files contain unused namespaces, this takes up space and incurs unnecessary processing. Other structural issues, such as use of deprecated elements or API calls that are not supported by the target API versions, might lead to code failing to run correctly.

Overview

Android Studio provides a code scanning tool called Lint that can help you to easily identify and correct problems with the structural quality of your code, without having to execute the app or write any test cases. Each problem detected by the tool is reported with a description message and a severity level, so that you can quickly prioritize the critical improvements that need to be made. You can also configure a problem's severity level to ignore issues that are not relevant for your project, or raise the severity level. The tool has a command-line interface, so you can easily integrate it into your automated testing process.

The Lint tool checks your Android project source files for potential bugs and optimization improvements for correctness, security, performance, usability, accessibility, and internationalization. You can run Lint from the command-line or from Android Studio.

Note: In Android Studio, additional IntelliJ code inspections run when your code is compiled in Android Studio to streamline code review.

Figure 1 shows how the Lint tool processes the application source files.

Figure 1. Code scanning workflow with the Lint tool

Application source files
The source files consist of files that make up your Android project, including Java and XML files, icons, and ProGuard configuration files.
The lint.xml file
A configuration file that you can use to specify any Lint checks that you want to exclude and to customize problem severity levels.
The Lint tool
A static code scanning tool that you can run on your Android project from the command-line or Android Studio. The Lint tool checks for structural code problems that could affect the quality and performance of your Android application. It is strongly recommended that you correct any errors that Lint detects before publishing your application.
Results of Lint checking
You can view the results from Lint in the console or in the Event Log in Android Studio. Each issue is identified by the location in the source files where it occurred and a description of the issue.

The Lint tool is automatically installed as part of the Android SDK Tools revision 16 or higher.

Running lint in Android Studio

In Android Studio, the configured Lint and IDE inspections run automatically whenever you build your app. The IDE inspections are configured along with the Lint checks to run IntelliJ code inspections to streamline code review.

Note: To view and modify inspection severity levels, use the File > Settings > Editor > Inspections menu to open the Inspection Configuration page with a list of the supported inspections.

With Android Studio, you can also run Lint inspections for a specific build variant, or for all build variants from the build.gradle file. Add the lintOptionsproperty to the android settings in the build file. This code snippet from a Gradle build file shows how to set the quiet option to true and theabortOnError option to false.

android {
    lintOptions {
       // set to true to turn off analysis progress reporting by lint
       quiet true
       // if true, stop the gradle build if errors are found
       abortOnError false
       // if true, only report errors
       ignoreWarnings true
       }
       ...
    }

To manually run inspections in Android Studio, from the application or right-click menu, choose Analyze > Inspect Code. The Specify Inspections Scopedialog appears so you can specify the desired inspection scope and profile.

Results of each inspection appear in the Inspection tool window. You can see a problem synopsis inline by hovering over an inspection error, or display the error's full issue explanation by selecting it.

Running lint from the Command-Line

To run Lint against a list of files in a project directory:

lint [flags] <project directory>

For example, you can issue the following command to scan the files under the myproject directory and its subdirectories. The issue ID MissingPrefix tells Lint to only scan for XML attributes that are missing the Android namespace prefix.

lint --check MissingPrefix myproject

To see the full list of flags and command-line arguments supported by the tool:

lint --help

Example lint output

The following example shows the console output when the Lint command is run against a project called Earthquake.

$ lint Earthquake

Scanning Earthquake: ...............................................................................................................................
Scanning Earthquake (Phase 2): .......
AndroidManifest.xml:23: Warning: <uses-sdk> tag appears after <application> tag [ManifestOrder]
  <uses-sdk android:minSdkVersion="7" />
  ^
AndroidManifest.xml:23: Warning: <uses-sdk> tag should specify a target API level (the highest verified version; when running on later versions, compatibility behaviors may be enabled) with android:targetSdkVersion="?" [UsesMinSdkAttributes]
  <uses-sdk android:minSdkVersion="7" />
  ^
res/layout/preferences.xml: Warning: The resource R.layout.preferences appears to be unused [UnusedResources]
res: Warning: Missing density variation folders in res: drawable-xhdpi [IconMissingDensityFolder]
0 errors, 4 warnings

The output above lists four warnings and no errors in this project. Three warnings (ManifestOrder, UsesMinSdkAttributes, and UnusedResources) were found in the project's AndroidManifest.xml file. The remaining warning (IconMissingDensityFolder) was found in the Preferences.xml layout file.

Configuring lint

By default, when you run a Lint scan, the tool checks for all issues that are supported by Lint. You can also restrict the issues for Lint to check and assign the severity level for those issues. For example, you can disable Lint checking for specific issues that are not relevant to your project and configure Lint to report non-critical issues at a lower severity level.

You can configure Lint checking at different levels:

  • Globally, for the entire project
  • Per project module
  • Per production module
  • Per test module
  • Per open files
  • Per class hierarchy
  • Per Version Control System (VCS) scopes

Configuring Lint in Android Studio

The built-in Lint tool checks your code while you're using Android Studio. You can view warnings and errors in two ways:

  • As pop-up text in the Code Editor. When Lint finds a problem, it highlights the problematic code in yellow, or underlines the code in red for more serious issues.
  • In the Lint Inspection Results window after you select Analyze > Inspect Code.

To set default Lint checks:

  1. In Android Studio, open your project.
  2. Select File > Other Settings > Default Settings.
  3. In the Default Preferences dialog, select Editor > Inspections.
  4. In the Profile field, select Default or Project Default to set the scope for Android Studio or just for this project, respectively.
  5. Expand a category and change the Lint settings as needed.

    6. You can select individual checks, or entire categories.

  6. Click OK.

To produce a list of Lint checks displayed in the Inspection Results window:

  1. In Android Studio, open your project and select a portion of your project that you want to test.
  2. Select Analyze > Inspect Code.
  3. In the Specify Inspection Scope dialog, select the inspection scope and profile.

    4. The scope specifies the files you want to analyze, and the profile specifies the Lint checks you’d like to perform.

  4. If you want to change the Lint settings, click …. In the Inspections dialog, optionally click Manage to define a new profile, specify the Lint settings you want, and then click OK.

    5. In the Inspections dialog, you can search for a string to find Lint checks. Note that changing Lint settings for a profile in the Inspections dialog doesn’t change the default settings, as described in the previous procedure. It does change the settings for profiles displayed in the Inspectionsdialog, however.

  5. Click OK.

    6. The results appear in the Inspection Results window, organized by category.

Configuring the lint file

You can specify your Lint checking preferences in the lint.xml file. If you are creating this file manually, place it in the root directory of your Android project. If you are configuring Lint preferences in Android Studio, the lint.xml file is automatically created and added to your Android project for you.

The lint.xml file consists of an enclosing <lint> parent tag that contains one or more children <issue> elements. Each <issue> is identified by a uniqueid attribute value, which is defined by Lint.

<?xml version="1.0" encoding="UTF-8"?>
    <lint>
        <!-- list of issues to configure -->
</lint>

By setting the severity attribute value in the <issue> tag, you can disable Lint checking for an issue or change the severity level for an issue.

Tip: To see the full list of issues supported by the Lint tool and their corresponding issue IDs, run the lint --list command.

Sample lint.xml file

The following example shows the contents of a lint.xml file.

<?xml version="1.0" encoding="UTF-8"?>
<lint>
    <!-- Disable the given check in this project -->
    <issue id="IconMissingDensityFolder" severity="ignore" />

    <!-- Ignore the ObsoleteLayoutParam issue in the specified files -->
    <issue id="ObsoleteLayoutParam">
        <ignore path="res/layout/activation.xml" />
        <ignore path="res/layout-xlarge/activation.xml" />
    </issue>

    <!-- Ignore the UselessLeaf issue in the specified file -->
    <issue id="UselessLeaf">
        <ignore path="res/layout/main.xml" />
    </issue>

    <!-- Change the severity of hardcoded strings to "error" -->
    <issue id="HardcodedText" severity="error" />
</lint>

Configuring lint checking in Java and XML source files

You can disable Lint checking from your Java and XML source files.

Tip: If you are using Android Studio, you can use the File > Settings > Project Settings > Inspections feature to manage the Lint checking to your Java or XML source files.

Configuring lint checking in Java

To disable Lint checking specifically for a Java class or method in your Android project, add the @SuppressLint annotation to that Java code.

The following example shows how you can turn off Lint checking for the NewApi} issue in the onCreate method. The Lint tool continues to check for theNewApi issue in other methods of this class.

@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

The following example shows how to turn off Lint checking for the ParserError issue in the FeedProvider class:

@SuppressLint("ParserError")
public class FeedProvider extends ContentProvider {

To suppress checking for all Lint issues in the Java file, use the all keyword, like this:

@SuppressLint("all")

Configuring lint checking in XML

You can use the tools:ignore attribute to disable Lint checking for specific sections of your XML files. In order for this attribute to be recognized by the Lint tool, the following namespace value must be included in your XML file:

namespace xmlns:tools="http://schemas.android.com/tools"

The following example shows how you can turn off Lint checking for the UnusedResources issue for the <LinearLayout> element of an XML layout file. The ignore attribute is inherited by the children elements of the parent element in which the attribute is declared. In this example, the Lint check is also disabled for the child <TextView> element.

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:ignore="UnusedResources" >

    <TextView
        android:text="@string/auto_update_prompt" />
</LinearLayout>

To disable more than one issue, list the issues to disable in a comma-separated string. For example:

tools:ignore="NewApi,StringFormatInvalid"

To suppress checking for all Lint issues in the XML element, use the all keyword, like this:

tools:ignore="all"
来源： https://developer.android.com/studio/write/lint.html


Improve Code Inspection with Annotations

  1. Adding Basic Annotations
  2. Adding Nullness Annotations
  3. Adding Resource Annotations
  4. Adding Thread Annotations
  5. Adding Value Constraint Annotations
  6. Adding Permission Annotations
  7. Adding CheckResult Annotations
  8. Adding CallSuper Annotations
  9. Creating Enumerated Annotations

See also

  1. Improving Your Code with lint
  2. Annotations in Android Studio

Using code inspections tools such as Lint can help you find problems and improve your code, but inspection tools can only infer so much. Android resource ids, for example, use an int to identify strings, graphics, colors and other resource types, so inspection tools cannot tell when you have specified a string resource where you should have specified a color. This situation means that your app may render incorrectly or fail to run at all, even if you use code inspection.

Annotations allow you to provide hints to code inspections tools like Lint, to help detect these, more subtle code problems. They are added as metadata tags that you attach to variables, parameters, and return values to inspect method return values, passed parameters, and local variables and fields. When used with code inspections tools, annotations can help you detect problems, such as null pointer exceptions and resource type conflicts.

For more information on enabling and running Lint inspections, see Improving Your Code with lint.

Android supports a variety of annotations for insertion in the methods, parameters, and return values in your code, for example:

@Nullable
Can be null.
@NonNull
Cannot be null.
@StringRes
References a R.string resource.
@DrawableRes
References a Drawable resource.
@ColorRes
References a Color resource.
@InterpolatorRes
References a Interpolator resource.
@AnyRes
References any type of R. resource.
@UiThread
Calls from a UI thread.

For a complete list of the supported annotations, either examine the contents of the Support-Annotations library or use the auto-complete feature to display the available options for the import android.support.annotation. statement. The SDK Manager packages the Support-Annotations library in the Android Support Repository for use with Android Studio and in the Android Support Library for use with other Android development tools.

Adding Basic Annotations

To add annotations to your code, first add a dependency to the Support-Annotations library:

  1. Select File > Project Structure.
  2. In the Project Structure dialog, select the desired module, click the Dependencies tab.
  3. Click the [image] icon to include a Library dependency.
  4. In the Choose Library Dependency dialog, select support-annotations and click Ok.

The build.gradle file is updated with the support-annotations dependency.

You can also manually add this dependency to your build.gradle file, as shown in the following example.

dependencies {
    compile 'com.android.support:support-annotations:23.3.0'
}

The Support-Annotations library is decorated with the supported annotations so using this library's methods and resources automatically checks the code for potential problems.

If you include annotations in a library and use the Android Plugin for Gradle to build an Android ARchive (AAR) artifact of that library, the annotations are included as part of the artifact in XML format in the annotations.zip file.

To start a code inspection from Android Studio, which includes validating annotations and automatic Lint checking, select Analyze > Inspect Code from the menu options. Android Studio displays conflict messages throughout the code to indication annotation conflicts and suggest possible resolutions.

Adding Nullness Annotations

Add @Nullable and @NonNull annotations to check the nullness of a given variable, parameter, or return value. For example, if a local variable that contains a null value is passed as a parameter to a method with the @NonNull annotation attached to that parameter, building the code generates a warning indicating a non-null conflict.

This example attaches the @NonNull annotation to the context and attrs parameters to check that the passed parameter values are not null.

import android.support.annotation.NonNull;
...

    /** Add support for inflating the <fragment> tag. */
    @NonNull
    @Override
    public View onCreateView(String name, @NonNull Context context,
      @NonNull AttributeSet attrs) {
      ...
      }
...

Nullability Analysis

Android Studio supports running a nullability analysis to automatically infer and insert nullness annotations in your code. A nullability analysis scans the contracts throughout the method hierarchies in your code to detect:

  • Calling methods that can return null
  • Methods that should not return null
  • Variables, such as fields, local variables, and parameters, that can be null
  • Variables, such as fields, local variables, and parameters, that cannot hold a null value

The analysis then automatically inserts the appropriate null annotations in the detected locations.

To run a nullability analysis in Android Studio, select Analyze > Infer Nullity. Android Studio inserts the Android @Nullable and @NonNull annotations in detected locations in your code. After running a null analysis, it's good practice to verify the injected annotations.

Note: When adding nullness annotations, autocomplete may suggest the IntelliJ @Nullable and @NotNull annotations instead of the Android null annotations and may auto-import the corresponding library. However, the Android Studio Lint checker only looks for the Android null annotations. When verifying your annotations, confirm that your project uses the Android null annotations so the Lint checker can properly notify you during code inspection.

Adding Resource Annotations

Validating resource types can be useful as Android references to resources, such as Drawables and R.string resources, are passed as integers. Code that expects a parameter to reference a specific type of resource, for example Drawables, can be passed the expected reference type of int, but actually reference a different type of resource, such as a R.string resource.

For example, add @StringRes annotations to check that a resource parameter contains a R.string reference. During code inspection, the annotation generates a warning if a R.string reference is not passed in the parameter.

This example attaches the @StringRes annotation to the resId parameter to validate that it is really a string resource.

import android.support.annotation.StringRes;
...
    public abstract void setTitle(@StringRes int resId);
    ...

Annotations for the other resource types, such as @DrawableRes, @DimenRes, @ColorRes, and @InterpolatorRes can be added using the same annotation format and run during the code inspection.

Adding Thread Annotations

Thread annotations check if a method is called from a specific type of thread. The following thread annotations are supported:

  • @UiThread
  • @MainThread
  • @WorkerThread
  • @BinderThread

Note: The @MainThread and the @UiThread annotations are interchangeable so methods calls from either thread type are allowed for these annotations.

If all methods in a class share the same threading requirement, you can add a single thread annotation to the class to verify that all methods in the class are called from the same type of thread.

A common use of the thread annotation is to validate method overrides in the AsyncTask class as this class performs background operations and publishes results only on the UI thread.

Adding Value Constraint Annotations

Use the @IntRange, @FloatRange, and @Size annotations to validate the values of passed parameters.

The @IntRange annotation validates that the parameter value is within a specified range. The following example ensures that the alpha parameter contains an integer value from 0 to 255:

public void setAlpha(@IntRange(from=0,to=255) int alpha) { … }

The @FloatRange annotation checks that the parameter value is within a specified range of floating point values. The following example ensures that thealpha parameter contains a float value from 0.0 to 1.0:

public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) {...}

The @Size annotation checks the size of a collection or array, as well as the length of a string. For example, use the @Size(min=1) annotation to check if a collection is not empty, and the @Size(2) annotation to validate that an array contains exactly two values. The following example ensures that thelocation array contains at least one element:

int[] location = new int[3];
button.getLocationOnScreen(@Size(min=1) location);

Adding Permission Annotations

Use the @RequiresPermission annotation to validate the permissions of the caller of a method. To check for a single permission from a list the valid permissions, use the anyOf attribute. To check for a set of permissions, use the allOf attribute. The following example annotates the setWallpapermethod to ensure that the caller of the method has the permission.SET_WALLPAPERS permission.

@RequiresPermission(Manifest.permission.SET_WALLPAPER)
public abstract void setWallpaper(Bitmap bitmap) throws IOException;

This example requires the caller of the copyFile() method to have both read and write permissions to external storage:

@RequiresPermission(allOf = {
    Manifest.permission.READ_EXTERNAL_STORAGE,
    Manifest.permission.WRITE_EXTERNAL_STORAGE})
public static final void copyFile(String dest, String source) {
    ...
}

Adding CheckResults Annotations

Use the @CheckResults annotation to validate that a method's result or return value is actually used. The following example annotates thecheckPermissions method to ensure the return value of the method is actually referenced. It also names the enforcePermission method as a method to be suggested to the developer as a replacement.

@CheckResult(suggest="#enforcePermission(String,int,int,String)")
public abstract int checkPermission(@NonNull String permission, int pid, int uid);
@StringDef

Adding CallSuper Annotations

Use the @CallSuper annotation to validate that an overriding method calls the super implementation of the method. The following example annotates theonCreate method to ensure that any overriding method implementations call super.onCreate().

@CallSuper
protected void onCreate(Bundle savedInstanceState) {
}

Creating Enumerated Annotations

Use the @IntDef and @StringDef annotations so you can create enumerated annotations of integer and string sets to validate other types of code references, such as passing references to a set of constants.

The following example illustrates the steps to create an enumerated annotation that ensures a value passed as a method parameter references one of the defined constants.

import android.support.annotation.IntDef;
...
public abstract class ActionBar {
    ...
    //Define the list of accepted constants
    @IntDef({NAVIGATION_MODE_STANDARD, NAVIGATION_MODE_LIST, NAVIGATION_MODE_TABS})

    //Tell the compiler not to store annotation data in the .class file
    @Retention(RetentionPolicy.SOURCE)

    //Declare the NavigationMode annotation
    public @interface NavigationMode {}

    //Declare the constants
    public static final int NAVIGATION_MODE_STANDARD = 0;
    public static final int NAVIGATION_MODE_LIST = 1;
    public static final int NAVIGATION_MODE_TABS = 2;

    //Decorate the target methods with the annotation
    @NavigationMode
    public abstract int getNavigationMode();

    //Attach the annotation
    public abstract void setNavigationMode(@NavigationMode int mode);

When you build this code, a warning is generated if the mode parameter does not reference one of the defined constants (NAVIGATION_MODE_STANDARD,NAVIGATION_MODE_LIST, or NAVIGATION_MODE_TABS).

You can also define an annotation with a flag to check if a parameter or return value references a valid pattern. This example creates theDisplayOptions annotation with a list of valid DISPLAY_ constants.

import android.support.annotation.IntDef;
...

@IntDef(flag=true, value={
        DISPLAY_USE_LOGO,
        DISPLAY_SHOW_HOME,
        DISPLAY_HOME_AS_UP,
        DISPLAY_SHOW_TITLE,
        DISPLAY_SHOW_CUSTOM
})
@Retention(RetentionPolicy.SOURCE)
public @interface DisplayOptions {}

...

When you build code with an annotation flag, a warning is generated if the decorated parameter or return value does not reference a valid pattern.

来源： https://developer.android.com/studio/write/annotations.html


Design a UI with Layout Editor

In This Document

  1. Editing in the Text View
  2. Editing in the Design View

Android Studio offers an advanced layout editor that allows you to drag-and-drop widgets into your layout and preview your layout while editing the XML.

Within the layout editor, you can switch between the Text view, where you edit the XML file as text, and theDesign view. Just click the appropriate tab at the bottom of the window to display the desired editor.

Editing in the Text View

You can use the Text view to edit your layout file. This section describes some of the features that are available in the Text view.

Preview

While editing in the Text view, you can preview the layout on devices by opening the Preview pane available on the right side of the window. Within thePreview pane, you can modify the preview by changing various options at the top of the pane, including the preview device, layout theme, platform version and more. To see a preview of how your app would look with a particular device skin, click the preview icon [image] and choose the desired device, such as Nexus 4:

Figure 1. Previewing your app.

To preview the layout on multiple devices simultaneously, select Preview All Screen Sizes from the device drop-down.

When you click in the preview image, the layout editor highlights the corresponding section in the XML, and vice-versa.

Interactive error detection and recovery

As you edit the Text view of your layout XML file, Android Studio flags typos and offers assistance.

For example, suppose you are adding a button, and you misspell it as "Buttonn". Android Studio helps you to correct it by displaying an error such as the following, where you can click on "Change to Button" to fix the error in the XML file:

Figure 2. Flagging errors.

Android Studio also prompts you to supply missing information. For example, suppose you start adding a fragment to your layout XML file. First of all, Android Studio displays auto-complete suggestions as you type. Once it becomes clear that you are adding a fragment, Android Studio displays an error panel with links that you can click to supply the missing attributes. Clicking "Automatically add all missing attributes" in this case does just that—it completes the fragment definition in your layout XML file:

Figure 3. Supplying missing information

Picking a theme

To pick a theme for your app, click the Theme icon [image] .

This displays the Select Theme dialog, where you can search for a particular theme and/or select one from the list on the right hand side. The theme you choose will be reflected in the previewed image.

Figure 4. Specifying a theme.

Localization

Android Studio provides built-in localization support. When you click the localization icon [image] , you can select a particular locale, add and edit translations, preview the locales your app supports (all locales or just a single locale), and preview right-to-left layout for languages that are RTL.

See Supporting Different Languages for a description of how to support different locales in your app.

For example, here is a preview of a "Hello World" app for the [image] locale:

Figure 5. Previewing locales.

Editing in the Design View

You can switch to the graphical editor by clicking Design at the bottom of the window. While editing in the Design view, you can show and hide the widgets available to drag-and-drop by clicking Palette on the left side of the window. Clicking Designer on the right side of the window reveals a panel with a layout hierarchy and a list of properties for each view in the layout.

When you drag a widget into the graphical layout for your app, the display changes to help you place the widget. What you see depends on the type of layout. For example, if you're dragging a widget into a FrameLayout, it displays a grid to help you place the widget, as shown in figure 6:

Figure 6. Using the grid layout to place a widget.

Within the graphical editor, you can rearrange your app's UI by dragging widgets to the desired location.

Multi-API Version Rendering

Android Studio supports multi-API version rendering. When you click the Android version icon [image] in the Design view, Android Studio allows you to preview your Android layouts across multiple Android API levels.

Figure 7. Multi-API version rendering.

Taking a snapshot

When you run your app on a connected device, you can take a snapshot of it by clicking the camera icon [image] to the left of the logging panel (at the bottom of the window by default). This takes a snapshot of your running app (or whatever is currently displayed on your device) and displays it in a window. Check Frame Screenshot to show your screenshot within the device skin of your choice. You can also specify whether you want the image to have screen glare and/or a drop shadow. Once you have the desired effect, you can save the image.

You can use the same process to create a snapshot of your app's preview. Just click the camera icon in the preview area and follow the steps for adding a device skin.

来源： https://developer.android.com/studio/write/layout-editor.html


Design App Themes with Theme Editor

  1. Theme Editor Basics
  2. Themes and Colors
  3. Device-Specific Configurations

Android Studio includes a visual assistant called Theme Editor that helps you:

  • Create and modify themes for your app.
  • Adjust themes for different resource classifiers.
  • Visualize the effect of color changes on common UI elements.

    • This page introduces the fundamental tasks that you can perform with the Theme Editor, and explains how to do so.

    Theme Editor Basics

    This section describes how to access the Theme Editor, and how it is laid out.

    Accessing the Theme Editor

    There are two ways to open the Theme Editor:

  • From an open styles XML file, such as styles.xml, click Open editor near the top-right of the file window.
  • From the Tools menu, click Android > Theme Editor.

    Navigating the Theme Editor

    The Theme Editor's main screen is divided into two sections. The left side of the editor shows what specific UI elements, such as the app bar or a raised button, look like when you apply the current theme to them. The right side of the editor displays the name of the current theme being previewed, the module where the theme is defined, and the settings for theme resources, such as Theme parent and colorPrimary. You can modify design themes by changing these resource settings.

    Themes and Colors

    The Theme Editor allows you to create new themes, modify existing ones, and manage the colors that make up the themes.

    Creating New Themes

    To create a theme, follow these steps:

    1. Open the Theme dropdown menu near the top of the right side of the Theme Editor.
    2. Click Create New Theme.
    3. In the New Theme dialog, enter a name for the new theme.
    4. In the Parent theme name list, click on the parent from which the theme inherits initial resources.

    Renaming Themes

    To rename a theme, perform the following steps:

    1. Open the Theme dropdown menu near the top of the right side of the Theme Editor.
    2. Click Rename theme-name.
    3. In the Rename dialog, enter a new name for the theme.
    4. (optional) To see how the changes will look, click Preview.
    5. To apply the changes, click Refactor.

    Changing Color Resources

    To change an existing color resource, such as colorPrimary, follow these steps:

    1. Click the colored square next to the name of the resource you want to change. The Resources dialog appears, which displays a list of colors on the left side, and settings and information for the currently selected resource color on the right.
    2. Set a color for the theme resource by doing one of the following:
      • Select a material palette color from the list of colors.
      • Select a color defined in your project from the list of colors, and optionally modify the color value, opacity, and name as desired.
      • Define a new color in your project by clicking New Resource > New color Value from the drop-down menu in the lower left of the Resources dialog, and specify the color value, opacity, and name.
    3. If you've created or modified a custom project color, you can ensure that the color matches the closest material palette color by clicking CLOSEST MATERIAL COLOR, located next to Custom color. Android Studio changes the color and opacity values of the color you picked to the material color most like it, and replaces Custom color with the name of the color from the material palette.

    Viewing State Lists and Colors

    The Theme Editor allows you to preview colors associated with different states. To do so, open the Resources dialog by clicking on the color set square next to the name of an editable state list resource. The Resources dialog displays a list of states, such as Selected, and the color value associated with the state. Click the color for a state to choose a different color value.

    To more fully control the states themselves, you can directly view and edit their properties in the XML file that defines them. For more information, see the documentation for the ColorStateList class.

    Device-Specific Configurations

    You can choose device-specific configurations for your app to support. Perform the following steps to do so:

    1. Click the triangle next to Device Configuration, near the bottom of the Resources dialog. The Device Configuration section expands, revealing the source set and name of the XML file containing the resource, as well as a list of configuration-specific directories in which to place that file.
    2. If necessary, change the XML file name.
    3. Check the boxes next to the directories corresponding to the device-specific configurations you wish to support. Any configuration for which you do not specify a directory defaults to using the values directory.

    For more information about the relationship between directory names and configurations, see Supporting Multiple Screens. For more information about supported directory names, see Providing Resources.

    来源： https://developer.android.com/studio/write/theme-editor.html


Add Multi-Density Vector Graphics

  1. About Vector Asset Studio
  2. Running Vector Asset Studio
  3. Importing a Vector Graphic
  4. Adding a Vector Drawable to a Layout
  5. Referring to a Vector Drawable in Code
  6. Modifying XML Code Generated by Vector Asset Studio
  7. Deleting a Vector Asset from a Project
  8. Delivering an App Containing Vector Drawables

See also

  1. Create Vector Drawables
  2. Material Icons
  3. Drawable Class
  4. VectorDrawable Class
  5. Android Support Library 23.2

Videos

  1. DevBytes: Android Vector Graphics
  2. Android Studio Support for Vector Graphics

Dependencies and Prerequisites

  • Android Plugin for Gradle 1.5.0 or higher

Android Studio includes a tool called Vector Asset Studio that helps you add material icons and import Scalable Vector Graphic (SVG) files into your project as vector drawable resources. Using vector drawables instead of bitmaps reduces the size of your APK because the same file can be resized for different screen densities without loss of image quality. For older versions of Android that don't support vector drawables, Vector Asset Studio can, at build time, turn your vector drawables into different bitmap sizes for each screen density.

About Vector Asset Studio

Vector Asset Studio adds a vector graphic to the project as an XML file that describes the image. Maintaining one XML file can be easier than updating multiple raster graphics at various resolutions.

Android 4.4 (API level 20) and lower doesn't support vector drawables. If your minimum API level is set at one of these API levels, you have two options when using Vector Asset Studio: generate Portable Network Graphic (PNG) files (the default) or use the Support Library.

For backward-compatibility, Vector Asset Studio generates raster images of the vector drawable. The vector and raster drawables are packaged together in the APK. You can refer to vector assets as Drawable in Java code or @drawable in XML code; when your app runs, the corresponding vector or raster image displays automatically depending on the API level.

To instead use Android Support Library 23.2 or higher, you must add some statements to your build.gradlefile. This technique uses vector drawables only.

Supported vector graphic types

The Google material design specification provides material icons that you can use in your Android apps. Vector Asset Studio helps you choose, import, and size material icons, as well as define opacity and the Right-to-Left (RTL) mirroring setting.

Vector Asset Studio also helps you to import your own SVG files. SVG is an XML-based open standard of the World Wide Web Consortium (W3C). Vector Asset Studio supports the essential standard, but not all features. When you specify an SVG file, Vector Asset Studio gives immediate feedback about whether the graphics code is supported or not. If the SVG code is supported, it converts the file into an XML file containing VectorDrawable code.

For Android 5.0 (API level 21) and higher, you can use the AnimatedVectorDrawable class to animate the properties of VectorDrawable. For more information, see Animate Vector Drawables.

Considerations for SVG files

A vector drawable is appropriate for simple icons. The material icons provide good examples of the types of images that work well as vector drawables in an app. In contrast, many app launch icons do have many details, so they work better as raster images.

The initial loading of a vector graphic can cost more CPU cycles than the corresponding raster image. Afterward, memory use and performance are similar between the two. We recommend that you limit a vector image to a maximum of 200 x 200 dp; otherwise, it can take too long to draw.

Although vector drawables do support one or more colors, in many cases it makes sense to color icons black (android:fillColor="#FF000000"). Using this approach, you can add a tint to the vector drawable that you placed in a layout, and the icon color changes to the tint color. If the icon color isn't black, the icon color might instead blend with the tint color.

Vector drawable backward-compatibility solutions

The following table summarizes the two techniques you can use for backward-compatibility with Android 4.4 (API level 20) and lower:

Technique | Drawables in APK | VectorDrawable XML Elements | Android Plugin for Gradle | Build Flags | App Code
PNG generation | Vector and raster | Subset supported | 1.5.0 or higher | Default | Variety of coding techniques supported
Support Library 23.2 or higher | Vector | Full support | 2.0 or higher | Support Library statements required | Subset of coding techniques supported

Using vector graphics can produce a smaller APK, but the initial loading of vector graphics can take longer.

PNG generation

Android 5.0 (API level 21) and higher provides vector drawable support. If your app has a minimum API level that is lower, Vector Asset Studio adds the vector drawable file to your project; also, at build time, Gradle creates PNG raster images at various resolutions. Gradle generates the PNG densities specified by the Domain Specific Language (DSL) generatedDensities property in a build.gradle file. To generate PNGs, the build system requires Android Plugin for Gradle 1.5.0 or higher.

For Android 5.0 (API level 21) and higher, Vector Asset Studio supports all of the VectorDrawable elements. For backward compatibility with Android 4.4 (API level 20) and lower, Vector Asset Studio supports the following XML elements:

<vector>

  • android:width
  • android:height
  • android:viewportWidth
  • android:viewportHeight
  • android:alpha

<group>

  • android:rotation
  • android:pivotX
  • android:pivotY
  • android:scaleX
  • android:scaleY
  • android:translateX
  • android:translateY

<path>

  • android:pathData
  • android:fillColor
  • android:strokeColor
  • android:strokeWidth
  • android:strokeAlpha
  • android:fillAlpha
  • android:strokeLineCap
  • android:strokeLineJoin
  • android:strokeMiterLimit

Only Android 5.0 (API level 21) and higher supports dynamic attributes, for example, android:fillColor="?android:attr/colorControlNormal".

You can change the XML code that Vector Asset Studio generates, although it’s not a best practice. Changing the values in the code should not cause any issues, as long as they’re valid and static. If you want to add XML elements, you need to make sure that they’re supported based on your minimum API level.

Support Library

This technique requires Android Support Library 23.2 or higher and Android Plugin for Gradle 2.0 or higher, and uses vector drawables only. Before using Vector Asset Studio, you must add a statement to your build.gradle file:

android {
  defaultConfig {
    vectorDrawables.useSupportLibrary = true
  }
}

dependencies {
  compile 'com.android.support:appcompat-v7:23.2.0'
}

You must also use coding techniques that are compatible with the Support Library (including the app:srcCompat attribute). For more information, seeAndroid Support Library 23.2.

Running Vector Asset Studio

To start Vector Asset Studio:

  1. In Android Studio, open an Android app project.
  2. In the Project window, select the Android view.
  3. Right-click the res folder and select New > Vector Asset.

    4. Some other project views and folders have this menu item as well.

    Vector Asset Studio appears.

  4. If a Need newer Android plugin for Gradle dialog appears instead, correct your Gradle version as follows:
    1. Select File > Project Structure.
    2. In the Project Structure dialog, select Project.
    3. In the Android Plugin Version field, change the Android Plugin for Gradle version to 1.5.0 or higher, and click OK.

      4. Gradle syncs the project.

    4. In the Android view of the Project window, right-click the res folder and select New > Vector Asset.

      5. Vector Asset Studio appears.

  5. Continue with Importing a Vector Graphic.

Importing a Vector Graphic

Vector Asset Studio helps you to import a vector graphics file into your app project. Follow one of the following procedures:

  • Adding a material icon
  • Importing an SVG file

Adding a material icon

After you open Vector Asset Studio, you can add a material icon as follows:

  1. In Vector Asset Studio, select Material Icon.
  2. Click Choose.
  3. Select a material icon and click OK.

    4. The icon appears in the Vector Drawable Preview.

  4. Optionally change the resource name, size, opacity, and Right-To-Left (RTL) mirroring setting:
    • Resource name - Type a new name if you don’t want to use the default name. Vector Asset Studio automatically creates a unique name (adds a number to the end of the name) if that resource name already exists in the project. The name can contain lowercase characters, underscores, and digits only.
    • Override default size from material design - Select this option if you want to adjust the size of the image. When you type a new size, the change appears in the preview area.

      • The default is 24 x 24 dp, which is defined in the material design specification. Deselect the checkbox to return to the default.

    • Opacity - Use the slider to adjust the opacity of the image. The change appears in the preview area.
    • Enable auto mirroring for RTL layout - Select this option if you want a mirror image to display when the layout is right to left, instead of left to right. For example, some languages are read right to left; if you have an arrow icon, you might want to display a mirror image of it in this case. Note that if you’re working with an older project, you might also need to add android:supportsRtl="true" to your app manifest. Auto-mirroring is supported on Android 5.0 (API level 21) and higher, and the Support Library.
  5. Click Next.
  6. Optionally change the module and resource directory:
    • Target Module - Select a module in the project where you want to add the resource. For more information, see Add a Module for a New Device.
    • Res Directory - Select the resource source set where you want to add the vector asset: src/main/res, src/debug/res, src/release/res, or a user-defined source set. The main source set applies to all build variants, including debug and release. The debug and release source sets override the main source set and apply to one version of a build. The debug source set is for debugging only. To define a new source set, select File > Project Structure > app > Build Types. For example, you could define a beta source set and create a version of an icon that includes the text "BETA” in the bottom right corner. For more information, see Configure Build Variants.

    The Output Directories area displays the vector image and the directory where it will appear.

  7. Click Finish.

    8. Vector Asset Studio adds an XML file defining the vector drawable to the project in the app/src/main/res/drawable/ folder. From the Android view of the Project window, you can view the generated vector XML file in the drawable folder.

  8. Build the project.

    9. If the minimum API level is Android 4.4 (API level 20) and lower, and you haven't enabled the Support Library technique, Vector Asset Studio generates PNG files. From the Project view of the Project window, you can view the generated PNG and XML files in the app/build/generated/res/pngs/debug/folder.

    You should not edit these generated raster files, but instead work with the vector XML file. The build system regenerates the raster files automatically when needed so you don’t need to maintain them.

Importing a Scalable Vector Graphic (SVG)

After you open Vector Asset Studio, you can import an SVG file as follows:

  1. In Vector Asset Studio, select Local SVG file.

    2. The file must be on a local drive. If it’s located on the network, for example, you need to download it to a local drive first.

  2. Specify an Image file by clicking … .

    3. The image appears in the Vector Drawable Preview.

    However, if the SVG file contains unsupported features, an error appears at the bottom left of Vector Asset Studio, as shown in the following figure.

    In this case, you can’t use Vector Asset Studio to add the graphics file. Click More to view the errors. For a list of supported elements, see Vector Drawable Backward-Compatibility Solutions.

  3. Optionally change the resource name, size, opacity, and Right-To-Left (RTL) mirroring setting:
    • Resource name - Type a new name if you don’t want to use the default name. Vector Asset Studio automatically creates a unique name (adds a number to the end of the name) if that resource name already exists in the project. The name can contain lowercase characters, underscores, and digits only.
    • Override default size from material design - Select this option if you want to adjust the size of the image. After you select it, the size changes to the size of the image itself. Whenever you change the size, the change appears in the preview area.

      • The default is 24 x 24 dp, which is defined in the material design specification. Deselect the checkbox to return to the default.

    • Opacity - Use the slider to adjust the opacity of the image. The change appears in the preview area.
    • Enable auto mirroring for RTL layout - Select this option if you want a mirror image to display when the layout is right to left, instead of left to right. For example, some languages are read right to left; if you have an arrow icon, you might want to display a mirror image of it in this case. Note that if you’re working with an older project, you might need to add android:supportsRtl="true" to your app manifest. Auto-mirroring is supported on Android 5.0 (API level 21) and higher, and the Support Library.
  4. Click Next.
  5. Optionally change the module and resource directory:
    • Target Module - Select a module in the project where you want to add the resource. For more information, see Add an App Module.
    • Res Directory - Select the resource source set where you want to add the vector asset: src/main/res, src/debug/res, src/release/res, or a user-defined source set. The main source set applies to all build variants, including debug and release. The debug and release source sets override the main source set and apply to one version of a build. The debug source set is for debugging only. To define a new source set, select File > Project Structure > app > Build Types. For example, you could define a beta source set and create a version of an icon that includes the text "BETA” in the bottom right corner. For more information, see Configure Build Variants.

    The Output Directories area displays the vector image and the directory where it will appear.

  6. Click Finish.

    7. Vector Asset Studio adds an XML file defining the vector drawable to the project in the app/src/main/res/drawable/ folder. From the Android view of the Project window, you can view the generated vector XML file in the drawable folder.

  7. Build the project.

    8. If the minimum API level is Android 4.4 (API level 20) and lower, and you haven't enabled the Support Library technique, Vector Asset Studio generates PNG files. From the Project view of the Project window, you can view the generated PNG and XML files in the app/build/generated/res/pngs/debug/folder.

    You should not edit these generated raster files, but instead work with the vector XML file. The build system regenerates the raster files automatically when needed so you don’t need to maintain them.

Adding a Vector Drawable to a Layout

In a layout file, you can set any icon-related widget, such as ImageButton, ImageView, and so on, to point to a vector asset. For example, the following layout shows a vector asset displayed on a button:

To display a vector asset on a widget, as shown in the figure:

  1. Open a project and import a vector asset.
  2. In the Android view of the Project window, double-click a layout XML file, such as content_main.xml.
  3. Click the Design tab to display the Layout Editor.
  4. Drag the ImageButton widget from the Palette window onto the Layout Editor.
  5. In the Properties window, locate the src property of the ImageButton instance and click … .
  6. In the Resources dialog, select the Project tab, navigate to the Drawable folder, and select a vector asset. Click OK.

    7. The vector asset appears on the ImageButton in the layout.

  7. To change the color of the image to the accent color defined in the theme, locate the tint property in the Properties window and click … .
  8. In the Resources dialog, select the Project tab, navigate to the Color folder, and select colorAccent. Click OK.

    9. The color of the image changes to the accent color in the layout.

If you're not using the Support Library technique, the ImageButton code should be similar to the following:

<ImageButton
  android:id="@+id/imageButton"
  android:src="@drawable/ic_build_24dp"
  android:tint="@color/colorAccent"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_below="@+id/textView2"
  android:layout_marginTop="168dp" />

Referring to a Vector Drawable in Code

You can normally refer to a vector drawable resource in a generic way in your code, and when your app runs, the corresponding vector or raster image displays automatically depending on the API level:

  • In most cases, you can refer to vector assets as @drawable in XML code or Drawable in Java code.

    • For example, the following layout XML code applies the image to a view:

    <ImageView
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:src="@drawable/myimage" />

    The following Java code retrieves the image as a Drawable:

    Resources res = getResources();
    Drawable drawable = res.getDrawable(R.drawable.myimage);
  • Occasionally, you might need to typecast the drawable resource to its exact class, such as when you need to use specific features of theVectorDrawable class. To do so, you could use Java code such as the following:
    • if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
           VectorDrawable vectorDrawable =  (VectorDrawable) drawable;
    } else {
           BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
    }

For the Support Library technique, you must use coding techniques that are compatible with the Support Library. For more information, see Android Support Library 23.2.

Modifying XML Code Generated by Vector Asset Studio

You can modify the vector asset XML code, but not the PNGs and corresponding XML code generated at build time. However, we don't recommended it.

When using the PNG generation technique, Vector Asset Studio makes sure that the vector drawable and the PNGs match, and that the manifest contains the proper code. If you add code that's not supported on Android 4.4 (API level 20) and lower, your vector and PNG images might differ. You also need to make sure that the manifest contains the code to support your changes.

To modify the vector XML file when you're not using the Support Library technique:

  1. In the Project window, double-click the generated vector XML file in the drawable folder.

    2. The XML file appears in the editor and Preview windows.

  2. Edit the XML code based on what’s supported by the minimum API level:
    • Android 5.0 (API level 21) and higher - Vector Asset Studio supports all of the Drawable and VectorDrawable elements. You can add XML elements and change values.
    • Android 4.4 (API level 20) and lower - Vector Asset Studio supports all of the Drawable elements and a subset of the VectorDrawable elements. SeeVector Drawable Backward-Compatibility Solutions for a list. You can change values in the generated code and add XML elements that are supported. Dynamic attributes aren't supported.

    For example, if you didn’t select the RTL option in Vector Asset Studio but realize you now need it, you can add the autoMirrored attribute later. To view the RTL version, select Preview Right-to-Left Layout in the [image] menu of the Preview window. (Select None to remove the RTL preview.)

    Note: If you’re working with an older project, you might need to add android:supportsRtl="true" to your app manifest. Also, becauseautoMirrored is a dynamic attribute, it's supported on Android 5.0 (API level 21) and higher only.

  3. Build the project and check that the vector and raster images look the same.

    4. Remember that the generated PNGs could display differently in the Preview window than in the app due to different rendering engines and any changes made to the vector drawable before a build. If you add code to the vector XML file created by Vector Asset Studio, any features unsupported in Android 4.4 (API level 20) and lower don't appear in the generated PNG files. As a result, when you add code, you should always check that the generated PNGs match the vector drawable. To do so, you could double-click the PNG in the Project view of the Project window; the left margin of the code editor also displays the PNG image when your code refers to the drawable.

Deleting a Vector Asset from a Project

To remove a vector asset from a project:

  1. In the Project window, delete the generated vector XML file by selecting the file and pressing the Delete key (or select Edit > Delete).

    2. The Safe Delete dialog appears.

  2. Optionally select options to find where the file is used in the project, and click OK.

    3. Android Studio deletes the file from the project and the drive. However, if you chose to search for places in the project where the file is used and some usages are found, you can view them and decide whether to delete the file.

  3. Select Build > Clean Project.

    4. Any auto-generated PNG and XML files corresponding to the deleted vector asset are removed from the project and the drive.

Delivering an App Containing Vector Drawables

If you used the Support Library technique or your minimum API level is Android 5.0 (API level 21) or higher, your APK will contain the vector images that you added with Vector Asset Studio. These APKs will be smaller than if the vector images were converted to PNGs.

When your minimum API level includes Android 4.4 (API level 20) or lower, and you have corresponding vector and raster images in your project, you have two options for delivering your APK files:

  • Create one APK that includes both the vector images and the corresponding raster representations. This solution is the simplest to implement.
  • Create separate APKs for different API levels. When you don’t include the corresponding raster images in the APK for Android 5.0 (API level 21) and higher, the APK can be much smaller in size. For more information, see Multiple APK Support.

来源： https://developer.android.com/studio/write/vector-asset-studio.html


Add Bitmap Images with Image Asset Studio

  1. Accessing Image Asset Studio
  2. Creating Icons
  3. Customizing Icons
  4. Saving Icons
  5. Configuring Build Properties
  6. Referring to an Image Resource in Code
  7. Managing Launcher Icons as mipmap Resources

Android Studio includes a tool called Image Asset Studio that helps you to generate custom icons for your Android applications from existing image, clipart, or text-string resources. It generates a set of icons at the appropriate resolution for each generalized screen density that your app supports. The newly generated icons are placed in density-specific folders (for example, mipmap-mdpi/ or drawable-xxxhdpi/), which reside in the application’s res/ folder. At runtime, Android uses the appropriate resource based on the screen density of the device your application is running on.

Image Asset Studio generates the following asset types:

  • Launcher icons.
  • Action bar and tab icons.
  • Notification icons.

This guide shows how to generate these assets using Image Asset Studio.

Accessing Image Asset Studio

Follow these steps to access Image Asset Studio:

  1. In Android Studio, open an Android app project.
  2. In the Project window on the left side of the screen, select Android from the dropdown menu. The Android project view appears in the pane.
  3. Right-click the res/folder and select New > Image Asset. The Image Asset Studio window appears.

Creating Icons

You can generate icons from image, clipart , or text-string resources. This section explains how to work with each of these resources.

From an image resource

  1. Open the Asset Type dropdown menu and select an icon type.
  2. From the available Foreground options, select Image.
  3. Specify the asset to use by entering a filename in the Image file field or by navigating to and selecting a file via the file browser. Image Asset Studio supports the following file types, in descending order of desirability: PNG, JPG, and GIF.

    The icon to be generated appears in the Preview pane, displayed at sizes corresponding to different screen densities.

    The rest of the settings on this screen are optional. To learn how to customize your icons using these options, see Customizing Icons.

  4. Save your icons to the project folder.

From a clipart resource

  1. Open the Asset Type dropdown menu and select an icon type.
  2. From the available Foreground options, select Clipart. The Choose button appears.
  3. Click Choose. A window containing clipart resources appears.
  4. Select a clipart resource.

    The icon to be generated appears in the Preview pane, displayed at sizes corresponding to different screen densities.

    The rest of the settings on this screen are optional. To learn how to customize your icons using these options, see Customizing Icons.

  5. Save your icons to the project folder.

From a text-string resource

  1. Open the Asset Type dropdown menu and select an icon type.
  2. From the available Foreground options, select Text.
  3. Enter into the Text field the text you want to turn into an icon.

    The icon to be generated appears in the Preview pane, displayed at sizes corresponding to different screen densities.

  4. To change the font, select a font from the Font dropdown menu.

    The rest of the settings on this screen are optional. To learn how to customize your icons using these options, see Customizing Icons.

  5. Save your icons to the project folder.

Customizing Icons

Image Asset Studio lets you customize various visual effects for your icons. The following options are of particular note.

  • Trim surrounding blank space: This option allows you to adjust the margin between the icon graphic and border.
    Figure 1: An icon before and after trimming.
  • Additional Padding: This option allows you to adjust the icon's padding on all four sides. Use the slider to select a value between 0 and 100 pixels. For example, for a 100px X 100px image with padding of 25px, the resulting image is 150px X 150px.
  • Theme: This option allows you to set a theme for your action bar and tab icons. You can tint icons using the HOLO_DARK or HOLO_LIGHT theme or create a custom theme using the color palette.
  • Resource name: This option allows you to specify a resource name other than the default one. If an asset with the specified resource name already exists, Image Asset Studio warns you that it is going to overwrite the existing asset with this one.

Saving Icons

This section explains how to save your icons to the res/ folder. Do so by following these steps:

  1. From the initial screen that appeared when you opened Image Asset Studio, click Next. Image Asset Studio opens a new window.
  2. Confirm the target module and resource directory settings for the icon. If you don't want to use the default target module or resource directory, you can enter your own values for them.
  3. Click Finish. The Image Asset Studio generates new icon files, in PNG format, according to the options you have chosen.

Note: Launcher icon files reside in a different location from that of other icons. They are located in the mipmap/ folder. All other icon files reside in thedrawable/ folder of your project.

Configuring Build Properties

To change the module and resource directory, follow these steps:

  1. In the Target Module field, select a module to add the resource to. For more information, see Add a Module for a New Device.
  2. In the Res Directory field, select an option for where to place the image asset:
    • src/main/res: This source set applies to all build variants, including debug and release.
    • src/debug/res, src/release/res: These source sets override the main source set and apply to one version of a build. The debug source set is for debugging only.
    • User-defined: To define your own source set, select File > Project Structure > app > Build Types. For example, you could define a beta source set and create a version of an icon that includes the text "BETA” in the bottom right corner. For more information, see Work with build variants.

Referring to an Image Resource in Code

After you have an image resource in the res/directory of your project, you can reference it from your Java code or your XML layout using its resource ID.

For example, the following XML references the ic_launcher icon in the mipmap/ folder.

<application android:name="ApplicationTitle"
    android:label="@string/app_label"
    android:icon="@mipmap/ic_launcher" >

The following Java code sets an ImageView to use the drawable/myimage.png resource:

ImageView imageView = (ImageView) findViewById(R.id.myimageview);
imageView.setImageResource(R.drawable.myimage);

Managing Launcher Icons as mipmap Resources

Different home screen launcher apps on different devices show app launcher icons at various resolutions. When app resource optimization techniques remove resources for unused screen densities, launcher icons can wind up looking fuzzy because the launcher app has to upscale a lower-resolution icon for display. To avoid these display issues, apps should use the mipmap/ resource folders for launcher icons. The Android system preserves these resources regardless of density stripping, and ensures that launcher apps can pick icons with the best resolution for display.

Make sure launcher apps show a high-resolution icon for your app by moving all densities of your launcher icons to density-specific res/mipmap/ folders (for example res/mipmap-mdpi/ and res/mipmap-xxxhdpi/). The mipmap/ folders replace the drawable/ folders for launcher icons. For xxhpdi launcher icons, be sure to add the higher resolution xxxhdpi versions of the icons to enhance the visual experience of the icons on higher resolution devices.

Note: Even if you build a single APK for all devices, it is still best practice to move your launcher icons to the mipmap/ folders.

Manifest update

When you move your launcher icons to the mipmap-[density] folders, change the launcher icon references in the AndroidManifest.xml file so your manifest references the mipmap/ location. This example changes the manifest file to reference the ic_launcher icon in the mipmap/ folder.

...
<application android:name="ApplicationTitle"
         android:label="@string/app_label"
         android:icon="@mipmap/ic_launcher" >
         ...

来源： https://developer.android.com/studio/write/image-asset-studio.html


Create Resizable Bitmaps (9-Patch files)

The Draw 9-patch tool is a WYSIWYG editor that allows you to create bitmap images that automatically resize to accommodate the contents of the view and the size of the screen. Selected parts of the image are scaled horizontally or vertically based indicators drawn within the image.

For an introduction to NinePatch graphics and how they work, please read the section about NinePatch Drawables in the Canvas and Drawablesdocument.

Here's a quick guide to create a NinePatch graphic using the Draw 9-patch tool. You'll need the PNG image with which you'd like to create a NinePatch image.

  1. From a terminal, run the draw9patch command from your SDK sdk/tools directory to launch the Draw 9-patch tool.
  2. Drag your PNG image into the Draw 9-patch window (or File > Open 9-patch... to locate the file). Your workspace will now open.

    The left pane is your drawing area, in which you can edit the lines for the stretchable patches and content area. The right pane is the preview area, where you can preview your graphic when stretched.

  3. Click within the 1-pixel perimeter to draw the lines that define the stretchable patches and (optional) content area. Right-click (or hold Shift and click, on Mac) to erase previously drawn lines.
  4. When done, select File > Save 9-patch...

    Your image will be saved with the .9.png file name.

To make sure that your NinePatch graphics scale down properly, verify that any stretchable regions are at least 2x2 pixels in size. Otherwise, they may disappear when scaled down. Also, provide one pixel of extra safe space in the graphics before and after stretchable regions to avoid interpolation during scaling that may cause the color at the boundaries to change.

Note: A normal PNG file (*.png) will be loaded with an empty one-pixel border added around the image, in which you can draw the stretchable patches and content area. A previously saved NinePatch file (*.9.png) will be loaded as-is, with no drawing area added, because it already exists.

Optional controls include:

  • Zoom: Adjust the zoom level of the graphic in the drawing area.
  • Patch scale: Adjust the scale of the images in the preview area.
  • Show lock: Visualize the non-drawable area of the graphic on mouse-over.
  • Show patches: Preview the stretchable patches in the drawing area (pink is a stretchable patch).
  • Show content: Highlight the content area in the preview images (purple is the area in which content is allowed).
  • Show bad patches: Adds a red border around patch areas that may produce artifacts in the graphic when stretched. Visual coherence of your stretched image will be maintained if you eliminate all bad patches.

    来源： https://developer.android.com/studio/write/draw9patch.html


Localize the UI with Translations Editor

  1. About the Translations Editor
  2. Running the Translations Editor
  3. Managing String Resources
  4. Ordering Translation Services

See also

  1. Supporting Different Languages
  2. Localizing with Resources
  3. Providing Resources

If your application supports multiple languages, you need to properly manage your translated string resources. Android Studio provides the Translations Editor to make viewing and managing your translated resources easier.

About the Translations Editor

Translated resources are stored in multiple XML files in multiple directories in your project. Manually finding and editing resource files across many translations can be difficult. Because of this, your application might have missing translations that go unnoticed until after your application has been built and distributed to users.

The Translations Editor lets you view and update all your string resources in one convenient place. The editor gives you a single view of all of your translated resources, making it easy to change or add translations, and even find missing translations.

Figure 1. Manage locales and strings in the Translations Editor.

Running the Translations Editor

Follow these steps to start the Translations Editor:

  1. In the Project window on the left side of Android Studio, select Android from the dropdown list.
  2. Open the res folder, and then open the values folder.
  3. If a strings.xml folder is present, open this folder.
  4. Right-click the strings.xml file (not folder) and select Open Translations Editor.

You can also access the Translations Editor by opening a strings.xml file for editing and clicking the Open editor link, or clicking the globe icon [image] in the Design layout view and choosing Edit Translations.

Managing String Resources

The Translations Editor provides a view of all your string resources and current locale translations. The name of each resource is listed in the Key column, along with a default value for the key, a checkbox to mark the key as untranslatable, and values for each locale translation.

Edit translations by double-clicking on the translation and editing the value directly in the list view, or selecting the translation and editing the Translationfield value at the bottom of the editor. The default value can be edited by double-clicking on the default value or selecting the default value and updating the Default Value field.

If a resource is missing a translation and isn't marked untranslatable, the key name is displayed in red. If you hover over a red resource, Android Studio displays details about the missing translations.

Adding a new string resource

Add a new resource by clicking the add icon [image] . Android Studio prompts you for a key name, default value, and resource folder that contains thestrings.xml file where the new resource is added.

Adding additional locales

Add additional locales by pressing the globe icon [image] and selecting the locale you want to add. The Translations Editor adds the new locale column and creates the translation strings XML file in the appropriate project directory.

The Translations Editor has BCP 47 support, and combines language and region codes into a single selection for targeted localizations.

Ordering Translation Services

Clicking the Order a translation link opens a page in your browser where you can upload string resource XML files and order translation services. App translation services are available from Google Play and other vendors. For more information about Google Play App Translation Services, see the Google Play App Translation Service announcement.

来源： https://developer.android.com/studio/write/translations-editor.html


Add URL and App Indexing Support

  1. Typical Workflow
  2. Adding an Intent Filter for URL Support and Google Search
  3. Adding App Indexing API Skeleton Code to an Activity
  4. Testing a URL
  5. Viewing App Indexing API Messages in the logcat Monitor
  6. Configuring Lint
  7. Performing a Google App Indexing Test

See also

  1. App Indexing
  2. Making Your App Content Searchable by Google
  3. Handling App Links
  4. Improving Your Code with lint
  5. logcat Monitor
  6. Google Search Console
  7. Google Play Services

Video

  1. DevBytes: App Indexing

Dependencies and prerequisites

  • Android 2.3 (API level 9) or higher
  • Android Studio 1.5 or higher
  • Google Play Services 8.1.0 or higher

Android Studio helps you add support for URLs, app indexing, and search functionality to your apps. These features can help to drive more traffic to your app, discover which app content is used most, make it easier for users to find content in an installed app, and attract new users.

Typical Workflow

To use Android Studio to add support for URL, app indexing, and search features to your app:

  1. Add intent filters and code to handle incoming intents.
  2. Associate a website with your app.
  3. Add App Indexing API code.

Intent filters and the App Indexing API are ways to implement URL support and app indexing, but there are other possible implementations as well. See Alternate Android Indexing Methods for more information.

Intent filters for URLs

Android Studio can create a basic intent filter in your manifest that you can customize to define URLs for your app. You can then write Java code in an activity to handle the intent. This implementation lets users directly open the specified app activity by clicking a URL. Users can see the URLs in google.com in a browser, in the Google Search app, and in Google Now on Tap.

Website association with URLs

After setting up URL support for your app, you can associate your website with your app by using the Google Search Console and Google Play Developer Console. Afterward, Google indexes your app for URLs defined in your intent filters and begins to include them in search results. In addition, you can optionally exclude app content from Google Search. After you associate a website with your app, features such as Now on Tap and enhanced search result display (like including your app icon) become available.

As an alternative to associating your app with a website, for Android 6.0 (API level 23) and higher, you can add default handlers and verification for URLs instead.

Chrome displaying google.com serves search results with URLs that are accessible to both signed-in users and those who aren't. Google Search app users must be signed in to see URLs in their search results.

App Indexing API code in activities

Next, if you want to support additional search features, such as autocompletions, you can add App Indexing API code to your app. Android Studio can create skeleton code in an activity that you can then customize to support app indexing. The App Indexing API allows app indexing even if Googlebotcan’t get content from your app.

URL support and App Indexing API testing

Android Studio helps you test your code with the following features:

  • URL support testing helps you verify that a specified URL can launch an app.
  • The logcat Monitor helps you test App Indexing API calls in an activity.
  • The Android Lint tool has warnings for certain issues involving URL support and the App Indexing API. These warnings and errors appear in the Code Editor and in Lint inspection results.
  • A Google App Indexing test checks whether Google can index a URL by either crawling your app page or using the App Indexing API.

The details for implementing URL support and app indexing are described next.

Adding an Intent Filter for URL Support and Google Search

To use Android Studio features to add an intent filter defining a URL:

  1. In the Android view of the Project window, double-click the AndroidManifest.xml file to open it in the Code Editor.
  2. Insert an intent filter in one of the following ways:
    • In an <activity> element, click in the left column so the light bulb [image] appears. Click [image] and select Create URL.
    • Right-click in an <activity> element and select Generate > URL.
    • Place your cursor in an activity, and then select Code > Generate > URL.

    The Code Editor adds skeleton code using the intention action and generate code mechanisms.

    The Code Editor adds an intent filter similar to the following:

    <!-- ATTENTION: This intent was auto-generated. Follow instructions at
     https://g.co/AppIndexing/AndroidStudio to publish your URLs. -->
    <intent-filter>
           <action android:name="android.intent.action.VIEW" />

           <category android:name="android.intent.category.DEFAULT" />
           <category android:name="android.intent.category.BROWSABLE" />
           <!-- ATTENTION: This data URL was auto-generated.
         We recommend that you use the HTTP scheme.
         TODO: Change the host or pathPrefix as necessary. -->
           <data
               android:host="www.example.com"
               android:pathPrefix="/gizmos"
               android:scheme="http" />
    </intent-filter>
  3. Modify the <data> element and optionally the <category> element, as needed.

    4. We recommend that you define a <data> element that supports URLs that you’ll add in the future. In the previous sample code, for example, Google will index any URLs starting with http://www.example.com/gizmos. Also, remember to include a URL for your app home screen so it’s included in search results.

    The URLs you specify in your intent filters can be the same as the URLs of the comparable pages on your website.

  4. In the corresponding activity, add Java code to read data from the intent filter and direct the app to respond accordingly.
  5. Test your URL.

To support Google Search for your URLs:

  1. Define an association between your app and your website.

    2. Alternatively, for Android 6.0 (API level 23) and higher, add link default handling and verification.

  2. Optionally exclude certain URLs from the Google index.
  3. Optionally add App Indexing API code to support additional search features.

To test and debug your links, you can use the following Android Studio features:

  • Launch your URL in Android Studio to test that it works.
  • Enable the following Android Lint categories:
    • Missing support for Google App Indexing
    • URL not supported by app for Google App Indexing
  • Perform a Google App Indexing Test.

In addition, you can preview your APK in the Google Search Console to test your URLs, whether the app is associated with a website or not.

Adding App Indexing API Skeleton Code to an Activity

After adding URL support to your app, you can add App Indexing API code to an activity to support additional search features.

To add App Indexing API code to an activity:

  1. In Android view in the Project window, double-click the activity Java file to open it in the Code Editor.
  2. Insert skeleton code in one of the following ways:
    • In an activity definition, click in the Java code so the light bulb [image] appears. Click [image] and select Insert App Indexing API Code.
    • Right-click in an activity definition and select Generate > App Indexing API Code.
    • Place the cursor in an activity, and then select Code > Generate > App Indexing API Code.

    The Code Editor adds skeleton code using the intention action and generate code mechanisms.

    If you don’t see the App Indexing API Code menu item, make sure your cursor is within an activity, and check your code for App Indexing API methods. The Code Editor can insert skeleton Java code into an activity in the following circumstances:

    • The activity doesn’t have an onStart() method, or the onStart() method doesn’t contain an AppIndexApi.start() or AppIndexApi.view() call.
    • The activity doesn’t have an onStop() method, or the onStop() method doesn’t contain an AppIndexApi.end() or AppIndexApi.viewEnd() call.

    The Code Editor adds Java code similar to the following:

       /**
        * ATTENTION: This was auto-generated to implement the App Indexing API.
        * See https://g.co/AppIndexing/AndroidStudio for more information.
        */
           private GoogleApiClient client;

               // ATTENTION: This was auto-generated to implement the App Indexing API.
               // See https://g.co/AppIndexing/AndroidStudio for more information.
           client     = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
           }

           @Override
           public void onStart() {
               super.onStart();

               // ATTENTION: This was auto-generated to implement the App Indexing API.
               // See https://g.co/AppIndexing/AndroidStudio for more information.
           client    .connect();
               Action viewAction = Action.newAction(
                       Action.TYPE_VIEW, // TODO: choose an action type.
                       "Main Page", // TODO: Define a title for the content shown.
                       // TODO: If you have web page content that matches
                       // this app activity's content,
                       // make sure this auto-generated web page URL is correct.
                       // Otherwise, set the URL to null.
                       Uri.parse("http://www.example.com/gizmos"),
                       // TODO: Make sure this auto-generated app URL is correct.
                       Uri.parse("android-app://com.example/http/www.example.com/gizmos")
               );
               AppIndex.AppIndexApi.start(client, viewAction);
           }

           @Override
           public void onStop() {
               super.onStop();

               // ATTENTION: This was auto-generated to implement the App Indexing API.
               // See https://g.co/AppIndexing/AndroidStudio for more information.
               Action viewAction = Action.newAction(
                       Action.TYPE_VIEW, // TODO: choose an action type.
                       "Main Page", // TODO: Define a title for the content shown.
                       // TODO: If you have web page content that matches
                       // this app activity's content,
                       // make sure this auto-generated web page URL is correct.
                       // Otherwise, set the URL to null.
                       Uri.parse("http://www.example.com/gizmos"),
                       // TODO: Make sure this auto-generated app URL is correct.
                       Uri.parse("android-app://com.example/http/www.example.com/gizmos")
               );
               AppIndex.AppIndexApi.end(client, viewAction);
           client    .disconnect();
           }
    }

    For more information about the App Indexing API methods, see Android API for App Indexing. For information about the action types, see theAction Class Constant Summary.

    If your app isn’t already configured for the Google Play Services App Indexing API, the Code Editor also modifies your build.gradle andAndroidManifest.xml files to include it. If your app already depends on it but the version is lower than 8.1.0, your app is upgraded to version 8.1.0. For more information and to correct any issues, see Add Google Play Services and Setting Up Google Play Services.

  3. Customize the skeleton code, as needed.

    4. Pay attention to the comments, which help you find areas that need work, such as setting the title and URLs. For more information, see Add the App Indexing API.

  4. Verify that your app indexing code is working by using the logcat Monitor.

To test and debug your App Indexing API code, you can use the following Android Studio features:

  • Examine logcat Monitor Messages.
  • Enable the following Android Lint category: Missing support for Google App Indexing API
  • Perform a Google App Indexing Test.

In addition, you can preview your APK in the Google Search Console.

Testing a URL

When you run your app from Android Studio, you can specify a URL to launch so you can test it.

To launch a URL from Android Studio:

  1. In Android Studio, open your project in Android view.
  2. After opening a project, select Run > Edit Configurations.
  3. In the Run/Debug Configurations dialog, beneath Android Application, select the module you want to test.
  4. Select the General tab.
  5. In the Launch field, select URL.
  6. In the URL field, click … to select from a list of defined URLs.

    7. Or type the URL you want to test, for example, http://example.com/gizmos.

  7. Click OK.
  8. Select Run > Run app or Debug app.
  9. If the Select Deployment Target dialog appears, select a connected device or an emulator, and click OK.

    10. If the link is successful, the app launches in the device or emulator, and displays the app at the specified activity. Otherwise, an error message appears in the Run window.

For more information about creating run configurations at the project, default, and module levels, see Build and Run Your App.

You can view App Indexing API log messages while the app is running, as described next.

Viewing App Indexing API Messages in the logcat Monitor

The logcat Monitor can display app indexing log messages to determine if your App Indexing API code is pushing the correct data to the cloud. For example, you can check the app title and the URL. The logcat Monitor is part of Android Monitor in Android Studio.

To view App Indexing API messages in the logcat Monitor:

  1. Run your app in Android Studio so it launches a URL.
  2. Display Android Monitor and click the logcat tab.
  3. Set the log level to Verbose.
  4. In the filter menu, select No Filters.
  5. Search the log for the string "appindex".

    6. App indexing log messages should appear. If they don’t, check the following items:

    • Is Google Play Services installed on the device or emulator? You can check the settings on the device.
    • Is the Google Play Services version on the device or emulator lower than the version specified in the build.gradle file? If so, it might be out-of-date and should be upgraded to a higher version.

    For more information, see the Google Play Services Download page and Setting Up Google Play Services.

  6. Visit app pages that trigger App Indexing API calls.

Configuring Lint

You can use the Android Studio built-in Lint tool to check whether you have valid URLs defined in the manifest and have implemented the App Indexing API correctly in activities.

You can view URL and app indexing warnings and errors in two ways:

  • As pop-up text in the Code Editor. When Lint finds a problem, it highlights the problematic code in yellow, or underlines the code in red for more serious issues.
  • In the Lint Inspection Results window after you select Analyze > Inspect Code.

To set default Lint checks for URLs and the App Indexing API:

  1. In Android Studio, open your project in Android view.
  2. Select File > Other Settings > Default Settings.
  3. In the Default Preferences dialog, select Editor > Inspections.
  4. In the Profile field, select Default or Project Default to set the scope for Android Studio or just for this project, respectively.
  5. Expand the Android Lint category and change the Lint settings as needed:
    • Missing support for Google App Indexing - Reports a warning if the app hasn’t implemented URLs, which are used by Google Search. This warning setting is enabled by default.
    • Missing support for Google App Indexing API - Reports if an app hasn’t implemented the App Indexing API at all. This warning setting is disabled by default.
    • URL not supported by app for Google App Indexing - Reports URL errors in manifest code. This error setting is enabled by default.

    For example, the following Lint warning appears for the first setting:

  6. Click OK.

To produce a list of Lint checks displayed in the Inspection Results window:

  1. In Android Studio, open your project in Android view and select a portion of your project that you want to test.
  2. Select Analyze > Inspect Code.
  3. In the Specify Inspection Scope dialog, select the inspection scope and profile.

    4. The scope specifies the files you want to analyze, and the profile specifies the Lint checks you’d like to perform.

  4. If you want to change the Lint settings, click …. In the Inspections dialog, optionally click Manage to define a new profile, specify the Lint settings you want, and then click OK.

    5. In the Inspections dialog, you can search for the string "app indexing" to find the URL and App Indexing API Lint checks. Note that changing Lint settings for a profile in the Inspections dialog doesn’t change the default settings, as described in the previous procedure. It does change the settings for profiles displayed in the Inspections dialog, however.

  5. Click OK.

    6. The results appear in the Inspection Results window.

Performing a Google App Indexing Test

You can use a Google App Indexing Test to check whether Google can index a URL by either crawling your app page or using the App Indexing API. Google can index the URL if your app supports at least one of the following:

  • Googlebot can open and crawl the page identified by the URL.
  • Your app sends the correct data by using the App Indexing API.

To perform a Google App Indexing Test:

  1. Add URL and App Indexing API support to your app.
  2. While your project is open in Android Studio, select Tools > Android > Google App Indexing Test.
  3. In the Google App Indexing Test dialog, select a Module, URL, and Language.
  4. Log in if you see a message asking you to log into a Google Cloud Platform account.
  5. In the Google App Indexing Test dialog, click OK.

    6. Android Studio builds the APK and starts the test. The test can take a few minutes to complete. The results appear in a new tab in the Code Editor.

    If the app preview on the right shows the screen that corresponds to the URL you're testing, then Googlebot can find the URL.

  6. Correct any issues the test identifies, and repeat the test as often as needed.

The following table lists common errors and warnings you might encounter.

Warning or Error | Description
Error: Google cannot index this page. | Your app can't be crawled by Googlebot or using the App Indexing API, so Google isn't able to index this app.
Warning: The App URL you sent by using the App Indexing API doesn't match the URL opened. | When calling the App Indexing API, the URL specified in the app must match the opened URL.
Warning: Google cannot index this page using the App Indexing API because the title is empty. | When calling the App Indexing API, the title shouldn't be empty.
Warning: Google can index this page using Googlebot crawling but identified blocked resources. | The app references other resources, and some of them are blocked or temporarily unavailable. If these resources aren't critical, it might not matter. Check the preview on the right to see whether the content displays correctly. To fix this issue, make sure the resources aren't blocked by robots.txt.
Warning: Google cannot index this page using the App Indexing API. | Your app isn’t using the App Indexing API. We recommended adding App Indexing API support to your app.

来源： https://developer.android.com/studio/write/app-link-indexing.html


Run Apps on the Emulator

在 Android Emulator 上运行应用

本文内容

  1. 关于 Android Emulator
  2. 在 Android Emulator 中运行应用
  3. 在不运行应用的情况下启动 Android Emulator
  4. 屏幕导航
  5. 在模拟器中执行基本任务
  6. 使用扩展控件、设置和帮助

另请参阅

  1. Android Emulator 命令行功能
  2. 使用 AVD Manager 管理 AVD

Android Emulator 可以模拟设备并将其显示在您的开发计算机上。利用该模拟器，您可以对 Android 应用进行原型设计、开发和测试，无需使用硬件设备。模拟器支持 Android 电话、平板电脑、Android Wear 和 Android TV 设备，并随附一些预定义的设备类型，便于您快速上手。您可以创建自己的设备定义和模拟器皮肤。

Android Emulator 运行速度快，功能强大且丰富。模拟器传输信息的速度要比使用连接的硬件设备传输快，从而可以加快开发流程。多核特性让模拟器可以充分利用开发计算机上的多核处理器，进一步提升模拟器性能。

关于 Android Emulator

您可以在运行项目时在模拟器上启动应用，也可以将 APK 文件拖动到模拟器上，安装应用。与在硬件设备上一样，将应用安装到虚拟设备后，它将一直保持安装状态，直至您将其卸载或替换。如果需要，您可以测试多个应用（例如您自己的应用或系统应用）彼此之间的协作方式。

众多功能可以助您测试应用

您可以与模拟器互动，就像与硬件设备互动一样，只不过是使用鼠标与键盘、模拟器按钮和控件。模拟器支持虚拟硬件按钮和触摸屏，包括双指操作，以及方向键 (D-pad)、轨迹球、方向轮和各种传感器。您可以根据需要动态调整模拟器窗口的大小、缩小放大、更改屏幕方向，甚至截图。

当您在模拟器上运行应用时，它可以使用 Android 平台的服务调用其他应用、访问网络、播放音频和视频、接受音频输入、存储和检索数据、通知用户，以及渲染图形转换和主题。利用模拟器的控件，您可以轻松发送来电和短信、指定设备的位置、模拟指纹扫描、指定网络速度和状态，以及模拟电池属性。模拟器可以模拟 SD 卡和内部数据存储；您可以将文件（例如图形或数据文件）拖动到模拟器上进行存储。

观看下面的视频，快速地概括了解模拟器的部分功能。

Android Virtual Device 配置

模拟器使用 Android Virtual Device (AVD) 配置确定被模拟设备的外观、功能和系统映像。利用 AVD，您可以定义被模拟设备特定的硬件方面，也可以创建多个配置来测试不同的 Android 平台和硬件排列。

每个 AVD 都可以作为一台独立的设备工作，并拥有专用的用户数据存储空间、SD 卡，等等。当您使用 AVD 配置启动模拟器时，它会从 AVD 目录自动加载用户数据和 SD 卡数据。默认情况下，模拟器将用户数据、SD 卡数据和缓存存储在 AVD 目录中。

要创建和管理 AVD，请使用 AVD Manager。

系统映像

Android Emulator 运行完整的 Android 系统堆栈（一直深入至内核级别），此堆栈包含一套预安装的应用（例如拨号器），您可以从自己的应用访问这些应用。创建 AVD 时，您可以选择要在模拟器中运行哪个版本的 Android 系统。

通过 AVD Manager 获得的 Android 系统映像包含适用于 Android Linux 内核、原生库、VM 和各种 Android 软件包（例如 Android 框架和预安装应用）的代码。

依赖项和先决条件

本页面介绍的 Android Emulator 版本具有以下要求：

  • Android Studio 2.0 或更高版本
  • SDK Tools 25.0.10 或更高版本
  • 新创建的 AVD，用于替换 24.0.x 或更低版本模拟器的任何 AVD
  • 特定操作所需的活动网络连接，例如测试需要网络连接的应用功能
  • 通过 Tools > Android > Enable ADB Integration 启用 ADB 集成

不支持的功能

Android Emulator 支持设备的大多数功能，不过虚拟硬件不包含以下功能：

  • WLAN
  • 蓝牙
  • NFC
  • SD 卡插入/弹出
  • 连接到设备的耳机
  • USB

Android Wear 的手表模拟器不支持“概览”（最近使用的应用）按钮、D-pad 和指纹传感器。

尽管电话和平板电脑的大多数最终用户都倾向于使用较低的 API 级别，但 Android Wear 和 Android TV 用户更愿意使用最新的版本。使用最新版本可以为您带来更好的模拟器使用体验。

在 Android Emulator 中运行应用

您可以从 Android Studio 项目中运行应用。或者，您也可以运行已经安装到模拟器上的应用，就像在设备上运行任何应用一样。

要在您的项目中启动模拟器并运行应用，请执行以下操作：

  1. 打开一个 Android Studio 项目并点击 Run [image] 。

    2. 将显示 Select Deployment Target 对话框。

  2. 如果您在对话框的顶部看到错误或警告消息，请点击链接，纠正问题或者了解更多信息。

    3. No USB devices or running emulators detected 警告表示您当前未运行任何模拟器，或者检测到有硬件设备连接到您的计算机。如果您未将硬件设备连接到计算机或者已经运行模拟器，可以忽略此警告。

    不过，您必须修正某些错误才能继续，例如某些 Hardware Accelerated Execution Manager (Intel? HAXM) 错误。

  3. 在 Select Deployment Target 对话框中，选择一个现有的模拟器定义，然后点击 OK。

    如果您未看到想要使用的定义，请点击 Create New Emulator 以启动 AVD Manager。定义新的 AVD 后，在 Select Deployment Target 对话框中点击OK。

    如果您想要将此模拟器定义用作项目的默认设置，请选择 Use same selection for future launches。

    模拟器将启动并显示您的应用。

  4. 在模拟器中测试您的应用。

    5. 您可以使用以下部分中介绍的功能：

    • 屏幕导航
    • 在模拟器中执行基本任务
    • 使用扩展控件、设置和帮助
  5. 要关闭模拟器，请点击 Close [image] 。

    6. 模拟器设备会存储已安装的应用，因此，您可以根据需要再次运行。要移除应用，您需要将其卸载。如果您在相同的模拟器上重新运行项目，系统会使用新版本替换应用。

在不运行应用的情况下启动 Android Emulator

要启动模拟器，请执行以下操作：

  1. 打开 AVD Manager。
  2. 双击 AVD，或者点击 Run [image] 。

    3. 将显示 Android Emulator。

    在模拟器运行时，您可以运行 Android Studio 项目并选择模拟器作为目标设备。您也可以将一个或多个 APK 拖动到模拟器上进行安装，然后运行这些应用。

屏幕导航

使用计算机鼠标指针可以模仿您的手指在触摸屏上的操作；选择菜单项和输入字段，以及点击按钮和控件。使用您的计算机键盘键入字符和输入模拟器快捷键。

功能 | 说明
滑动屏幕 | 指向屏幕，按住主鼠标按钮，在屏幕上滑动，然后释放。
拖动对象 | 指向屏幕上的某个对象，按住主鼠标按钮，移动对象，然后释放。
点按 （触摸） | 指向屏幕，按主鼠标按钮，然后释放。例如，您可以点击某个文本字段以开始输入内容，选择某款应用，或者按某个按钮。
点按两次 | 指向屏幕，快速按两次主鼠标按钮，然后释放。
触摸并按住 | 指向屏幕上的某个对象，按主鼠标按钮，保持一段时间，然后释放。例如，您可以打开某个对象的选项。
键入 | 您可以使用计算机键盘或者模拟器屏幕上弹出的键盘在模拟器中键入内容。例如，选择某个文本字段后，您可以在其中键入内容。
双指张合 | 按 Ctrl 或 Command (?) 可以调出张合手势多点触控界面。鼠标作为第一根手指，鼠标关于锚点对称的点为第二根手指。拖动光标，移动第一个点。 点击鼠标左按钮相当于同时触摸两个点，释放按钮则相当于张开两根手指。

在模拟器中执行基本任务

模拟器右侧的面板让您可以执行各种任务。您也可以将文件拖动到模拟器上，安装应用和下载文件。

功能 | 说明 | 键盘快捷键
Close
关闭模拟器。
Minimize
将模拟器窗口最小化。
Resize | 像调整任何其他操作系统窗口一样调整模拟器的大小。模拟器将保持适合您的设备的宽高比。 | ?↑ 和 ?↓
Power
点击可以开启或关闭屏幕。
点击并按住可以开启或关闭设备。
Ctrl + P
?P
Volume Up
点击可以显示一个滑块控件并将音量调高。再次点击可以进一步调高音量，也可以使用滑块控件更改音量。
Ctrl + =
?=
Volume Down
点击可以显示一个滑块控件并将音量调低。再次点击可以进一步调低音量，也可以使用滑块控件更改音量。
Ctrl + -
?-
Rotate Left
将电话逆时针旋转 90 度。
Ctrl + 左箭头
?←
Rotate Right
将电话顺时针旋转 90 度。
Ctrl + 右箭头
?→
Take Screenshot
点击可以对设备进行屏幕截图。默认保存位置为计算机桌面。要更改保存位置，请选择 … > Settings。模拟器将创建一个名为 Screenshot_yyyymmdd-hhmmss.png 的文件，并显示截图的年份、月份、日期、时、分、秒，例如Screenshot_20160219-145848.png。
Ctrl + S
?S
Enter Zoom Mode

点击，使光标变为缩放图标：

  • 点击鼠标左键可以放大，增量为 25%，最大可以放大至虚拟设备屏幕分辨率的两倍。
  • 点击鼠标右键可以缩小。
  • 点击鼠标左键并拖动可以选择要放大的框形区域。
  • 点击鼠标右键并拖动出一个选择框可以重置为默认缩放。
  • 处于缩放模式时，在按住 Ctrl 键的同时触摸屏幕。

再次点击 Enter Zoom Mode 图标可以返回正常的屏幕尺寸。

Ctrl + Z
?Z
处于缩放模式时：
Ctrl + 上箭头
Ctrl + 下箭头
Ctrl + Shift + 上箭头
Ctrl + Shift + 下箭头
Ctrl + Shift + 左箭头
Ctrl + Shift + 右箭头
?↑ 和 ?↓
??↑ 和 ??↓
??← 和 ??→
Back
返回上一个屏幕，或者关闭对话框、选项菜单、“通知”面板或屏幕上的键盘。
Ctrl + 退格键
??
Home
返回主屏幕。按住该图标可以打开特定于 API 级别的对象。
Ctrl + H
??H
Overview
（最近使用的应用）
点按该图标可以打开您最近所使用应用的缩略图列表。要打开某款应用，请点按相应的应用。要从列表中移除某个缩略图，请将相应缩略图向左或向右滑动。Android Wear 不支持此按钮。
Ctrl + O
?O
菜单 键入键盘快捷键可以模拟“菜单”按钮，例如，打开所选应用的菜单。
Ctrl + M
?M
More
点击该图标可以访问下一个表格中介绍的其他功能与设置。
安装 APK | 将 APK 文件拖动到模拟器屏幕上。将显示 APK 安装程序对话框。安装完成后，您可以在应用列表中查看应用。如果出现显示“APK failed to install.”的对话框，则说明应用安装失败。
添加文件 | 将任意文件拖动到模拟器屏幕上。文件将保存到 /sdcard/Download 目录中。使用适合 API 级别的方法导航到文件。例如，对于 API 22，导航路径为：Settings > Device:Storage & USB > Internal Storage > Explore（虚拟 SD 卡）。
切换轨迹球模式 | F6

使用扩展控件、设置和帮助

利用扩展控件，您可以发送数据、更改设备属性和控制应用，等等。要访问这些控件，请在模拟器面板中选择 …，然后在 Extended Controls 对话框的左侧面板中选择您需要的选项。

功能 说明 键盘快捷键
Location

利用模拟器，您可以模拟“我的位置”信息：被模拟设备当前所处的位置。例如，如果您在 Google 地图中点击 My Location [image] ，然后发送一个位置，地图将显示该位置。

要发送一个 GPS 位置，请执行以下操作：

  1. 选择 Decimal 或 Sexagesimal。
  2. 指定位置。

    3. 在十进制模式下，输入一个介于 -90.0 至 +90.0 度范围内的 Latitude 值，以及一个介于 -180.0 至 +180.0 度范围内的Longitude 值。

    在六十进制模式下，输入一个介于 -90 至 +90 度、0 至 59 分和 0.0 至 60.0 秒的三部分 Latitude 值。输入一个介于 -180 至 +180 度、0 至 59 分和 0.0 至 60.0 秒的 Longitude 值。

    对于纬度，- 表示南纬，+ 表示北纬；对于经度，- 表示西经，+ 表示东经。+ 可选。

    （可选）指定一个介于 -1,000.0 至 +10,000.0 范围内的 Altitude 值。

  3. 点击 Send。

要使用 GPS 交换格式 (GPX) 或 Keyhole 标记语言 (KML) 文件，请执行以下操作：

  1. 点击 Load GPX/KML。
  2. 在文件对话框中，选择计算机上的一个文件，然后点击 Open。
  3. （可选）选择一个 Speed 值。

    4. 速度默认采用 Delay 值 (Speed 1X)。您可以将速度设为两倍 (Speed 2X)、三倍 (Speed 3X)，等等。

  4. 点击 Run [image] 。
Ctrl + Shift + L
??L
Cellular

利用模拟器，您可以模拟各种网络条件。您可以大致确定不同网络协议的网络速度，或者指定 Full，这样将以计算机允许的最大速度传输数据。指定任何一种网络协议后的传输速度都会比 Full 慢。您还可以指定语音和数据网络状态，例如漫游。默认值在 AVD 中设置。

选择 Network type：

  • GSM - Global System for Mobile Communications
  • HSCSD - High-Speed Circuit-Switched Data
  • GPRS - Generic Packet Radio Service
  • EDGE - Enhanced Data rates for GSM Evolution
  • UMTS - Universal Mobile Telecommunications System
  • HSPDA - High-Speed Downlink Packet Access
  • Full (default)

选择 Voice status、Data status（或两者）：

  • Home (default)
  • Roaming
  • Searching
  • Denied (emergency calls only)
  • Unregistered (off)
Ctrl + Shift + C
??C
Battery

您可以模拟设备的电池属性，了解应用在不同条件下的运行情况。要选择 Charge level，请使用滑块控件。

选择一个 Charger connection 值：

  • None
  • AC charger

选择一个 Battery health 值：

  • Good (default)
  • Failed
  • Dead
  • Overvoltage
  • Overheated
  • Unknown

选择一个 Battery status 值：

  • Unknown
  • Charging (default)
  • Discharging
  • Not charging
  • Full
Ctrl + Shift + B
??B
Phone

利用模拟器，您可以模拟来电和短信。请注意，信息流是单向的，方向为从控件到模拟器。例如，如果模拟器挂断电话，控件不会更改其状态；您需要在控件中结束通话。

要呼叫模拟器，请执行以下操作：

  1. 在 From 字段中选择或键入电话号码。
  2. 点击 Call Device。
  3. （可选）点击 Hold Call，保持通话。
  4. 要结束通话，请点击 End Call。

要想模拟器发送短信，请执行以下操作：

  1. 在 From 字段中选择或键入电话号码。
  2. 在 SMS message 字段中键入消息。
  3. 点击 Send Message。
Ctrl + Shift + P
??P
Directional Pad

如果 AVD 在硬件配置中已启用方向键，您可以将方向键控件与模拟器搭配使用。不过，并不是所有设备都支持方向键，例如 Android 手表。按钮可以模拟以下操作：

Ctrl + Shift + D
??D
Fingerprint

此控件可以模拟 10 种不同的指纹扫描。您可以使用他测试您的应用中的指纹集成。Android Wear 不支持此功能。

要在虚拟设备上模拟指纹扫描，请执行以下操作：

  1. 准备一款应用来接收指纹。
  2. 选择 Fingerprint 值。
  3. 点击 Touch Sensor。
Ctrl + Shift + F
??F
Settings

您可以指定以下设置：

  • Emulator window theme - 选择 Light 或 Dark。
  • Send keyboard shortcuts to - 默认情况下，某些键盘组合会触发模拟器控件快捷键。如果您正在开发的应用（例如面向带有蓝牙键盘的设备的应用）包含键盘快捷键，您可以更改此设置，将所有键盘输入发送到虚拟设备，包括在模拟器将是快捷键的输入。
  • Screenshot save location - 点击文件夹图标，指定一个位置来保存模拟器的屏幕截图。
  • Use detected ADB location - 如果您正在从 Android Studio 运行模拟器，那么应当选择此设置（默认）。如果您从 Android Studio 外部运行模拟器并且想要其使用特定的 ADB 可执行文件，请取消选择此选项并指定 SDK Tools 位置。如果此设置不正确，拖放应用安装与文件复制以及屏幕截图等功能将无法使用。
  • When to send crash reports - 选择 Always、Never 或 Ask。
Ctrl + Shift + S
??S
Help > Keyboard Shortcuts

了解模拟器接受的键盘快捷键。要使快捷键能够工作，您需要进行以下操作：

  • 选择 Settings > Send keyboard shortcuts to > Emulator controls (default)。
F1
?/
Help > Emulator Help

要访问模拟器的在线文档，请点击 Documentation。

要提交模拟器的错误，请点击 File a Bug。

要提供建议，请点击 Send Feedback。

所有这些链接都需要互联网连接和浏览器才能访问。

F1
?/
Help > About

了解模拟器使用哪个 ADB 端口，以 Android 和模拟器版本号。将最新可用的模拟器版本号与您的版本比较，确定您是否安装了最新的软件。

模拟器序列号为 emulator-adb_port，您可以将其指定为 ADB 命令行选项。

F1
?/

来源： https://developer.android.com/studio/run/emulator.html


Create and Manage Virtual Devices

创建和管理虚拟设备

本文内容

  1. 关于 AVD
  2. 查看和管理您的 AVD
  3. 创建 AVD
  4. 创建硬件配置文件
  5. 使用现有的 AVD
  6. 使用现有的硬件配置文件
  7. 运行和停止模拟器，并清除数据
  8. 导入和导出硬件配置文件
  9. 硬件配置文件属性
  10. AVD 属性
  11. 创建模拟器皮肤

依赖项和先决条件

  • Android Studio 2.0 或更高版本
  • SDK Tools 25.0.10 或更高版本
  • 通过 Tools > Android > Enable ADB Integration 启用 ADB 集成

利用 Android Virtual Device (AVD) 定义，您可以定义您想要在 Android Emulator 中模拟的 Android 电话、平板电脑、Android Wear 或 Android TV 设备的特征。AVD Manager 可以帮助您轻松地创建和管理 AVD。

要高效地测试应用，您需要创建 AVD，AVD 能够模拟应用设计支持的每个设备类型。例如，我们建议您针对等于或高于为 minSdkVersion 所指定值的每个 API 级别创建 AVD。通过使用高于应用所需的 API 级别进行测试，您可以确保应用在用户下载系统更新后的向前兼容性。

关于 AVD

AVD 包括硬件配置文件、系统映像、存储区域、皮肤和其他属性。

硬件配置文件定义了设备出厂时的特征。AVD Manager 会预加载特定的硬件配置文件，如 Nexus 电话设备，您可以根据需要定义和导入硬件配置文件。如果需要，您可以替换 AVD 中的一些设置。

AVD Manager 会提供一些推荐，帮助您为 AVD 选择系统映像。利用 AVD Manager，您也可以下载系统映像，一些映像具有应用需要的插件库，如 Google API。请注意，x86 系统映像在模拟器中运行得最快。

AVD 在您的开发机器上有专门的存储区域，可以存储设备用户数据，如已安装的应用和设置，以及模拟 SD 卡。

模拟器皮肤指定了设备的外观。AVD Manager 会提供一些预定义的皮肤。您也可以自己定义皮肤，或者使用第三方提供的皮肤。

就像在真实设备上一样，对于要使用在 AVD 中定义的某些功能（例如相机）的应用，应用清单中必须具有相应的 <uses-feature> 设置。

查看和管理您的 AVD

AVD Manager 让您可以在一个位置管理 AVD。

要运行 AVD Manager，请执行以下操作：

  • 在 Android Studio 中，选择 Tools > Android > AVD Manager。
  • 点击工具栏中的 AVD Manager [image] 。

将显示 AVD Manager。

AVD Manager 会显示您已定义的任何 AVD。首次安装 Android Studio 时，会创建一个 AVD。如果已为 Android Emulator 24.0.x 或更低版本定义了 AVD，您需要重新创建它们。

从此页面中，您可以进行以下操作：

  • 定义新的 AVD 或硬件配置文件。
  • 编辑现有 AVD 或硬件配置文件。
  • 删除 AVD 或硬件配置文件。
  • 导入或导出硬件配置文件定义。
  • 运行 AVD 以启动模拟器。
  • 停止模拟器。
  • 清除数据，然后从您首次运行模拟器的状态重新开始。
  • 在磁盘上显示关联的 AVD .ini 和 .img 文件。
  • 查看 AVD 配置详细信息，您可以在提交给 Android Studio 团队的任何错误报告中包含这些信息。

创建 AVD

您可以从头创建新的 AVD，也可以复制 AVD，然后更改一些属性。

要创建新的 AVD，请执行下列操作：

  1. 在 AVD Manager 的 Your Virtual Devices 页面中，点击 Create Virtual Device。

    2. 或者，从 Android Studio 中运行您的应用。在 Select Deployment Target 对话框中，点击 Create New Emulator。

    将显示 Select Hardware 页面。

  2. 选择硬件配置文件，然后点击 Next。

    3. 如果您没有看到想要的硬件配置文件，可以创建或导入硬件配置文件。

    将显示 System Image 页面。

  3. 选择针对特定 API 级别的系统映像，然后点击 Next。

    4. Recommended 标签会列出推荐的系统映像。其他标签包含更完整的列表。右窗格中介绍了选定的系统映像。x86 映像在模拟器中运行得最快。

    如果您在系统映像旁看到 Download 链接，点击它可以下载相应的系统映像。您必须连接到互联网才能下载。

    目标设备的 API 级别非常重要，因为您的应用将无法在 API 级别低于应用所需级别（在应用清单文件的 minSdkVersion 属性中定义）的系统映像上运行。有关系统 API 级别与 minSdkVersion 之间关系的更多信息，请参阅管理应用版本。

    如果您的应用在清单文件中声明了 <uses-library> 元素，应用会要求存在外部库的系统映像。如果您想要在模拟器上运行应用，请创建包含所需库的 AVD。为此，您需要使用适用于 AVD 平台的插件组件；例如包含 Google 地图库的 Google API 插件。

    将显示 Verify Configuration 页面。

  4. 根据需要更改 AVD 属性，然后点击 Finish。

    点击 Show Advanced Settings 显示更多设置，如皮肤。

    5. 新 AVD 将显示在 Your Virtual Devices 页面或 Select Deployment Target 对话框中。

要从副本开始创建 AVD，请执行以下操作：

  1. 从 AVD Manager 的 Your Virtual Devices 页面中，右键点击 AVD，然后选择 Duplicate。

    2. 或者点击 Menu [image] ，然后选择 Duplicate。

    将显示 Verify Configuration 页面。

  2. 如果您需要在 System Image 和 Select Hardware 页面上进行更改，请点击 Change 或 Previous。
  3. 进行更改，然后点击 Finish。

    4. AVD 将显示在 Your Virtual Devices 页面中。

创建硬件配置文件

AVD Manager 会为常见设备提供预定义的硬件配置文件，这样您就可以轻松地将它们添加至您的 AVD 定义中。如果您需要定义不同的设备，则可以创建新的硬件配置文件。您可以从头定义新的硬件配置文件，也可以复制硬件配置文件。预加载的硬件配置文件无法编辑。

要从头创建新的硬件配置文件，请执行以下操作：

  1. 在 Select Hardware 页面中，点击 New Hardware Profile。
  2. 在 Configure Hardware Profile 页面中，根据需要更改硬件配置文件属性。
  3. 点击 Finish。

    4. 您的新硬件配置文件将显示在 Select Hardware 页面中。您也可以点击 Next，利用新硬件配置创建 AVD。或者，点击 Cancel 返回至 Your Virtual Devices 页面或 Select Deployment Target 对话框。

要从副本开始创建硬件配置文件，请执行以下操作：

  1. 在 Select Hardware 页面中，选择硬件配置文件，然后点击 Clone Device。

    2. 或者，右键点击硬件配置文件，然后选择 Clone。

  2. 在 Configure Hardware Profile 页面中，根据需要更改硬件配置文件属性。
  3. 点击 Finish。

    4. 您的新硬件配置文件将显示在 Select Hardware 页面中。您也可以点击 Next，利用新硬件配置创建 AVD。或者，点击 Cancel 返回至 Your Virtual Devices 页面或 Select Deployment Target 对话框。

使用现有的 AVD

从 Your Virtual Devices 页面，您可以对现有的 AVD 执行以下操作：

  • 要编辑 AVD，请点击 Edit [image] ，然后进行更改。
  • 要删除 AVD，请右键点击 AVD，然后选择 Delete。或者点击 Menu [image] ，然后选择 Delete。
  • 要在磁盘上显示关联的 AVD .ini 和 .img 文件，请右键点击 AVD，然后选择 Show on Disk。或者点击 Menu [image] ，然后选择 Show on Disk。
  • 要查看 AVD 配置详细信息（您可以将其包含在提交给 Android Studio 团队的任何错误报告中），请右键点击 AVD，然后选择 View Details。或者点击 Menu [image] ，然后选择 View Details。

使用现有的硬件配置文件

从 Select Hardware 页面，您可以对现有的硬件配置执行以下操作：

  • 要编辑硬件配置文件，请选择相应配置文件，然后点击 Edit Device。或者，右键点击硬件配置文件，然后选择 Edit。接下来，进行更改。
  • 要删除硬件配置文件，请右键点击相应配置文件，然后选择 Delete。

您无法编辑或删除预定义的硬件配置文件。

运行和停止模拟器，并清除数据

从 Your Virtual Devices 页面，您可以对模拟器执行以下操作：

  • 要运行使用 AVD 的模拟器，请双击 AVD。或者点击 Run [image] 。
  • 要停止运行的模拟器，请右键点击 AVD，然后选择 Stop。或者点击 Menu [image] ，然后选择 Stop。
  • 要为模拟器清除数据，并返回到首次定义时的状态，请右键点击 AVD，然后选择 Wipe Data。或者点击 Menu [image] ，然后选择 Wipe Data。

导入和导出硬件配置文件

从 Select Hardware 页面，您可以导入和导出硬件配置文件：

  • 要导入硬件配置文件，请点击 Import Hardware Profiles，然后选择您的计算机上包含定义的 XML 文件。
  • 要导出硬件配置文件，请右键点击相应配置文件，然后选择 Export。指定您想要存储包含定义的 XML 文件的位置。

硬件配置文件属性

您可以在 Configure Hardware Profile 页面中指定硬件配置文件的下列属性。AVD 配置属性可以替换硬件配置文件属性，而您在模拟器运行时设置的模拟器属性可以替换前两者。

AVD Manager 包含的预定义硬件配置属性无法编辑。不过，您可以复制它们并编辑副本。

硬件配置文件属性 | 说明
设备名称 | 硬件配置文件的名称。名称可以包含大小写字母、从 0 至 9 的数字、句号 (.)、下划线 (_) 和括号 ( () )。存储硬件配置文件的文件的名称来自硬件配置文件名称。
设备类型 选择下列其中一项：
  • Phone/Tablet
  • Android Wear
  • Android TV
屏幕尺寸 | 屏幕的实际尺寸（单位：英寸），按照对角线测量。如果尺寸大于您的计算机屏幕，启动时尺寸会缩小。
屏幕分辨率 | 输入宽度和高度（单位：像素）指定模拟屏幕上的总像素数。
圆形 | 如果设备（如 Android Wear 设备）具有圆形屏幕，请选择此选项。
存储设备：RAM | 输入设备的 RAM 大小，然后选择单位，选项包括 B（字节）、KB（千字节）、MB（兆字节）、GB（千兆字节）或者 TB（太字节）。
输入：具有硬件按钮（返回/主屏幕/菜单） | 如果您的设备具有硬件导航按钮，请选择此选项。如果这些按钮仅集成在软件中，请取消选择此选项。如果您选择此选项，按钮将不会出现在屏幕上。任何情况下，您都可以使用模拟器侧面板“按”这些按钮。
输入：具有硬件键盘 | 如果您的设备具有硬件硬盘，请选择此选项。如果没有，请取消选择此选项。如果您选择此选项，屏幕上将不会显示键盘。任何情况下，您都可以使用计算机键盘向模拟器发送按键。
导航样式

选择下列其中一项：

  • None - 无硬件控件。通过软件导航。
  • D-pad - 方向键支持。
  • Trackball
  • Wheel

这些选项针对设备本身的实际硬件控件。不过，由外部控制器发送至设备的事件也是如此。

支持的设备状态

选择一个或两个选项：

  • Portrait - 纵向跨度大于宽度。
  • Landscape - 横向跨度大于高度。

如果您同时选择两个选项，则在模拟器中可以在两个方向之间切换。您必须选择一个选项才能继续。

相机

选择一个或两个选项：

  • Back-Facing Camera - 镜头背对用户。
  • Front-Facing Camera - 镜头朝向用户。

然后，您可以使用模拟器提供的网络摄像头或照片模拟使用相机拍照。

传感器：加速度计 | 如果设备具有可以帮助确定其方向的硬件，请选择此选项。
传感器：陀螺仪 | 如果设备具有检可以测旋转或扭曲的硬件，请选择此选项。与加速度计一起使用时，陀螺仪可以更方便地检测方向和支持六轴方向系统。
传感器：GPS | 如果设备具有支持全球定位系统 (GPS) 卫星导航系统的硬件，请选择此选项。
传感器：近程传感器 | 如果设备具有可以检测通话过程中设备是否靠近您的脸部以停用从屏幕输入的硬件，请选择此选项。
默认皮肤 | 选择一款可以控制设备在模拟器中显示样式的皮肤。请记住，指定相对于分辨率而言过小的屏幕意味着屏幕会被切断，您将无法看到完整的屏幕。如需了解详细信息，请参阅创建模拟器皮肤。

AVD 属性

您可以在 Verify Configuration 页面中为 AVD 配置指定下列属性。AVD 配置指定了开发计算机与模拟器之间的交互，以及您想要在硬件配置文件中替换的属性。

AVD 配置属性可以替换硬件配置文件属性，而您在模拟器运行时设置的模拟器属性可以替换前两者。

AVD 属性 | 说明
AVD 名称 | AVD 的名称。名称可以包含大小写字母、从 0 至 9 的数字、句号 (.)、下划线 (_) 和括号 ( () )。存储 AVD 配置的文件的名称来自 AVD 名称。
AVD ID（高级） | AVD 文件名来自 ID，您可以使用 ID 从命令行引用 AVD。
硬件配置文件 | 点击 Change 可以在 Select Hardware 页面中选择不同的硬件配置文件。
系统映像 | 点击 Change 可以在 System Image 页面中选择不同的系统映像。需要活动互联网连接才能下载新映像。
启动：缩放 | 选择您想要在模拟器启动时使用的初始尺寸。如果初始尺寸大于计算机屏幕，模拟器屏幕可能会调小。默认值为 Auto（自动）。
Startup:方向

为初始模拟器屏幕方向选择一个选项：

  • Portrait - 纵向跨度大于宽度。
  • Landscape - 横向跨度大于高度。

选项仅在硬件配置文件中选定时启用。在模拟器中运行 AVD 时，如果硬件配置文件中支持纵向和横向，那么您可以更改方向。

相机（高级）

选择一个或两个选项：

  • Front - 镜头背对用户。
  • Back - 镜头朝向用户。

此选项仅在硬件配置文件中选定时可用；不适用于 Android Wear 和 Android TV。

网络：速度（高级）

选择网络协议以确定数据传输的速度：

  • GSM - Global System for Mobile Communications
  • HSCSD - High-Speed Circuit-Switched Data
  • GPRS - Generic Packet Radio Service
  • EDGE - Enhanced Data rates for GSM Evolution
  • UMTS - Universal Mobile Telecommunications System
  • HSPDA - High-Speed Downlink Packet Access
  • Full (default) - 以计算机允许的最大速度传输数据。
网络：延迟（高级） | 选择网络协议以设置协议将数据包从一点传输至另一点所需的时间（延迟）。
仿真性能：图形

选择图形在模拟器中的渲染方式：

  • Hardware - 使用计算机显卡更快地渲染。
  • Software - 在软件中模拟图形，当显卡中的渲染遇到问题时这种方式非常有用。
  • Auto - 由模拟器根据显卡决定最佳选项。
多核 CPU（高级） | 选择计算机上您要用于模拟器的处理器核心数量。使用更多的处理器核心可以加快模拟器的运行速度。
内存和存储：RAM | 设备上的 RAM 大小。此值由硬件制造商设置，不过如果需要（比如为了实现更快的模拟器操作），您可以将其替换。增加 RAM 大小会占用计算机更多的资源。输入 RAM 大小，然后选择单位，选项包括 B（字节）、KB（千字节）、MB（兆字节）、GB（千兆字节）或者 TB（太字节）。
内存和存储：虚拟机堆 | 虚拟机堆大小。此值由硬件制造商设置，不过如果需要，您可以将其替换。键入堆大小，然后选择单位，选项包括 B（字节）、KB（千字节）、MB（兆字节）、GB（千兆字节）或者 TB（太字节）。如需了解有关 Android 虚拟机的详细信息，请参阅不同虚拟机的内存管理。
内存和存储：内部存储 | 设备上可用的不可移动内存空间的大小。此值由硬件制造商设置，不过如果需要，您可以将其替换。键入大小，然后选择单位，选项包括 B（字节）、KB（千字节）、MB（兆字节）、GB（千兆字节）或者 TB（太字节）。
内存和存储：SD 卡 | 设备上可用于存储数据的可移动内存空间的大小。要使用由 Android Studio 管理的虚拟 SD 卡，请选择 Studio，键入大小，然后选择单位，选项包括 B（字节）、KB（千字节）、MB（兆字节）、GB（千兆字节）或者 TB（太字节）。如果使用相机，建议最小内存为 100 MB。要管理文件中的空间，请选择 External File，然后点击 ... 指定文件和位置。如需了解详细信息，请参阅 mksdcard。
设备框架：启用设备框架 | 选择此选项可以在模拟真实设备外观的模拟器窗口周围启用框架。
自定义皮肤定义（高级） | 选择一款可以控制设备在模拟器中显示样式的皮肤。请记住，指定相对于分辨率而言过小的屏幕意味着屏幕会被切断，您将无法看到完整的屏幕。如需了解详细信息，请参阅创建模拟器皮肤。
键盘：启用键盘输入（高级） | 如果您想要使用硬件键盘与模拟器互动，请选择此选项。此选项对 Android Wear 和 Android TV 停用。

创建模拟器皮肤

Android Emulator 皮肤是定义模拟器显示画面的视觉和控制元素的一系列文件。如果 AVD 设置中可用的皮肤定义无法满足您的要求，您可以创建自己的自定义皮肤定义，然后将其应用到 AVD。

每个模拟器皮肤均包含：

  • hardware.ini 文件
  • 用于支持的方向（横向、纵向）和物理配置的布局文件
  • 用于显示元素（如背景、键和按钮）的图片文件

要创建和使用自定义皮肤，请执行以下操作：

  1. 创建一个用于保存皮肤配置文件的新目录。
  2. 在一个名称为 layout 的文本文件钟定义皮肤的视觉外观。此文件可以定义皮肤的多个特征，如大小和特定按钮的图片资源。例如：
    parts {
        device     {
            display     {
                width       320
                height      480
                x           0
                y           0
                }
            }

        portrait     {
            background     {
                image background_port    .png
                }

            buttons     {
                power     {
                    image  button_vertical    .png
                    x     1229
                    y     616
                    }
                }
            }
            ...
    }
  3. 在相同的目录下添加设备映像的位图文件。
  4. 在 hardware.ini 文件中为设备设置（如 hw.keyboard 和 hw.lcd.density）指定其他硬件特定的设备配置。
  5. 将皮肤文件夹中的文件归档，然后选择归档文件作为自定义皮肤。

如需了解有关创建模拟器皮肤的详细信息，请参阅工具源代码中的 Android Emulator 皮肤文件规范。

来源： https://developer.android.com/studio/run/managing-avds.html


Control the Emulator from the Command Line

  1. Starting and Stopping the Emulator
  2. Installing Applications on the Emulator
  3. Using Command Line Parameters
  4. Using the Emulator Console
    1. Starting and stopping a console session
    2. Port redirection
    3. Geo location provider emulation
    4. Hardware events emulation
    5. Device power characteristics
    6. Network status
    7. Network delay emulation
    8. Network speed emulation
    9. Telephony emulation
    10. SMS emulation
    11. VM state
    12. Emulator window
    13. Simulating finger print support
    14. Terminating an emulator instance
  5. Using SD Card Emulation
    1. Creating an SD card image
    2. Copying files to an SD card image
    3. Loading an SD card image
  6. Working with Emulator Disk Images
    1. Default image files
    2. Runtime images: user data and SD card
    3. Temporary images
  7. Setting Up Emulator Networking
    1. Network address space
    2. Local networking limitations
    3. Using network redirection
    4. Configuring the emulator DNS settings
    5. Using the emulator with a proxy
    6. Interconnecting emulator instances
    7. Sending a voice call or SMS to another emulator instance
  8. Using Hardware Acceleration
    1. Configuring graphics acceleration
    2. Configuring virtual machine acceleration
  9. Troubleshooting Emulator Problems

See also

  1. Running Apps in the Android Emulator
  2. Managing AVDs with the AVD Manager

The Android SDK includes a mobile device emulator — a virtual mobile device that runs on your computer. The emulator lets you develop and test Android applications without using a physical device.

This page describes command line features that you can use with the Android Emulator. For information about using the Android Emulator UI, see Using the Android Emulator.

Starting and Stopping the Emulator

During development and testing of your application, you install and run your application in the Android Emulator. You can launch the emulator as a standalone application from a command line, or you can run it from within your Android Studio development environment. In either case, you specify the AVD configuration to load and any startup options you want to use, as described in this document.

You can run your application on a single instance of the emulator or, depending on your needs, you can start multiple emulator instances and run your application in more than one emulated device. You can use the emulator built-in commands to simulate GSM phone calling or SMS between emulator instances, and you can set up network redirection that allows emulators to send data to one another. For more information, seeTelephony Emulation, SMS Emulation, and Emulator Networking.

To start an instance of the emulator from the command line, navigate to the tools/ folder of the SDK. Enteremulator command like this:

emulator -avd <avd_name> [<options>]

This initializes the emulator, loads an AVD configuration and displays the emulator window.

Note: You can run multiple instances of the emulator concurrently, each with its own AVD configuration and storage area for user data, SD card, and so on.

When you run your app from Android Studio, it installs and launches the app on your connected device or emulator (launching the emulator, if necessary). You can specify emulator startup options in the Run/Debug dialog, in the Target tab. When the emulator is running, you can issue console commands as described later in this document.

If you are not working in Android Studio, see Installing Applications on the Emulator for information about how to install your application.

To stop an emulator instance, just close the emulator window.

Installing Applications on the Emulator

If you don't have access to Android Studio, you can install your application on the emulator using the adbutility. Before installing the application, you need to build and package it into an .apk as described in Build and Run Your App. After the application is installed, you can start the emulator from the command line as described previously, using any startup options necessary. When the emulator is running, you can also connect to the emulator console to issue commands as needed.

As you update your code, you periodically package and install it on the emulator. The emulator preserves the application and its state data across restarts, in a user-data disk partition. To ensure that the application runs properly as you update it, you may need to delete the emulator user-data partition. To do so, start the emulator with the -wipe-data option. For more information about the user-data partition and other emulator storage, see Working with Emulator Disk Images.

Using Command Line Parameters

The emulator supports a variety of options that you can specify when launching the emulator, to control its appearance or behavior. Here's the command-line syntax of the options available to the emulator program:

emulator -avd <avd_name> [-<option> [<value>]] ... [-<qemu args>]
emulator -list-avds
Category | Option | Description | Comments
AVD -avd <avd_name> or
@<avd_name> 		Required. Specifies the AVD to load for this emulator instance. You must create an AVD configuration before launching the emulator. For information, see Managing AVDs with AVD Manager.
Disk Images -cache <filepath> Use <filepath> as the working cache partition image. An absolute or relative path to the current working directory. If no cache file is specified, the emulator default behavior is to use a temporary file instead.

For more information on disk images, use -help-disk-images.

-data <filepath> | Use <filepath> as the working user-data disk image. | Optionally, you can specify a path relative to the current working directory. If -data is not used, the emulator looks for a file named userdata-qemu.img in the storage area of the AVD being used (see -avd).
-initdata <filepath> When resetting the user-data image (through -wipe-data), copy the contents of this file to the new user-data disk image. By default, the emulator copies the <system>/userdata.img. Optionally, you can specify a path relative to the current working directory. See also -wipe-data.

For more information on disk images, use -help-disk-images.

-nocache | Start the emulator without a cache partition. | See also -cache <file>.
-ramdisk <filepath> Use <filepath> as the ramdisk image. Default value is <system>/ramdisk.img.

Optionally, you can specify a path relative to the current working directory. For more information on disk images, use -help-disk-images.

-sdcard <filepath> Use <file> as the SD card image. Default value is <system>/sdcard.img.

Optionally, you can specify a path relative to the current working directory. For more information on disk images, use -help-disk-images.

-wipe-data Reset the current user-data disk image (that is, the file specified by -datadir and-data, or the default file). The emulator deletes all data from the user data image file, then copies the contents of the file at-inidata data to the image file before starting. See also -initdata.

For more information on disk images, use -help-disk-images.

Debug | -debug <tags> | Enable/disable debug messages for the specified debug tags. | <tags> is a space/comma/column-separated list of debug component names. Use -help-debug-tags to print a list of debug component names that you can use.
-debug-<tag> | Enable/disable debug messages for the specified debug tag. | Use -help-debug-tags to print a list of debug component names that you can use in <tag>.
-debug-no-<tag> | Disable debug messages for the specified debug tag.
-logcat <logtags> | Enable logcat output with given tags. | If the environment variable ANDROID_LOG_TAGS is defined and not empty, its value will be used to enable logcat output by default.
-shell | Create a root shell console on the current terminal. | You can use this command even if the adb daemon in the emulated system is broken. Pressing Ctrl-c from the shell stops the emulator instead of the shell.
-shell-serial <device> Enable the root shell (as in -shell and specify the QEMU character device to use for communication with the shell. <device> must be a QEMU device type. See the documentation for '-serial dev' athttp://wiki.qemu.org/download/qemu-doc.html for a list of device types.

Here are some examples:

  • -shell-serial stdio is identical to -shell
  • -shell-serial tcp::4444,server,nowait lets you communicate with the shell over TCP port 4444
  • -shell-serial fdpair:3:6 lets a parent process communicate with the shell using fds 3 (in) and 6 (out)
  • -shell-serial fdpair:0:1 uses the normal stdin and stdout fds, except that QEMU won't tty-cook the data.
-show-kernel <name> | Display kernel messages.
-trace <name> | Enable code profiling (press F9 to start), written to a specified file.
-verbose Enable verbose output. Equivalent to -debug-init.

You can define the default verbose output options used by emulator instances in the Android environment variable ANDROID_VERBOSE. Define the options you want to use in a comma-delimited list, specifying only the stem of each option: -debug-<tags>.

Here's an example showing ANDROID_VERBOSE defined with the -debug-init and -debug-modem options:

ANDROID_VERBOSE=init,modem

For more information about debug tags, use <-help-debug-tags>.

Media | -audio <backend> | Use the specified audio backend.
-audio-in <backend> | Use the specified audio-input backend.
-audio-out <backend> | Use the specified audio-output backend.
-noaudio | Disable audio support in the current emulator instance.
-radio <device> | Redirect radio modem interface to a host character device.
-useaudio | Enable audio support in the current emulator instance. | Enabled by default.
Network | -dns-server <servers> | Use the specified DNS server(s). | The value of <servers> must be a comma-separated list of up to 4 DNS server names or IP addresses.
-http-proxy <proxy> Make all TCP connections through a specified HTTP/HTTPS proxy The value of <proxy> can be one of the following:
http://<server>:<port>
http://<username>:<password>@<server>:<port>

The http:// prefix can be omitted. If the -http-proxy <proxy> command is not supplied, the emulator looks up the http_proxy environment variable and automatically uses any value matching the <proxy> format described above.

-netdelay <delay> | Set network latency emulation to <delay>. | Default value is none. See the table in Network Delay Emulation for supported <delay> values.
-netfast | Shortcut for -netspeed full -netdelay none
-netspeed <speed> | Set network speed emulation to <speed>. | Default value is full. See the table in Network Speed Emulation for supported <speed> values.
-port <port> | Set the console port number for this emulator instance to <port>. | The console port number must be an even integer between 5554 and 5584, inclusive. <port>+1 must also be free and will be reserved for adb.
-report-console <socket> Report the assigned console port for this emulator instance to a remote third party before starting the emulation. <socket> must use one of these formats:

tcp:<port>[,server][,max=<seconds>]
unix:<port>[,server][,max=<seconds>]

Use -help-report-console to view more information about this topic.

System -cpu-delay <delay> Slow down emulated CPU speed by <delay> Supported values for <delay> are integers between 0 and 1000.

Note that the <delay> does not correlate to clock speed or other absolute metrics — it simply represents an abstract, relative delay factor applied non-deterministically in the emulator. Effective performance does not always scale in direct relationship with <delay> values.

-gps <device> | Redirect NMEA GPS to character device. | Use this command to emulate an NMEA-compatible GPS unit connected to an external character device or socket. The format of <device> must be QEMU-specific serial device specification. See the documentation for 'serial -dev' at http://wiki.qemu.org/download/qemu-doc.html.
-nojni | Disable JNI checks in the Dalvik runtime.
-qemu Pass arguments to the qemu emulator software.

Important: When using this option, make sure it is the last option specified, since all options after it are interpretted as qemu-specific options.

-qemu -enable-kvm Enable KVM acceleration of the emulator virtual machine. This option is only effective when your system is set up to use KVM-based VM acceleration. You can optionally specify a memory size (-m <size>) for the VM, which should match your emulator memory size:

-qemu -m 512 -enable-kvm
-qemu -m 1024 -enable-kvm
-qemu -h | Display qemu help.
-gpu on | Turn on graphics acceleration for the emulator. | This option is only available for emulators using a system image with API Level 15, revision 3 and higher. For more information, see Configuring Graphics Acceleration.
-radio <device> | Redirect radio mode to the specified character device. | The format of <device> must be QEMU-specific serial device specification. See the documentation for 'serial -dev' at http://wiki.qemu.org/download/qemu-doc.html.
-timezone <timezone> Set the timezone for the emulated device to <timezone>, instead of the host timezone. <timezone> must be specified in zoneinfo format. For example:

"America/Los_Angeles"
"Europe/Paris"

-version | Display the emulator version number.
UI | -dpi-device <dpi> | Scale the resolution of the emulator to match the screen size of a physical device. | The default value is 165. See also -scale.
-no-boot-anim | Disable the boot animation during emulator startup. | Disabling the boot animation can speed the startup time for the emulator.
-no-window | Disable the emulator graphical window display.
-scale <scale> | Scale the emulator window. | <scale> is a number between 0.1 and 3 that represents the desired scaling factor. You can also specify scale as a DPI value if you add the suffix "dpi" to the scale value. A value of "auto" tells the emulator to select the best window size.
-raw-keys | Disable Unicode keyboard reverse-mapping.
-noskin | Don't use any emulator skin.
-keyset <file> | Use the specified keyset file instead of the default. | The keyset file defines the list of key bindings between the emulator and the host keyboard. For more information, use -help-keyset to print information about this topic.
-onion <image> | Use overlay image over screen. | No support for JPEG. Only PNG is supported.
-onion-alpha <percent> | Specify onion skin translucency value (as percent). | Default is 50.
-onion-rotation <position> | Specify onion skin rotation. | <position> must be one of the values 0, 1, 2, 3.
-skin <skinID> | This emulator option is deprecated. | Please set skin options using AVDs, rather than by using this emulator option. Using this option may yield unexpected and in some cases misleading results, since the density with which to render the skin may not be defined. AVDs let you associate each skin with a default density and override the default as needed. For more information, see Managing AVDs with the AVD Manager.
-skindir <dir> | This emulator option is deprecated. | See comments for -skin, above.
Help | -help | Print a list of all emulator options.
-help-all | Print help for all startup options.
-help-<option> | Print help for a specific startup option.
-help-debug-tags | Print a list of all tags for -debug <tags>.
-help-disk-images | Print help for using emulator disk images.
-help-environment | Print help for emulator environment variables.
-help-keys | Print the current mapping of keys.
-help-keyset-file | Print help for defining a custom key mappings file.
-help-virtual-device | Print help for Android Virtual Device usage.

Using the Emulator Console

Each running emulator instance provides a console that lets you query and control the emulated device environment. For example, you can use the console to manage port redirection, network characteristics, and telephony events while your application is running on the emulator.

Starting and stopping a console session

To access the console and enter commands, from a terminal window, use telnet to connect to the console port and provide your authentication token. Each time the console displays OK, it's ready to accept commands. It doesn't have a typical prompt.

To connect to the console of a running emulator instance:

  1. Open a terminal window and enter the following command:
    2. telnet localhost console-port

    The emulator window title lists the console port number. For example, the window title for an emulator using console port 5554 could be5554:Nexus_5X_API_23.

    An emulator instance occupies a pair of adjacent ports: a console port and an adb port. The port numbers differ by 1, with the adb port having the higher port number. The console of the first emulator instance running on a particular machine uses console port 5554 and adb port 5555. Subsequent instances use port numbers increasing by two — for example, 5556/5557, 5558/5559, and so on. Up to 16 concurrent emulator instances can run a console facility.

    To connect to the emulator console, you must specify a valid console port. If multiple emulator instances are running, you need to determine the console port of the emulator instance you want to connect to.

    The adb devices command prints a list of running emulator instances and their console port numbers. For more information, see Querying for Emulator/Device Instances.

    Note: The emulator listens for connections on ports 5554 to 5587 and accepts connections from localhost only.

  2. After the console displays OK, enter the auth auth_token command.

    3. Before you can enter console commands, the emulator console requires authentication. auth_token must match the contents of the.emulator_console_auth_token file in your home directory.

    If that file doesn't exist, the telnet localhost console-port command creates the file, which contains a randomly generated authentication token.

    To disable authentication, delete the token from the .emulator_console_auth_token file or create an empty file if it doesn't exist.

  3. After you're connected to the console, enter console commands.

    4. Enter help and help command to see a list of console commands and learn about specific commands.

  4. To exit the console session, enter quit or exit.

Here's an example session:

me-macbook$ telnet localhost 5554
Trying ::1...
telnet: connect to address ::1: Connection refused
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Android Console: Authentication required
Android Console: type 'auth <auth_token>' to authenticate
Android Console: you can find your <auth_token> in
'/Users/me/.emulator_console_auth_token'
OK
auth 123456789ABCdefZ
Android Console: type 'help' for a list of commands
OK
help
Android console command help:

    help|h|?         print a list of commands
    crash            crash the emulator instance
    kill             kill the emulator instance
    quit|exit        quit control session
    redir            manage port redirections
    power            power related commands
    event            simulate hardware events
    avd              control virtual device execution
    finger           manage emulator fingerprint
    geo              Geo-location commands
    sms              SMS related commands
    cdma             CDMA related commands
    gsm              GSM related commands
    rotate           rotate the screen by 90 degrees

try 'help <command>' for command-specific help
OK
exit
Connection closed by foreign host.
me-macbook$

The following sections describe the major functional areas of the console.

Port redirection

You can use the console to add and remove port redirection while the emulator is running. After you connect to the console, manage port redirection by entering the following command:

redir <list|add|del>

The redir command supports the subcommands listed in the table below.

Subcommand | Description | Comments
list | List the current port redirection.
add <protocol>:<host-port>:<guest-port> Add a new port redirection.
  • <protocol> must be either "tcp" or "udp"
  • <host-port> is the port number to open on the host
  • <guest-port> is the port number to route data to on the emulator/device
del <protocol>:<host-port> | Delete a port redirection. | The meanings of <protocol> and <host-port> are listed in the previous row.

Geo location provider emulation

You can use the console to set the geographic location reported to the applications running inside an emulator. Use the geo command to send a simple GPS fix to the emulator, with or without NMEA 1083 formatting:

geo <fix|nmea>

The geo command supports the subcommands listed in the table below.

Subcommand | Description | Comments
fix <longitude> <latitude> [<altitude>] | Send a simple GPS fix to the emulator instance. | Specify longitude and latitude in decimal degrees. Specify altitude in meters.
nmea <sentence> | Send an NMEA 0183 sentence to the emulated device, as if it were sent from an emulated GPS modem. | <sentence> must begin with '$GP'. Only '$GPGGA' and '$GPRCM' sentences are currently supported.

You can issue the geo command as soon as an emulator instance is running. The emulator sets the location you enter by creating a mock location provider. This provider responds to location listeners set by applications, and also supplies the location to the LocationManager. Any application can query the location manager to obtain the current GPS fix for the emulated device by calling:

LocationManager.getLastKnownLocation("gps")

For more information about the Location Manager, see LocationManager.

Hardware events emulation

The event console commands sends hardware events to the emulator. The syntax for this command is as follows:

event <send|types|codes|text>

The event command supports the subcommands listed in the table below.

Subcommand | Description | Comments
send <type>:<code>:<value> [...] | Send one or more events to the Android kernel. | You can use text names or integers for <type> and<value>.
types | List all <type> string aliases supported by theevent subcommands. |
codes <type> | List all <codes> string aliases supported by theevent subcommands for the specified <type>. |
event text <message> | Simulate keypresses to send the specified string of characters as a message, | The message must be a UTF-8 string. Unicode posts will be reverse-mapped according to the current device keyboard. Unsupported characters will be discarded silently.

Device power characteristics

The power command controls the power state reported by the emulator to applications. The syntax for this command is as follows:

power <display|ac|status|present|health|capacity>

The event command supports the subcommands listed in the table below.

Subcommand | Description | Comments
display | Display battery and charger state. |
ac <on|off> | Set AC charging state to on or off. |
status <unknown|charging|discharging|not-charging|full> | Change battery status as specified. |
present <true|false> | Set battery presence state. |
health <unknown|good|overheat|dead|overvoltage|failure> | Set battery health state. |
capacity <percent> | Set remaining battery capacity state (0-100). |

Network status

You can use the console to check the network status and current delay and speed characteristics. To do so, connect to the console and use thenetstatus command. Here's an example of the command and its output.

network status

Network delay emulation

The emulator lets you simulate various network latency levels, so that you can test your application in an environment more typical of the actual conditions in which it will run. You can set a latency level or range at emulator startup or you can use the console to change the latency, while the application is running in the emulator.

To set latency at emulator startup, use the -netdelay emulator option with a supported <delay> value, as listed in the table below. Here are some examples:

emulator -netdelay gprs
emulator -netdelay 40 100

To make changes to network delay while the emulator is running, connect to the console and use the netdelay command with a supported <delay> value from the table below.

network delay gprs

The format of network <delay> is one of the following (numbers are milliseconds):

Value | Description | Comments
gprs | GPRS | (min 150, max 550)
edge | EDGE/EGPRS | (min 80, max 400)
umts | UMTS/3G | (min 35, max 200)
none | No latency | (min 0, max 0)
<num> | Emulate an exact latency (milliseconds). |
<min>:<max> | Emulate an specified latency range (min, max milliseconds). |

Network speed emulation

The emulator also lets you simulate various network transfer rates. You can set a transfer rate or range at emulator startup or you can use the console to change the rate, while the application is running in the emulator.

To set the network speed at emulator startup, use the -netspeed emulator option with a supported <speed> value, as listed in the table below. Here are some examples:

emulator -netspeed gsm
emulator -netspeed 14.4 80

To make changes to network speed while the emulator is running, connect to the console and use the netspeed command with a supported <speed>value from the table below.

network speed 14.4 80

The format of network <speed> is one of the following (numbers are kilobits/sec):

Value | Description | Comments
gsm | GSM/CSD | (Up: 14.4, down: 14.4)
hscsd | HSCSD | (Up: 14.4, down: 43.2)
gprs | GPRS | (Up: 40.0, down: 80.0)
edge | EDGE/EGPRS | (Up: 118.4, down: 236.8)
umts | UMTS/3G | (Up: 128.0, down: 1920.0)
hsdpa | HSDPA | (Up: 348.0, down: 14400.0)
full | no limit | (Up: 0.0, down: 0.0)
<num> | Set an exact rate used for both upload and download. |
<up>:<down> | Set exact rates for upload and download separately. |

Telephony emulation

The Android emulator includes its own GSM emulated modem that lets you simulate telephony functions in the emulator. For example, you can simulate inbound phone calls, establish data connections and terminate them. The Android system handles simulated calls exactly as it would actual calls. The emulator does not support call audio.

You can use the gsm command to access the emulator telephony functions after connecting to the console. The syntax for this command is as follows:

gsm <call|accept|busy|cancel|data|hold|list|voice|status>

The gsm command supports the subcommands listed in the table below.

Subcommand | Description | Comments
call <phonenumber> | Simulate an inbound phone call from <phonenumber>.
accept <phonenumber> | Accept an inbound call from <phonenumber> and change the call state "active". | You can change a call state to "active" only if its current state is "waiting" or "held".
busy <phonenumber> | Close an outbound call to <phonenumber> and change the call state to "busy". | You can change a call state to "busy" only if its current state is "waiting".
cancel <phonenumber> | Terminate an inbound or outbound phone call to/from <phonenumber>.
data <state> Change the state of the GPRS data connection to <state>. Supported <state> values are:
  • unregistered -- No network available
  • home -- On local network, non-roaming
  • roaming -- On roaming network
  • searching -- Searching networks
  • denied -- Emergency calls only
  • off -- Same as 'unregistered'
  • on -- same as 'home'
hold | Change the state of a call to "held". | You can change a call state to "held" only if its current state is "active" or "waiting".
list | List all inbound and outbound calls and their states.
voice <state> Change the state of the GPRS voice connection to <state>. Supported <state> values are:
  • unregistered -- No network available
  • home -- On local network, non-roaming
  • roaming -- On roaming network
  • searching -- Searching networks
  • denied -- Emergency calls only
  • off -- Same as 'unregistered'
  • on -- Same as 'home'
status | Report the current GSM voice/data state. | Values are those described for the voice and data commands.

SMS emulation

The Android emulator console lets you generate an SMS message and direct it to an emulator instance. Once you connect to an emulator instance, you can generate an emulated incoming SMS using the following command:

sms send <senderPhoneNumber> <textmessage>

where <senderPhoneNumber> contains an arbitrary numeric string.

The console forwards the SMS message to the Android framework, which passes it through to an application that handles that message type.

VM state

You can use the vm command to control the VM on an emulator instance. The syntax for this command is as follows:

vm <start|stop|status>

The vm command supports the subcommands listed in the table below.

Subcommand | Description | Comments
start | Start the VM on the instance. |
stop | Stop the VM on the instance. |
start | Display the current status of the VM (running or stopped). |

Emulator window

You can use the window command to manage the emulator window. The syntax for this command is as follows:

window <scale>

The vm command supports the subcommands listed in the table below.

Subcommand | Description | Comments
scale <scale> | Scale the emulator window. | A number between 0.1 and 3 that sets the scaling factor. You can also specify scale as a DPI value if you add the suffix "dpi" to the scale value. A value of "auto" tells the emulator to select the best window size.

Simulating finger print support

Android Emulator console provides the finger command, allowing you to simulate, and thus validate, finger print authentication for your app. After you set up your app to accept finger print authentication, your emulator or device should display the finger print authentication screen, as shown in figure 1.

Figure 1. The finger print authentication screen.

Open a terminal session, and telnet to the emulator. For example:

telnet localhost 5554

Enter the finger command to simulate finger touch and removal:

  • finger touch <fingerprint-id> to simulate a finger touching the sensor
  • finger remove to simulate finger removal

Your app should respond as if a user touched and then removed their finger from the finger print sensor.

Terminating an emulator instance

You can terminate an emulator instance through the console, using the kill command.

Using SD Card Emulation

You can create a disk image and then load it to the emulator at startup, to simulate the presence of a user's SD card in the device. To do this, you can specify an SD card image when you create an AVD, or you can use the mksdcard utility included in the SDK.

The following sections describe how to create an SD card disk image, how to copy files to it, and how to load it in the emulator at startup.

Note that you can only load a disk image at emulator startup. Similarly, you can not remove a simulated SD card from a running emulator. However, you can browse, send files to, and copy/remove files from a simulated SD card either with adb or the emulator.

The emulator supports emulated SDHC cards, so you can create an SD card image of any size up to 128 gigabytes.

Creating an SD card image

There are several ways of creating an SD card image. The easiest way is to use the AVD Manager to create a new SD card by specifying a size when you create an AVD.

You can also use the mksdcard tool, included in the SDK, to create a FAT32 disk image that you can load in the emulator at startup. You can access mksdcard in the tools directory of the SDK and create a disk image like this:

mksdcard <size> <file>

For example:

mksdcard 1024M sdcard1.iso

For more information, see mksdcard.

Copying files to an SD card image

Once you have created the disk image, you can copy files to it prior to loading it in the emulator. To copy files, you can mount the image as a loop device and then copy the files to it, or you can use a utility such as mtools to copy the files directly to the image. The mtools package is available for Linux, Mac, and Windows.

Alternatively, you can use the adb push command to move files onto an SD card image while it is loaded in an emulator. For more information see the adb push documentation.

Loading an SD card image

By default, the emulator loads the SD card image that is stored with the active AVD (see the -avd startup option).

Alternatively, you can start the emulator with the -sdcard flag and specify the name and path of your image (relative to the current working directory):

emulator -sdcard <filepath>

Working with Emulator Disk Images

The emulator uses mountable disk images stored on your development machine to simulate flash (or similar) partitions on an actual device. For example, it uses a disk image containing an emulator-specific kernel, the Android system, a ramdisk image, and writable images for user data and simulated SD card.

To run properly, the emulator requires access to a specific set of disk image files. By default, the Emulator always looks for the disk images in the private storage area of the AVD in use. If no images exist there when the Emulator is launched, it creates the images in the AVD directory based on default versions stored in the SDK.

Note: The default storage location for AVDs is in ~/.android/avd on OS X and Linux, C:\Documents and Settings\<user>\.android\ on Windows XP, and C:\Users\<user>\.android\ on Windows Vista.

To let you use alternate or custom versions of the image files, the emulator provides startup options that override the default locations and filenames of the image files. When you use one of these options, the emulator searches for the image file under the image name or location that you specify; if it can not locate the image, it reverts to using the default names and location.

The emulator uses three types of image files: default image files, runtime image files, and temporary image files. The sections below describe how to override the location/name of each type of file.

Default image files

When the emulator launches, but does not find an existing user data image in the active AVD storage area, it creates a new one from a default version included in the SDK. The default user data image is read-only. The image files are read-only.

The emulator provides the -system <dir> startup option to let you override the location where the emulator looks for the default user data image.

The emulator also provides a startup option that lets you override the name of the default user data image, as described in the following table. When you use the option, the emulator looks in the default directory, or in a custom location (if you specified -system <dir>).

Name | Description | Comments
userdata.img | The initial user-data disk image | Override using -initdata <file>. Also see -data <file>, below.

Runtime images: user data and SD card

At runtime, the emulator reads and writes data to two disk images: a user-data image and (optionally) an SD card image. These images emulate the user-data partition and removable storage media on actual device.

The emulator provides a default user-data disk image. At startup, the emulator creates the default image as a copy of the system user-data image (user-data.img), described above. The emulator stores the new image with the files of the active AVD.

The emulator provides startup options to let you override the actual names and storage locations of the runtime images to load, as described in the following table. When you use one of these options, the emulator looks for the specified file(s) in the current working directory, in the AVD directory, or in a custom location (if you specified a path with the filename).

Name | Description | Comments
userdata-qemu.img | An image to which the emulator writes runtime user-data for a unique user. | Override using -data <filepath>, where <filepath> is the path the image, relative to the current working directory. If you supply a filename only, the emulator looks for the file in the current working directory. If the file at <filepath> does not exist, the emulator creates an image from the default userdata.img, stores it under the name you specified, and persists user data to it at shutdown.
sdcard.img | An image representing an SD card inserted into the emulated device. | Override using -sdcard <filepath>, where <filepath> is the path the image, relative to the current working directory. If you supply a filename only, the emulator looks for the file in the current working directory.

User-data image

Each emulator instance uses a writable user-data image to store user- and session-specific data. For example, it uses the image to store a unique user's installed application data, settings, databases, and files.

At startup, the emulator attempts to load a user-data image stored during a previous session. It looks for the file in the current working directory, in the AVD directory described in a previous section and at the custom location/name that you specified at startup.

  • If it finds a user-data image, it mounts the image and makes it available to the system for reading and writing of user data.
  • If it does not find one, it creates an image by copying the system user-data image (userdata.img), described above. At device power-off, the system persists the user data to the image, so that it will be available in the next session. Note that the emulator stores the new disk image at the location/name that you specify in -data startup option.

Note: Because of the AVD configurations used in the emulator, each emulator instance gets its own dedicated storage. There is no longer a need to use the -d option to specify an instance-specific storage area.

SD card

Optionally, you can create a writable disk image that the emulator can use to simulate removeable storage in an actual device. For information about how to create an emulated SD card and load it in the emulator, see Using SD Card Emulation.

You can also use the android tool to automatically create an SD Card image for you, when creating an AVD. For more information, see Managing AVDs with the AVD Manager.

Temporary images

The emulator creates two writable images at startup that it deletes at device power-off. The images are:

  • A writable copy of the Android system image
  • The /cache partition image

The emulator does not permit renaming the temporary system image or persisting it at device power-off.

The /cache partition image is initially empty, and is used by the browser to cache downloaded web pages and images. The emulator provides an -cache <file>, which specifies the name of the file in which to persist the /cache image at device power-off. If <file> does not exist, the emulator creates it as an empty file.

You can also disable the use of the cache partition by specifying the -nocache option at startup.

Setting Up Emulator Networking

The emulator provides versatile networking capabilities that you can use to set up complex modeling and testing environments for your application. The sections below introduce the emulator network architecture and capabilities.

Network address space

Each instance of the emulator runs behind a virtual router/firewall service that isolates it from your development machine network interfaces and settings and from the internet. An emulated device can not see your development machine or other emulator instances on the network. Instead, it sees only that it is connected through Ethernet to a router/firewall.

The virtual router for each instance manages the 10.0.2/24 network address space — all addresses managed by the router are in the form of 10.0.2.<xx>, where <xx> is a number. Addresses within this space are pre-allocated by the emulator/router as follows:

Network Address | Description
10.0.2.1 | Router/gateway address
10.0.2.2 | Special alias to your host loopback interface (i.e., 127.0.0.1 on your development machine)
10.0.2.3 | First DNS server
10.0.2.4 / 10.0.2.5 / 10.0.2.6 | Optional second, third and fourth DNS server (if any)
10.0.2.15 | The emulated device network/ethernet interface
127.0.0.1 | The emulated device loopback interface

Note that the same address assignments are used by all running emulator instances. That means that if you have two instances running concurrently on your machine, each will have its own router and, behind that, each will have an IP address of 10.0.2.15. The instances are isolated by a router and cannot see each other on the same network. For information about how to let emulator instances communicate over TCP/UDP, see Interconnecting Emulator Instances.

Also note that the address 127.0.0.1 on your development machine corresponds to the emulator own loopback interface. If you want to access services running on your development machine loopback interface (a.k.a. 127.0.0.1 on your machine), you should use the special address 10.0.2.2 instead.

Finally, note that the pre-allocated addresses of an emulated devider are specific to the Android Emulator and will probably be very different on real devices (which are also very likely to be NAT-ed, specifically, behind a router/firewall).

Local networking limitations

Android applications running in an emulator can connect to the network available on your workstation. However, they connect through the emulator, not directly to hardware, and the emulator acts like a normal application on your workstation. This means that the emulator, and thus your Android applications, are subject to some limitations:

  • Communication with the emulated device may be blocked by a firewall program running on your machine.
  • Communication with the emulated device may be blocked by another (physical) firewall/router to which your machine is connected.

The emulator virtual router should be able to handle all outbound TCP and UDP connections/messages on behalf of the emulated device, provided your development machine network environment allows it to do so. There are no built-in limitations on port numbers or ranges except the one imposed by your host operating system and network.

Depending on the environment, the emulator may not be able to support other protocols (such as ICMP, used for "ping") might not be supported. Currently, the emulator does not support IGMP or multicast.

Using network redirection

To communicate with an emulator instance behind its virtual router, you need to set up network redirection on the virtual router. Clients can then connect to a specified guest port on the router, while the router directs traffic to/from that port to the emulated device host port.

To set up the network redirection, you create a mapping of host and guest ports/addresses on the emulator instance. There are two ways to set up network redirection: using emulator console commands and using the adb tool, as described below.

Setting up redirection through the Emulator Console

Each emulator instance provides a control console the you can connect to, to issue commands that are specific to that instance. You can use the redirconsole command to set up redirection as needed for an emulator instance.

First, determine the console port number for the target emulator instance. For example, the console port number for the first emulator instance launched is 5554. Next, connect to the console of the target emulator instance, specifying its console port number, as follows:

telnet localhost 5554

Once connected, use the redir command to work with redirection. To add a redirection, use:

add <protocol>:<host-port>:<guest-port>

where <protocol> is either tcp or udp, and <host-port> and <guest-port> sets the mapping between your own machine and the emulated system, respectively.

For example, the following command sets up a redirection that handles all incoming TCP connections to your host (development) machine on 127.0.0.1:5000 and will pass them through to the emulated system 10.0.2.15:6000:

redir add tcp:5000:6000

To delete a redirection, you can use the redir del command. To list all redirection for a specific instance, you can use redir list. For more information about these and other console commands, see Using the Emulator Console.

Note that port numbers are restricted by your local environment. this typically means that you cannot use host port numbers under 1024 without special administrator privileges. Also, you won't be able to set up a redirection for a host port that is already in use by another process on your machine. In that case, redir generates an error message to that effect.

Setting up redirection through adb

The Android Debug Bridge (adb) tool provides port forwarding, an alternate way for you to set up network redirection. For more information, seeForwarding Ports in the adb documentation.

Note that adb does not currently offer any way to remove a redirection, except by killing the adb server.

Configuring the emulator DNS settings

At startup, the emulator reads the list of DNS servers that your system is currently using. It then stores the IP addresses of up to four servers on this list and sets up aliases to them on the emulated addresses 10.0.2.3, 10.0.2.4, 10.0.2.5 and 10.0.2.6 as needed.

On Linux and OS X, the emulator obtains the DNS server addresses by parsing the file /etc/resolv.conf. On Windows, the emulator obtains the addresses by calling the GetNetworkParams() API. Note that this usually means that the emulator ignores the content of your "hosts" file (/etc/hosts on Linux/OS X, %WINDOWS%/system32/HOSTS on Windows).

When starting the emulator at the command line, you can also use the -dns-server <serverList> option to manually specify the addresses of DNS servers to use, where <serverList> is a comma-separated list of server names or IP addresses. You might find this option useful if you encounter DNS resolution problems in the emulated network (for example, an "Unknown Host error" message that appears when using the web browser).

Using the emulator with a proxy

If your emulator must access the Internet through a proxy server, you can use the -http-proxy <proxy> option when starting the emulator, to set up the appropriate redirection. In this case, you specify proxy information in <proxy> in one of these formats:

http://<machineName>:<port>

or

http://<username>:<password>@<machineName>:<port>

The -http-proxy option forces the emulator to use the specified HTTP/HTTPS proxy for all outgoing TCP connections. Redirection for UDP is not currently supported.

Alternatively, you can define the environment variable http_proxy to the value you want to use for <proxy>. In this case, you do not need to specify a value for <proxy> in the -http-proxy command — the emulator checks the value of the http_proxy environment variable at startup and uses its value automatically, if defined.

You can use the -verbose-proxy option to diagnose proxy connection problems.

Interconnecting emulator instances

To allow one emulator instance to communicate with another, you must set up the necessary network redirection as illustrated below.

Assume that your environment is

  • A is you development machine
  • B is your first emulator instance, running on A
  • C is your second emulator instance, also running on A

and you want to run a server on B, to which C will connect, here is how you could set it up:

  1. Set up the server on B, listening to 10.0.2.15:<serverPort>
  2. On the B console, set up a redirection from A:localhost:<localPort> to B:10.0.2.15:<serverPort>
  3. On C, have the client connect to 10.0.2.2:<localPort>

For example, if you wanted to run an HTTP server, you can select <serverPort> as 80 and <localPort> as 8080:

  • B listens on 10.0.2.15:80
  • On the B console, issue redir add tcp:8080:80
  • C connects to 10.0.2.2:8080

Sending a voice call or SMS to another emulator instance

The emulator automatically forwards simulated voice calls and SMS messages from one instance to another. To send a voice call or SMS, use the dialer application or SMS application, respectively, from one of the emulators.

To initiate a simulated voice call to another emulator instance:

  1. Launch the dialer application on the originating emulator instance.
  2. As the number to dial, enter the console port number of the instance you'd like to call. You can determine the console port number of the target instance by checking its window title, where the console port number is reported as "Android Emulator (<port>).
  3. Press "Dial". A new inbound call appears in the target emulator instance.

To send an SMS message to another emulator instance, launch the SMS application (if available). Specify the console port number of the target emulator instance as as the SMS address, enter the message text, and send the message. The message is delivered to the target emulator instance.

You can also connect to an emulator console to simulate an incoming voice call or SMS. For more information, see Telephony Emulation and SMS Emulation.

Using Hardware Acceleration

To make the Android emulator run faster and be more responsive, you can configure it to take advantage of hardware acceleration, using a combination of configuration options, specific Android system images and hardware drivers.

Configuring graphics acceleration

Caution: As of SDK Tools Revision 17, the graphics acceleration feature for the emulator is experimental; be alert for incompatibilities and errors when using this feature.

Graphics acceleration for the emulator takes advantage of your development computer graphics hardware, specifically its graphics processing unit (GPU), to make screen drawing faster. To use the graphics acceleration feature, you must have the following versions of the Android development tools installed:

  • Android SDK Tools, Revision 17 or higher
  • Android SDK Platform API 15, Revision 3 or higher

Use the SDK Manager to install these components:

Note: Not all applications are compatible with graphics hardware acceleration. In particular, the Browser application and applications using theWebView component are not compatible with graphics acceleration.

To configure an AVD to use graphics acceleration:

  1. Make sure you have the required SDK components installed (listed above).
  2. Start the AVD Manager and create a new AVD with the Target value of Android 4.0.3 (API Level 15), revision 3 or higher.
  3. If you want to have graphics acceleration enabled by default for this AVD, in the Hardware section, click New, select GPU emulation and set the value to Yes.

    Note: You can also enable graphics acceleration when you start an emulator using command line options as describe in the next section.

  4. Name the AVD instance and select any other configuration options.

    Caution: Do not select the Snapshot: Enabled option. Snapshots are not supported for emulators with graphics acceleration enabled.

  5. Click Create AVD to save the emulator configuration.

If you set GPU emulation to Yes for your AVD, then graphics acceleration is automatically enabled when you run it. If you did not enable GPU emulationwhen you created the AVD, you can still enable it at runtime.

To enable graphics acceleration at runtime for an AVD:

  • If you are running the emulator from the command line, just include the -gpu on option:
    emulator -avd <avd_name> -gpu on

    Note: You must specify an AVD configuration that uses Android 4.0.3 (API Level 15, revision 3) or higher system image target. Graphics acceleration is not available for earlier system images.

  • If you are running the emulator from Android Studio, run your Android application using an AVD with the -gpu on option enabled:
    1. In Android Studio, click your Android application module folder and then select Run > Edit Configurations...
    2. In the left panel of the Run/Debug Configurations dialog, select your Android run configuration or create a new configuration.
    3. Under the Target Device options, select the AVD you created in the previous procedure.
    4. In the Emulator tab, in the Additional command line options field, enter:
      -gpu on
    5. Run your Android project using this run configuration.

Configuring virtual machine acceleration

Caution: As of SDK Tools Revision 17, the virtual machine acceleration feature for the emulator is experimental; be alert for incompatibilities and errors when using this feature.

Many modern CPUs provide extensions for running virtual machines (VMs) more efficiently. Taking advantage of these extensions with the Android emulator requires some additional configuration of your development system, but can significantly improve the execution speed. Before attempting to use this type of acceleration, you should first determine if your development system’s CPU supports one of the following virtualization extensions technologies:

  • Intel Virtualization Technology (VT, VT-x, vmx) extensions
  • AMD Virtualization (AMD-V, SVM) extensions (only supported for Linux)

The specifications from the manufacturer of your CPU should indicate if it supports virtualization extensions. If your CPU does not support one of these virtualization technologies, then you cannot use virtual machine acceleration.

Note: Virtualization extensions are typically enabled through your computer BIOS and are frequently turned off by default. Check the documentation for your motherboard to find out how to enable virtualization extensions.

Once you have determined that your CPU supports virtualization extensions, make sure you can work within these additional requirements of running an emulator inside an accelerated virtual machine:

  • x86 AVD Only - You must use an AVD that is uses an x86 system image target. AVDs that use ARM-based system images cannot be accelerated using the emulator configurations described here.
  • Not Inside a VM - You cannot run a VM-accelerated emulator inside another virtual machine, such as a VirtualBox or VMWare-hosted virtual machine. You must run the emulator directly on your system hardware.
  • Other VM Drivers - If you are running another virtualization technology on your system such as VirtualBox or VMWare, you may need to unload the driver for that virtual machine hosting software before running an accelerated emulator.
  • OpenGL? Graphics - Emulation of OpenGL ES graphics may not perform at the same level as an actual device.

To use virtual machine acceleration with the emulator, you need the following version of Android development tools. Use the SDK Manager to install these components:

  • Android SDK Tools, Revision 17 or higher
  • Android x86-based system image

If your development environment meets all of the requirements for running a VM-accelerated emulator, you can use the AVD Manager to create an x86-based AVD configuration:

  1. In the Android SDK Manager, make sure you have an x86-based System Image installed for your target Android version. If you do not have an x86System Image installed, select one in the Android SDK Manager and install it.

    Tip: System images are listed under each API Level in the SDK Manager. An x86 system image may not be available for all API levels.

  2. Start the AVD Manager and create a new AVD with an x86 value for the CPU/ABI field. You may need to select a specific Target value, or select aTarget value and then select a specific CPU/ABI option.
  3. Name the emulator instance and select any other configuration options.
  4. Click Create AVD to save the emulator configuration.

Configuring VM acceleration on Windows

Virtual machine acceleration for Windows requires the installation of the Intel Hardware Accelerated Execution Manager (Intel HAXM). The software requires an Intel CPU with Virtualization Technology (VT) support and one of the following operating systems:

  • Windows 7 (32/64-bit)
  • Windows Vista (32/64-bit)
  • Windows XP (32-bit only)

To install the virtualization driver:

  1. Start the Android SDK Manager, select Extras and then select Intel Hardware Accelerated Execution Manager.
  2. After the download completes, execute <sdk>/extras/intel/Hardware_Accelerated_Execution_Manager/IntelHAXM.exe.
  3. Follow the on-screen instructions to complete installation.
  4. After installation completes, confirm that the virtualization driver is operating correctly by opening a command prompt window and running the following command:
    sc query intelhaxm

    You should see a status message including the following information:

    SERVICE_NAME: intelhaxm
               ...
           STATE                  : 4  RUNNING
               ...

To run an x86-based emulator with VM acceleration:

  • If you are running the emulator from the command line, just specify an x86-based AVD:
    emulator -avd <avd_name>

    Note: You must provide an x86-based AVD configuration name, otherwise VM acceleration will not be enabled.

  • If you are running the emulator from Android Studio, run your Android application with an x86-based AVD:
    1. In Android Studio, click your Android project folder and then select Run > Edit Configurations...
    2. In the left panel of the Run/Debug Configurations dialog, select your Android run configuration or create a new configuration.
    3. Under the Target Device options, select the x86-based AVD you created previously.
    4. Run your Android project using this run configuration.

You can adjust the amount of memory available to the Intel HAXM kernel extension by re-running its installer.

You can stop using the virtualization driver by uninstalling it. Re-run the installer or use the Control Panel to remove the software.

Configuring VM acceleration on Mac

Virtual machine acceleration on a Mac requires the installation of the Intel Hardware Accelerated Execution Manager (Intel HAXM) kernel extension to allow the Android emulator to make use of CPU virtualization extensions. The kernel extension is compatible with Mac OS X Snow Leopard (version 10.6.0) and higher.

To install the Intel HAXM kernel extension:

  1. Start the Android SDK Manager, select Extras and then select Intel Hardware Accelerated Execution Manager.
  2. After the download completes, execute <sdk>/extras/intel/Hardware_Accelerated_Execution_Manager/IntelHAXM.dmg.
  3. Double click the IntelHAXM.mpkg icon to begin installation.
  4. Follow the on-screen instructions to complete installation.
  5. After installation completes, confirm that the new kernel extension is operating correctly by opening a terminal window and running the following command:
    kextstat | grep intel

    You should see a status message containing the following extension name, indicating that the kernel extension is loaded:

    com.intel.kext.intelhaxm

To run an x86-based emulator with VM acceleration:

  • If you are running the emulator from the command line, just specify an x86-based AVD:
    emulator -avd <avd_name>

    Note: You must provide an x86-based AVD configuration name, otherwise VM acceleration will not be enabled.

  • If you are running the emulator from Andriod Studio, run your Android application with an x86-based AVD:
    1. In Android Studio, click your Android module folder and then select Run > Edit Configurations...
    2. In the left panel of the Run/Debug Configurations dialog, select your Android run configuration or create a new configuration.
    3. Under the Target Device options, select the x86-based AVD you created previously.
    4. Run your Android project using this run configuration.

You can adjust the amount of memory available to the Intel HAXM kernel extension by re-running the installer.

You can stop using the virtualization kernel driver by uninstalling it. Before removing it, shut down any running x86 emulators. To unload the virtualization kernel driver, run the following command in a terminal window:

sudo /System/Library/Extensions/intelhaxm.kext/Contents/Resources/uninstall.sh

Configuring VM acceleration on Linux

Linux-based systems support virtual machine acceleration through the KVM software package. Follow instructions for installing KVM on your Linux system, and verify that KVM is enabled. In addition to following the installation instructions, be aware of these configuration requirements:

  • Running KVM requires specific user permissions, make sure you have sufficient permissions according to the KVM installation instructions.
  • If you use another virtualization technology in your Linux platform, unload its kernel driver before running the x86 emulator. For example, the VirtualBox driver program is vboxdrv.

To run an x86-based emulator with VM acceleration:

  • If you are running the emulator from the command line, start the emulator with an x86-based AVD and include the KVM options:
    emulator -avd <avd_name> -qemu -m 512 -enable-kvm

    Note: You must provide an x86-based AVD configuration name, otherwise VM acceleration will not be enabled.

  • If you are running the emulator from Android Studio, run your Android application with an x86-based AVD and include the KVM options:
    1. In Android Studio, click your Android module folder and then select Run > Edit Configurations...
    2. In the left panel of the Run/Debug Configurations dialog, select your Android run configuration or create a new configuration.
    3. Under the Target Device options, select the x86-based AVD you created previously.
    4. In the Emulator tab, in the Additional command line options field, enter:
      -qemu -m 512 -enable-kvm
    5. Run your Android project using this run configuration.

Important: When using the -qemu command line option, make sure it is the last parameter in your command. All subsequent options are interpreted as qemu-specific parameters.

Troubleshooting Emulator Problems

The adb utility sees the emulator as an actual physical device. For this reason, you might have to use the -d flag with some common adb commands, such as install. The -d flag lets you specify which of several connected devices to use as the target of a command. If you don't specify -d, the emulator targets the first device in its list. For more information about adb, see Android Debug Bridge.

For emulators running on Mac OS X, if you see an error Warning: No DNS servers found when starting the emulator, check to see whether you have an/etc/resolv.conf file. If not, please run the following line in a command window:

ln -s /private/var/run/resolv.conf /etc/resolv.conf

来源： https://developer.android.com/studio/run/emulator-commandline.html


Run Apps on a Hardware Device

在硬件设备上运行应用

本文内容

  1. 启用设备上的开发者选项
  2. 面向开发设置设备
    1. USB 供应商 ID

另请参阅

  1. 安装 USB 驱动程序
  2. Google USB 驱动程序

构建 Android 应用时，务必要始终先在真实的设备上测试您的应用，然后再向用户发布。本页面介绍了如何针对设备测试和调试设置您的开发环境和 Android 设备。

您可以将任何 Android 设备用作运行、调试和测试应用的环境。每次编译时，SDK 中包含的工具让您可以轻松地在设备上安装和运行应用。您可以直接从 Android Studio 中将应用安装在设备上，也可以使用 ADB 从命令行安装。如果您还没有设备，请与所在地区的服务提供商确认他们可以提供哪些 Android 设备。

如果您想要一部没有 SIM 锁的电话，则可以考虑选择 Nexus 电话。要购买 Nexus 电话，请访问 Google Play商店。

注：在设备上开发时，请记住，您仍应该使用 Android Emulator 在与真实设备不同的配置上测试应用。尽管模拟器无法让您测试每一种设备功能（例如加速度计），它仍然让您能够验证应用在不同版本的 Android 平台、不同的屏幕尺寸和屏幕方向等条件下是否可以正常运行。

启用设备上的开发者选项

Android 设备拥有众多您可以在电话上访问的开发者选项，这些选项让您能够进行以下操作：

  • 启用 USB 调试。
  • 将错误报告快速记录到设备上。
  • 在屏幕上显示 CPU 使用率。
  • 在屏幕上绘制调试信息，例如布局边界、GPU 视图和硬件层更新，等等。
  • 还有很多有助于模拟应用压力或启用调试选项的其他选项。

要访问这些设置，请在系统的 Settings 中打开 Developer options。在运行 Android 4.2 及更高版本的设备上，Developer options 屏幕默认情况下处于隐藏状态。如需将其显示出来，请转到 Settings > About phone 并点按 Build number 七次。返回上一屏幕，在底部可以找到Developer options。

面向开发设置设备

利用 Android 设备，您可以开发和调试您的 Android 应用，就像在模拟器上一样。开始之前，您需要先完成以下事项：

  1. 在清单或 build.gradle 文件中验证您的应用是否“可调试”。

    在构建文件中，确保 debug 构建类型中的 debuggable 属性设为 true。构建类型属性将替换清单设置。

    android {
        buildTypes     {
            debug     {
                debuggable     true
                }

    在 AndroidManifest.xml 文件中，将 android:debuggable="true" 添加到 <application> 元素中。

    注：如果您在清单文件中手动启用调试，请确保在发布版本中将其停用（您的已发布应用通常应当不可调试）。

  2. 转到 Settings > Developer options，在您的设备上启用 USB 调试。

    注：在运行 Android 4.2 及更新版本的设备上，Developer options 默认情况下处于隐藏状态。如需将其显示出来，请转到 Settings > About phone并点按 Build number 七次。返回上一屏幕即可找到 Developer options。

  3. 设置您的系统以检测设备。
    • 如果您在 Windows 上开发，则需要为 ADB 安装 USB 驱动程序。如需安装指南和原始设备制造商驱动程序的链接，请参阅原始设备制造商 USB 驱动程序文档。
    • 如果您在 Mac OS X 上开发，则不需要进行任何操作。请跳过此步骤。
    • 如果您在 Ubuntu Linux 上开发，则需要为想要在开发中使用的每一种设备类型添加一个包含 USB 配置的 udev 规则文件。在规则文件中，每一个设备制造商都由一个唯一的供应商 ID（如 ATTR{idVendor} 属性所指定）标识。要查看供应商 ID 列表，请参见下文的 USB 供应商 ID。要在 Ubuntu Linux 上设置设备检测，请执行以下操作：
      1. 以 root 身份登录，并创建此文件：/etc/udev/rules.d/51-android.rules。

        使用下面的格式将各个供应商添加到文件中：
        SUBSYSTEM=="usb", ATTR{idVendor}=="0bb4", MODE="0666", GROUP="plugdev"

        在本例中，供应商 ID 为 HTC 的 ID。MODE 赋值指定读/写权限，GROUP 则定义哪个 Unix 组拥有设备节点。

        注：取决于您的环境，规则语法可能稍有不同。如有需要，请查阅适用于您的系统的 udev 文档。有关规则语法的概述，请参阅编写 udev 规则的指南。

      2. 现在，请执行：
        chmod a+r /etc/udev/rules.d/51-android.rules

注：当您将运行 Android 4.2.2 或更高版本的设备连接到计算机时，系统将显示一个对话框，询问您是否接受允许在这台计算机上调试的 RSA 密钥。这种安全机制可以保护用户设备，因为它可以确保只有在您能够解锁设备并确认对话框的情况下才能执行 USB 调试和其他 ADB 命令。这样，要在运行 Android 4.2.2 或更高版本的设备上调试，您必须安装 ADB 版本 1.0.31（随 SDK Platform-tools r16.0.1 及更高版本提供）。

通过 USB 充电时，您可以从 SDK platform-tools/ 目录执行 adb devices，验证您的设备是否连接。如果已连接，您将看到设备名称以“设备”形式列示。

如果使用 Android Studio，可以照常运行或调试您的应用。系统将显示 Device Chooser 对话框，其中会列出可用模拟器和已连接设备。选择要在上面安装和运行应用的设备。

如果使用 Android Debug Bridge (ADB)，您可以发出包含 -d 标记的命令，将目标确定为您的已连接设备。

USB 供应商 ID

下表提供了在 Linux 上添加 USB 设备支持所需的供应商 ID 参考。USB 供应商 ID 是为规则文件中的 ATTR{idVendor} 属性所赋的值，如上文所述。

公司 | USB 供应商 ID
Acer | 0502
ASUS | 0b05
Dell | 413c
Foxconn | 0489
Fujitsu | 04c5
Fujitsu Toshiba | 04c5
Garmin-Asus | 091e
Google | 18d1
Haier | 201E
Hisense | 109b
HP | 03f0
HTC | 0bb4
Huawei | 12d1
Intel | 8087
K-Touch | 24e3
KT Tech | 2116
Kyocera | 0482
Lenovo | 17ef
LG | 1004
Motorola | 22b8
MTK | 0e8d
NEC | 0409
Nook | 2080
Nvidia | 0955
OTGV | 2257
Pantech | 10a9
Pegatron | 1d4d
Philips | 0471
PMC-Sierra | 04da
Qualcomm | 05c6
SK Telesys | 1f53
Samsung | 04e8
Sharp | 04dd
Sony | 054c
Sony Ericsson | 0fce
Sony Mobile Communications | 0fce
Teleepoch | 2340
Toshiba | 0930
ZTE 19d2

来源：  https://developer.android.com/studio/run/device.html


Install OEM USB Drivers

安装原始设备制造商 USB 驱动程序

本文内容

  1. 安装 USB 驱动程序
    1. Windows 7
    2. Windows Vista
  2. 获取原始设备制造商驱动程序

另请参阅

  1. 在硬件设备上运行应用
  2. 安装 Google USB 驱动程序

如果您在 Windows 上开发并且想要连接设备进行测试，则需要安装合适的 USB 驱动程序。本页面提供了多家原始设备制造商 (OEM) 网站的链接，您可以从他们的网站上为您的设备下载合适的 USB 驱动程序。

如果您在 Mac OS X 或 Linux 上开发，则不需要 USB 驱动程序。请阅读使用硬件设备。

要在 Windows 上连接任意 Google Nexus 设备并进行调试，您需要安装 Google USB 驱动程序。唯一例外是 Galaxy Nexus：Galaxy Nexus 的驱动程序由 Samsung 分发（以 GT-I9250TSGGEN 型号列示）。

安装 USB 驱动程序

首先，从下面的原始设备制造商驱动程序表中查找适合您的设备的驱动程序。

下载 USB 驱动程序后，请按照下面的说明操作，根据您的 Windows 版本以及是首次安装还是升级现有驱动程序，安装或升级驱动程序。然后参阅使用硬件设备，了解使用 Android 设备进行开发的其他重要相关信息。

注意：您可能会更改 usb_driver\ 内部的 android_winusb.inf 文件（例如，为了添加对其他设备的支持），不过，这样会导致在安装或升级驱动程序时显示安全警告。对驱动程序文件进行其他更改会中断安装过程。

Windows 7 及更高版本

要在 Windows 7 及更高版本的系统上首次安装 Android USB 驱动程序，请执行以下操作：

  1. 将您的 Android 设备连接到计算机的 USB 端口。
  2. 从桌面上或 Windows 资源管理器中右键点击 Computer 图标，然后选择 Manage。
  3. 在左窗格中选择 Devices。
  4. 在右窗格中定位并展开 Other Device。
  5. 右键点击设备名称（例如 Nexus S），然后选择 Update Driver Software。这将启动硬件更新向导。
  6. 选择 Browse my computer for driver software，然后点击 Next。
  7. 点击 Browse 并定位 USB 驱动程序文件夹。（Google USB 驱动程序位于 <sdk>\extras\google\usb_driver\ 中。）
  8. 点击 Next，安装驱动程序。

或者，要在 Windows 7 及更高版本的系统上使用新驱动程序升级现有的 Android USB 驱动程序，请执行以下操作：

  1. 将您的 Android 设备连接到计算机的 USB 端口。
  2. 从桌面上或 Windows 资源管理器中右键点击 Computer 图标，然后选择 Manage。
  3. 在“计算机管理”窗口的左窗格中选择 Device Manager。
  4. 在右窗格中定位并展开 Android Phone。
  5. 右键点击 Android Composite ADB Interface，然后选择 Update Driver。这将启动硬件更新向导。
  6. 选择 Install from a list or specific location，然后点击 Next。
  7. 选择 Search for the best driver in these locations；取消选中 Search removable media；然后选中 Include this location in the search。
  8. 点击 Browse 并定位 USB 驱动程序文件夹。（Google USB 驱动程序位于 <sdk>\extras\google\usb_driver\ 中。）
  9. 点击 Next，升级驱动程序。

Windows Vista

要在 Windows Vista 系统上首次安装 Android USB 驱动程序，请执行以下操作：

  1. 将您的 Android 设备连接到计算机的 USB 端口。Windows 将检测设备并启动“发现新硬件”向导。
  2. 选择 Locate and install driver software。
  3. 选择 Don't search online。
  4. 选择 I don't have the disk.Show me other options。
  5. 选择 Browse my computer for driver software。
  6. 点击 Browse 并定位 USB 驱动程序文件夹。（Google USB 驱动程序位于 <sdk>\extras\google\usb_driver\ 中。）只要指定安装包的确切路径，选不选中 Include subfolders 都无所谓。
  7. 点击 Next。Vista 可能提示您确认驱动程序安装所需的权限提升。请确认。
  8. 当 Vista 询问是否安装 Google ADB Interface 设备时，请点击 Install，安装驱动程序。

或者，要在 Windows Vista 系统上使用新驱动程序升级现有的 Android USB 驱动程序，请执行以下操作：

  1. 将您的 Android 设备连接到计算机的 USB 端口。
  2. 从桌面上或 Windows 资源管理器中右键点击 Computer 图标，然后选择 Manage。
  3. 在左窗格中选择 Device Manager。
  4. 在右窗格中定位并展开 ADB Interface。
  5. 右键点击 Android Composite ADB Interface，然后选择 Update Driver Software。
  6. 当 Vista 开始更新驱动程序时，系统将显示一个提示，询问您想要如何搜索驱动程序软件。选择 Browse my computer for driver software。
  7. 点击 Browse 并定位 USB 驱动程序文件夹。（Google USB 驱动程序位于 <sdk>\extras\google\usb_driver\ 中。）只要指定安装包的确切路径，选不选中 Include subfolders 都无所谓。
  8. 点击 Next。Vista 可能提示您确认驱动程序安装所需的权限提升。请确认。
  9. 当 Vista 询问是否安装 Google ADB Interface 设备时，请点击 Install，升级驱动程序。

获取原始设备制造商驱动程序

原始设备制造商 | 驱动程序网址
Acer | http://www.acer.com/worldwide/support/mobile.html
alcatel one touch | http://www.alcatelonetouch.com/global-en/support/
Asus | http://support.asus.com/download/
Blackberry | https://swdownloads.blackberry.com/Downloads/entry.do?code=4EE0932F46276313B51570F46266A608
Dell | http://support.dell.com/support/downloads/index.aspx?c=us&cs=19&l=en&s=dhs&~ck=anavml
Fujitsu | http://www.fmworld.net/product/phone/sp/android/develop/
Hisense | http://app.hismarttv.com/dss/resourcecontent.do?method=viewResourceDetail&resourceId=16&type=5
HTC | http://www.htc.com 点击 Support 标签选择您的产品/设备。不同的区域拥有不同的链接。
Huawei | http://consumer.huawei.com/en/support/index.htm
Intel | http://www.intel.com/software/android
Kyocera | http://www.kyocera-wireless.com/support/phone_drivers.htm
Lenovo | http://support.lenovo.com/us/en/GlobalProductSelector
LGE | http://www.lg.com/us/support/software-firmware
Motorola | https://motorola-global-portal.custhelp.com/app/answers/detail/a_id/88481/
MTK | http://online.mediatek.com/Public%20Documents/MTK_Android_USB_Driver.zip（ZIP 下载）
Oppo | http://www.oppo.com/index.php?q=software/view&sw_id=631
Pegatron | http://www.pegatroncorp.com/download/New_Duke_PC_Driver_0705.zip（ZIP 下载）
Samsung | http://www.samsung.com/us/support/downloads
Sharp | http://k-tai.sharp.co.jp/support/
Sony Mobile Communications | http://developer.sonymobile.com/downloads/drivers/
Toshiba | http://support.toshiba.com/sscontent?docId=4001814
Xiaomi | http://www.xiaomi.com/c/driver/index.html
ZTE | http://support.zte.com.cn/support/news/NewsDetail.aspx?newsId=1000442

来源： https://developer.android.com/studio/run/oem-usb.html


Install the Google USB Driver

获取 Google USB 驱动程序

另请参阅

  1. 安装 USB 驱动程序
  2. 使用硬件设备

使用任何 Google Nexus 设备进行 ADB 调试时，只有 Windows 需要 Google USB 驱动程序。唯一例外是 Galaxy Nexus：Galaxy Nexus 的驱动程序由Samsung 分发（以 SCH-I515 型号列示）。

所有其他设备的 Windows 驱动程序都由相应的硬件制造商提供，如原始设备制造商 USB 驱动程序文档中所列。

注：如果您在 Mac OS X 或 Linux 上开发，则不需要 USB 驱动程序。请参阅使用硬件设备。

您可以通过两种方式为 Windows 下载 Google USB 驱动程序：

  • 点击此处下载 Google USB 驱动程序 ZIP 文件 (latest_usb_driver_windows.zip)。
  • 也可以从 Android SDK Manager 获取，操作如下所示：
    1. 在 Android Studio 中，点击 Tools > Android > SDK Manager。
    2. 点击 SDK Tools 标签。
    3. 选择 Google USB Driver package 并点击 Install。
    4. 继续以安装软件包。完成后，驱动程序文件将下载到 <sdk>\extras\google\usb_driver\ 目录中。

    使用 SDK 管理器可以帮助您保持驱动程序处于最新状态，它可以在您当前的驱动程序过期时向您发送通知。

有关安装信息，请阅读安装 USB 驱动程序。

来源： https://developer.android.com/studio/run/win-usb.html


Create and Edit Run/Debug Configurations

  1. About Run/Debug Configurations
  2. Opening the Run/Debug Configurations Dialog
  3. Creating a New Run/Debug Configuration
  4. Running or Debugging an App Using a Saved Configuration
  5. Editing a Run/Debug Configuration
  6. Editing a Default Run/Debug Configuration Template
  7. Sorting and Grouping Configurations
  8. Defining Before Launch Operations
  9. Default Run/Debug Configuration Templates

See also

  • Run/Debug Configurations
  • Creating and Editing Run/Debug Configurations

When you run, debug, or test your code, Android Studio uses a run/debug configuration to determine how to perform the operation. Typically, the default configuration is sufficient and you can simply click Run [image] orDebug [image] to launch your app. However, you can modify and create new configurations, and modify the default templates, to suit your development process.

About Run/Debug Configurations

Run/debug configurations specify details such as app installation, launch, and test options. You can define a configuration for one-time use, or save it for future use. After you save it, you can select the configuration from the Select Run/Debug Configuration drop-down list within the toolbar. Android Studio saves configurations as part of the project.

Default run/debug configuration

When you first create a project, Android Studio creates a default run/debug configuration for the main activity based on the Android Application template. To run or debug your project, you must always have at least one run/debug configuration defined. For this reason, we recommend that you don’t delete this configuration.

Project scope and version control

Run/debug configurations and template changes apply to the current project only. If you choose to share a run/debug configuration and then check your project into a version control system, the configuration is shared with anyone who checks out the project. You can’t share templates.

Opening the Run/Debug Configurations Dialog

The Run/Debug Configurations dialog displays your run/debug configurations and the available default templates. In this dialog, you can:

  • Create new run/debug configurations.
  • Edit run/debug configurations.
  • Edit default templates.
  • Sort and group configurations.

To open the dialog, do one of the following:

  • Select Run > Edit Configurations.
  • Select Edit Configurations from the Select Run/Debug Configuration drop-down list in the toolbar.

    • The drop-down list is to the left of Run [image] and Debug [image] ; for example, [image] .

    If the toolbar isn’t currently displayed, select View > Toolbar to display it.

The Run/Debug Configurations dialog appears, as shown in Figure 1.

Figure 1. The Run/Debug Configurations dialog.

In the left panel, the dialog displays default templates in the Defaults folder. It groups your defined configurations by template type. You can resize the dialog to see any items that are hidden.

Creating a New Run/Debug Configuration

You can define new run/debug configurations from the Run/Debug Configurations dialog, the Project window, or the Code Editor. The new configuration must be based on a default template.

In the Run/Debug Configurations dialog, you can start a new configuration directly from a template, or from a copy of another configuration. You can then change the field values as needed.

Alternatively, you can right-click an item in the Project window to automatically create a configuration specific to that item. For example, if you want to run a particular activity, you can right-click the activity Java file and select Run. Depending on the item, Android Studio uses an Android Application,Android Tests, or JUnit default template to create the configuration.

In the Code Editor, you can easily create a test and run/debug configuration for a class or method, and then execute it.

When you create a configuration outside of the Run/Debug Configurations dialog, the configuration is temporary unless you save it. By default, you can have up to five temporary configurations in the project before Android Studio starts to remove them. To change this default, in the Run/Debug Configurations dialog, click the Defaults folder and type a value in the Temporary Configurations Limit field. For more information on temporary configurations, see Creating and Saving Temporary Run/Debug Configurations.

You can share a run/debug configuration (but not a template) through your version control system. If you select Shared in your run/debug configuration and then check your project into a version control system, anyone who checks out the project receives the configuration.

Starting a configuration based on a template

To define a run/debug configuration based on a template, follow these steps:

  1. Open the Run/Debug Configurations dialog.
  2. Click Add New Configuration [image] .
  3. Select a default template.
  4. Type a name in the Name field.
  5. Modify the configuration, as needed.

    6. Be sure to correct any errors displayed at the bottom of the dialog.

  6. Click Apply or OK.

Starting a configuration from a copy

To define a run/debug configuration starting from a copy of another configuration, follow these steps:

  1. Open the Run/Debug Configurations dialog.
  2. Select an existing run/debug configuration in the left pane.
  3. Click Copy Configuration [image] .
  4. Type a name in the Name field.
  5. Modify the configuration, as needed.

    6. Be sure to correct any errors displayed at the bottom of the dialog.

  6. Click Apply or OK.

Defining a configuration for an item in the project

Android Studio can automatically create a run/debug configuration for some items displayed in the Project window. The configuration is based on a default template:

  • Activity Java file - Android Application template.
  • Package - Android Tests or JUnit template, depending on your source set. If you select an instrumented test, then it uses the Android Tests template. If you select a local unit test, then it uses the JUnit template. For a local unit test, you can optionally run with code coverage. For more information, see Code Coverage.

Note: For a build.gradle or settings.gradle file, Android Studio uses the Groovy template. Instead, you should use the Gradle Console to run or debug a build.gradle file.

To create a run/debug configuration for an item in your project, follow these steps:

  1. Open a project in Android or Project view.
  2. In the Project window, right-click an item and choose Run or Debug.

    3. Android Studio creates a temporary run/debug configuration and launches your app.

  3. To save the configuration, select Save from the Select Run/Debug Configuration drop-down list in the toolbar.

    4. The drop-down list is to the left of Run [image] and Debug [image] ; for example, [image] .

    Alternatively, right-click the item again and select Save.

    Or, select the configuration in the Run/Debug Configurations dialog and click Save Configuration [image] on the upper left.

    Except for an activity, if you right-click and then run or debug the same item again, Android Studio creates a new configuration.

Defining a test configuration for a class or method

Android Studio lets you define a test run configuration for a class or method, and then execute it. For example, if you create a new class, you can create and run a test for it. If the test passes, you can then run the tests for the rest of the project to make sure that your new code doesn’t break anything somewhere else.

Android Studio uses the Android Tests or JUnit template, depending on your source set. For a local unit test, you can optionally run with code coverage.

To create a run/debug configuration for a class or method in your Java code, follow these steps:

  1. Open a project in Android or Project view.
  2. Open a Java file in the Code Editor.
  3. Select a class or method in the code, and then press Ctrl+Shift+T (??T).
  4. Select Create New Test from the menu that appears.
  5. In the Create Test dialog, optionally change the field values, and then click OK.
  6. In the Choose Destination Directory dialog, select androidTest to create an instrumented test or test to create a local unit test. Click OK.

    7. The new test appears in the Project window in the corresponding test source set.

  7. To run the test, do one of the following:
    • In the Project window, right-click the test and select Run or Debug.
    • In the Code Editor, right-click a class definition in the test file and select Run or Debug to test all methods in the class.
    • In the Code Editor, right-click a method name in the test file and select Run or Debug to test just that method.
    • In the Code Editor, click Play [image] in the left margin next to a class or method and select Run or Debug.
  8. To save the configuration, select Save from the Select Run/Debug Configuration drop-down list within the toolbar.

    9. The drop-down list is to the left of Run [image] and Debug [image] ; for example, [image] .

    Alternatively, right-click the item again and select Save.

    Or, select the configuration in the Run/Debug Configurations dialog and click Save Configuration [image] on the upper left.

Running or Debugging an App Using a Saved Configuration

If you’ve saved a run/debug configuration, you can select it before you run or debug your app.

To use a saved run/debug configuration, follow these steps:

  1. Select the run/debug configuration from the Select Run/Debug Configuration drop-down list within the toolbar.

    2. The drop-down list is to the left of Run [image] and Debug [image] ; for example, [image] .

  2. Click Run [image] or Debug [image] .

Note: During an Instant Run session, selecting a different run/debug configuration, and then clicking Run [image] or Debug [image] again, ends the current session.

Editing a Run/Debug Configuration

To edit a run/debug configuration, follow these steps:

  1. Open the Run/Debug Configurations dialog.
  2. Select a configuration in the left pane.
  3. Modify the configuration, as needed.

    4. Be sure to correct any errors displayed at the bottom of the dialog.

  4. Click Apply or OK.

Editing a Default Run/Debug Configuration Template

You can edit the default templates provided by Android Studio to suit your development process. When you edit a template, it doesn’t affect existing configurations that use the template. So, for example, if you need to create a number of configurations of a certain type, you can edit the template and then change it back when you’re done.

Although you can’t create new templates, you can create configurations to use similar to a template. You can copy a configuration and edit the copy to create new configurations.

To edit a template, follow these steps:

  1. Open the Run/Debug Configurations dialog.
  2. Expand the Defaults folder and select a default template.
  3. Modify the configuration, as needed.

    4. Be sure to correct any errors displayed at the bottom of the dialog.

  4. Click Apply or OK.

Sorting and Grouping Configurations

In the Run/Debug Configurations dialog, you can order your configurations to be able to find them quickly. You can sort the items in the folder alphabetically, and create new folders to group configurations.

To sort configurations alphabetically, follow these steps:

  1. Open the Run/Debug Configurations dialog.
  2. Select a folder containing configurations.
  3. Click Sort Configurations [image] .
  4. Click Apply or OK.

To group configurations in folders, follow these steps:

  1. Open the Run/Debug Configurations dialog.
  2. Select a folder containing configurations.
  3. Click Create New Folder [image] .
  4. Type a name in the Name field.
  5. Drag items in the same template category into the folder.
  6. Order the folders and configurations in the same template category by dragging them into position or using Move Up [image] and Move Down [image] .
  7. Click Apply or OK.

Defining Before Launch Operations

You can specify tasks to execute before applying the run/debug configuration. The tasks are performed in the order they appear in the list. Defining before launch tasks is an advanced feature.

Instead of using this feature, we recommend that you put any preparation logic as tasks in your build.gradle file so they’ll be executed when building from the command line.

To create a task list, follow these steps:

  1. To add a task to the list, click Add [image] and select a task type. If a dialog opens, fill in the fields and click OK.
  2. Add more tasks as needed.
  3. To order the tasks, select a task and click Up [image] and Down [image] to move it up or down in the list.
  4. Select Show this page if you want to display the run/debug configuration settings before applying them.

    This option is deselected by default.

  5. Select Active tool window if you want the Run or Debug tool window to be activated automatically when you run or debug your app.

    6. This option is selected by default.

To remove a task from the list, follow these steps:

  1. Select a task.
  2. Click Remove [image] .

To edit a task, follow these steps:

  1. Select a task.
  2. Click Edit [image] .
  3. Edit the task settings in the dialog that opens, and then click OK.

The following table lists the available tasks you can add.

Task | Description
Run External tool | Run an application that’s external to Android Studio. In the External Tools dialog, select one or more applications that you want to run and then click OK. If the application isn’t defined in Android Studio yet, add its definition in the Create Tools dialog. For more information, see Configuring Third-Party Tools and External Tools.
Run Another Configuration | Execute one of the existing run/debug configurations. In the Choose Configuration to Execute dialog, select a configuration to execute and then click OK.
Make | Compile the project or the module. Android Studio executes the Make Module command if the run/debug configuration specifies a particular module, or it executes the Make Project command if no modules are specified.
Make Project | Compile the project. Android Studio executes the Make Project command.
Make, no error check | This option is the same as Make, except that Android Studio executes the run/debug configuration irrespective of the compilation result.
Build Artifacts | Unsupported in Android Studio.
Run Gradle task | Run a Gradle task. In the dialog that opens, specify the details and then click OK. For more information, see Gradle.
Gradle-aware Make | Compile the project and run Gradle.
App Engine Gradle builder | The App Engine Gradle builder task syncs the project and then does a build of the module.

Default Run/Debug Configuration Templates

Android Studio provides default configuration templates to help you get started quickly. The following templates are applicable to Android development with Android Studio:

  • Android Application
  • Android Native
  • Android Tests
  • App Engine DevAppServer
  • JUnit

Note: The Android Native template is essentially the same as Android Application and might not be available in the future. You should use the Android Application template instead for your native apps.

The following unsupported templates come from IntelliJ IDEA and aren’t specific to Android development with Android Studio:

  • Application
  • Compound
  • Gradle
  • Groovy
  • JAR Application
  • JUnit Test Discovery
  • Java Scratch
  • Remote
  • TestNG
  • TestNG Test Discovery

Follow the links to the IntelliJ IDEA documentation for details on using these templates.

Android Application

You can run or debug Android apps and activities on virtual or hardware devices by using configurations based on this template.

Name and share

A run/debug configuration has the Name and Share options, while the template doesn’t.

Field | Description
Name | The name of the run/debug configuration.
Share

Select this option to make the run/debug configuration available to other team members through version control. You can share a run/debug configuration, but not a template. If you select this option, when the project is checked into Git (or another version control system), the run/debug configuration is included when someone checks out the project.

Android Studio stores the shared run/debug configuration in an individual XML file in the .idea/runConfigurations folder; otherwise, it stores the configuration in the .idea/workspace.xml file. For more information, see Directory-based Project Format.

Default: deselected

General tab

In the General tab, you can specify installation, launch, and deployment options. The Miscellaneous tab also contains installation options.

Field | Description
Module | Select a module to apply this configuration to.
Installation Options: Deploy

Select an option:

  • Default APK (default) - Create an APK as specified in your build configuration.
  • Custom Artifact - Unsupported in Android Studio.
  • Nothing - Don’t install an APK on a device. For example, if you prefer to manually install the APK, you don’t need Android Studio to install it.
Installation Options: Install Flags Type any adb pm install options you want to use. Format the options as you would on the command line, but without a path. Here are some examples:

-i foo.bar.baz -r /path/to/apk

and

-d -r

Default: no options

Launch Options: Launch

Select an option:

  • Nothing - Don’t launch anything. If you’ve specified Nothing in the Deploy field, your app is already running, and you select Debug, this option is similar to using Attach debugger to Android process; selecting Run does nothing.
  • Default Activity (default) - Launch the activity you’ve marked as startup in the manifest. For example:
    • <intent-filter>
  <action android:name="android.intent.action.MAIN" />
  <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
  • Specified Activity - Launch a particular app activity in your module. Type the name, or click … to select an activity from a list.
  • URL - Specify a URL to launch. See Testing a URL.
Launch Options: Launch Flags Type any adb am start options you want to use. Format the options as you would on the command line, but without an intent. For example:

-W --opengl-trace

This option doesn’t appear if you chose a Launch value of Nothing.

Default: no options

Deployment Target Options: Target

Select an option:

  • Show Device Chooser Dialog (default) - Open the Select Deployment Target dialog to select a virtual or hardware device.
  • USB Device - Use a hardware device connected to your development computer through a USB port. If there’s more than one, a dialog appears so you can select it.
  • Emulator - Use a virtual device. In a configuration, you can select an AVD; otherwise, it just uses the first AVD in the list.

Deployment Target Options: Use same device for future launches

If you want to automatically use the device you chose through the Select Deployment Target dialog in the future, select this option. If the device isn’t available, you’ll receive a dialog. Default: deselected
Before Launch | See Defining Before Launch Operations.

Miscellaneous tab

In the Miscellaneous tab, you can specify logcat, installation, launch, and deployment options. The General tab also contains installation options.

Field | Description
Logcat: Show logcat automatically | When this option is selected, the logcat tab of Android Monitor activates automatically every time you successfully deploy and launch an app using this configuration. Otherwise, the focus doesn’t move to the logcattab automatically on app start. Default: selected
Logcat: Clear log before launch | Select this option if you want Android Studio to remove data from previous sessions from the log file before starting the app. Default: deselected
Installation Options: Skip installation if APK has not changed | When selected, Android Studio doesn’t redeploy your APK if it detects that it’s unchanged. If you want Android Studio to force an install of the APK, even if it hasn’t changed, then deselect this option. Default: selected
Installation Options: Force stop running application before launching activity

If selected, when Android Studio detects that it doesn't have to reinstall an APK because it hasn’t changed, it will force-stop the app so that the app starts from the default launcher activity. If this option is deselected, Android Studio doesn’t force-stop the app.

This option works in conjunction with the previous option that controls whether an APK is installed or not. For both Installation Options fields, leave them at the default unless you explicitly want to force an install every time.

In some cases you might want to deselect this option. For example, if you’re writing an input method engine (IME), force-stopping the app deselects it as the current keyboard, which you might not want.

Default: selected

Before Launch | See Defining Before Launch Operations.

Debugger tab

Specify debug options in the Debug tab.

Field | Description
Debug type | Select Java, Native, or Hybrid. The latter two options are applicable only if your project contains some native C or C++ source code. See Debug Your App. Default: Java
Before Launch | See Defining Before Launch Operations.

Profiling tab

Specify GPU Debugger profiling options for Android Monitor in the Profiling tab.

Field | Description
Graphics Trace Options: Disable precompiled shaders and programs

Select this option to disable OpenGL ES graphics driver support for precompiled shader and program binaries during tracing. This option is relevant for the GPU Debugger tool.

Precompiled shaders aren’t supported for replaying traces, and so only shaders compiled at runtime using theglShaderSource function can be used for framebuffer inspection.

Apps should always query for precompiled shader support before using the glShaderBinary orglProgramBinary functions, and fall back to runtime compilation if precompiled shaders or programs aren’t supported.

Default: deselected

Before Launch | See Defining Before Launch Operations.

Android Tests

The tests template that you should use depends on your source set. The Android Tests template is for an instrumented test. The JUnit template is for a local unit test.

If you're using Google Cloud Test Lab to test on a variety of devices, you can use this template to define your instrumented tests. For more information, see Using Cloud Test Lab from Android Studio.

Name and share

A run/debug configuration has the Name and Share options, while the template doesn’t.

Field | Description
Name | The name of the run/debug configuration.
Share

Select this option to make the run/debug configuration available to other team members through version control. You can share a run/debug configuration, but not a template. If you select this option, when the project is checked into Git (or another version control system), the run/debug configuration is included when someone checks out the project.

Android Studio stores the shared run/debug configuration in an individual XML file in the .idea/runConfigurations folder; otherwise, it stores the configuration in the .idea/workspace.xml file. For more information, see Directory-based Project Format.

Default: deselected

General tab

In the General tab, you can specify test location, instrumentation runner, adb shell, and deployment options.

Field | Description
Module | Select a module to apply this configuration to.
Test

In this area, specify the location of tests that you want to run:

  • All in module (default) - Launch all tests from the selected module.
  • All in package - Launch all tests from the package specified in the Package field. Type the name, or click … to select the package from a dialog.
  • Class - Launch tests of the class specified in the Class field. Type the name, or click … to select the class from a dialog.
  • Method - Launch a test method. In the Class field, specify the class that contains the method. In the Method field, specify the method. Type the name, or click … to select the class or method from a dialog.
Specific instrumentation runner (optional) | Type the location of the instrumentation runner; click … to use a dialog. The build.gradle file specifies the location of the instrumentation runner; this value overrides it. The default is typically the AndroidJUnitRunner class from theAndroid Testing Support Library .
Extra options | Type any adb am instrument options you want to use. Don’t type the component. For example, if you’re usingAndroidJUnitRunner from the Android Testing Support Library, you can use this field to pass additional options to the runner, such as -e size small. Default: no options
Deployment Target Options: Target

Select an option:

  • Show Device Chooser Dialog (default) - Open the Select Deployment Target dialog to select a virtual or hardware device.
  • USB Device - Use a hardware device connected to your development computer through a USB port. If there’s more than one, a dialog appears so you can select it.
  • Emulator - Use a virtual device. In a configuration, you can select an AVD; otherwise, it just uses the first AVD in the list.
Deployment Target Options: Use same device for future launches | If you want to automatically use the device you chose through the Select Deployment Target dialog in the future, select this option. If the device isn’t available, you’ll receive a dialog. Default: deselected
Before Launch | See Defining Before Launch Operations.

Miscellaneous tab

The Miscellaneous tab contains logcat and installation options.

Field | Description
Logcat: Clear log before launch | Select this option if you want data from previous sessions to be removed from the log file before starting the app. Default: deselected
Installation Options: Skip installation if APK has not changed | When selected, Android Studio doesn’t redeploy your APK if it detects that it’s unchanged. If you want Android Studio to force an install of the APK, even if it hasn’t changed, then deselect this option. Default: selected
Installation Options: Force stop running application before launching activity

If selected, when Android Studio detects that it doesn't have to reinstall an APK because it hasn’t changed, it will force-stop the app so that the app starts from the default launcher activity. If this option is deselected, Android Studio doesn’t force-stop the app.

This option works in conjunction with the previous option that controls whether an APK is installed or not. For both Installation Options fields, leave them at the default unless you explicitly want to force an install every time.

In some cases you might want to deselect this option. For example, if you’re writing an input method engine (IME), force-stopping the app deselects it as the current keyboard, which you might not want.

Default: selected

Before Launch | See Defining Before Launch Operations.

Debugger tab

Specify debug options in the Debug tab.

Field | Description
Debug type | Select Java, Native, or Hybrid. The latter two options are applicable only if your project contains some native C or C++ source code. See Debug Your App. Default: Java
Before Launch | See Defining Before Launch Operations.

Profiling tab

Specify GPU Debugger profiling options for Android Monitor in the Profiling tab.

Field | Description
Graphics Trace Options: Disable precompiled shaders and programs

Select this option to disable OpenGL ES graphics driver support for precompiled shader and program binaries during tracing. This option is relevant for the GPU Debugger tool.

Precompiled shaders aren’t supported for replaying traces, and so only shaders compiled at runtime using theglShaderSource function can be used for framebuffer inspection.

Apps should always query for precompiled shader support before using the glShaderBinary orglProgramBinary functions, and fall back to runtime compilation if precompiled shaders or programs aren’t supported.

Default: deselected

Before Launch | See Defining Before Launch Operations.

App Engine DevAppServer

This run/debug configuration applies to the Google Cloud Platform. For more information, see Adding an App Engine Java Servlet Module and Running, Testing, and Deploying the Backend. When you follow these steps and sync your project to the build.gradle file, Android Studio creates an App Engine DevAppServer configuration for you.

Note that the IntellJ IDEA App Engine Server template is a different template that’s not available in Android Studio.

Field | Description
Name | The name of the run/debug configuration.
Share

Select this option to make the run/debug configuration available to other team members through version control. You can share a run/debug configuration, but not a template. If you select this option, when the project is checked into Git (or another version control system), the run/debug configuration is included when someone checks out the project.

Android Studio stores the shared run/debug configuration in an individual XML file in the .idea/runConfigurations folder; otherwise, it stores the configuration in the .idea/workspace.xml file. For more information, see Directory-based Project Format.

Default: deselected

Single instance only | If you want to make sure that only one instance of the run/debug configuration is currently executed, select this option. It doesn't allow multiple runs of the same configuration at the same time. Default: selected
Module | Select a module to apply this configuration to.
Synchronize with build.gradle configuration | If you add an App Engine module and sync to the build.gradle file, the App Engine DevAppServer configuration fields are filled in for you (recommended). Selecting Tools > Android > Sync Project with Gradle Files also syncs the project. Default: selected
App Engine SDK | Type a path to a Google App Engine SDK for Java on the local machine. Click ... to select it from a dialog.
War Path | Type a path to the Web Application Archive (WAR) directory of the app you’re deploying on the local development server. Click ... to select it from a dialog.
VM Args

Specify the command-line options you want to pass to the VM for launching the DevAppServer. When specifying the options:

  • Use spaces to separate different options.
  • For options that have spaces, enclose the space in quotation marks (" " ).
  • If an option includes quotation marks, add a backslash before the quotation mark (\").

For more information about VM options, see the documentation for your J2SE version, such as java JDK 7 and java JDK 8.

Default: no options

Server Address | Type the host address to use for the server. You might need to provide the address to be able to access the development server from another computer on your network. An address of 0.0.0.0 allows both localhost access and hostname access. Default: localhost
Server Port | Type the port number to use for the server. Default: 8080
Disable Check for App Engine SDK Updates | If given, the development server will not contact App Engine to check for the availability of a new release of the SDK. By default, the server checks for a new version on startup, and prints a message if a new version is available.
Before Launch | See Defining Before Launch Operations.

来源： https://developer.android.com/studio/run/rundebugconfig.html


构建和运行您的应用

本文内容

  1. 选择和构建不同模块
  2. 更改运行/调试配置
  3. 更改构建变体
  4. 监控构建流程
  5. 生成 APK
  6. 关于 Instant Run
    1. 针对 Instant Run 配置和优化您的项目
    2. Instant Run 的限制

另请参阅

  1. 配置构建
  2. 在 Android Emulator 上运行应用
  3. 在硬件设备上运行应用

默认情况下，Android Studio 仅需点击几下即可设置要部署至模拟器或物理设备的新项目。使用 Instant Run，您无需构建新的 APK，就可以将更改推送至方法，将现有应用资源推送至正在运行的应用，所以几乎立刻就能看到代码更改。

要构建和运行应用，请点击 Run [image] 。Android Studio 使用 Gradle 构建您的应用，会要求您选择部署目标（模拟器或连接的设备），然后将您的应用部署至目标。您可以通过更改运行配置自定义一些这样的默认行为，例如选择自动部署目标。

如果想要使用 Android Emulator 运行您的应用，您需要准备好 Android Virtual Device (AVD)。如果您尚未创建模拟器，点击 Run 后，在 Select Deployment Target 对话框中点击 Create New Emulator。按照 Virtual Device Configuration 向导操作，定义您想要模拟的设备类型。如需了解详细信息，请参阅创建和管理虚拟设备。

如果您正在使用物理 Android 设备，则需要在设备上启用 USB 调试。如需了解详细信息，请参阅在硬件设备上运行应用。

注：您也可以通过点击 Debug [image] ，在调试模式下部署应用。在调试模式下运行应用让您可以在代码中设置断点、在运行时检查变体和评估表达式，以及运行调试工具。如需了解详细信息，请参阅调试应用。

选择和构建不同模块

如果您的项目除默认应用模块之外还有多个模块，可以执行以下操作来构建特定模块：

  • 在 Project 面板中选择模块，然后点击 Build > Make Module module-name。

Android Studio 使用 Gradle 构建模块。模块构建后，如果您已经为新应用或新设备构建了模块，可以运行和调试模块；或者如果您已构建了库或 Google 云模块，可以将其用作依赖项。

要运行构建的应用模块，请执行以下操作：

  • 点击 Run > Run，然后从 Run 对话框中选择模块。

更改运行/调试配置

运行/调试配置指定要运行的模块、要部署的软件包、要启动的活动、目标设备、模拟器设置、logcat 选项，等等。默认运行/调试配置会启动默认项目活动并使用 Select Deployment Target 对话框选择目标设备。如果默认设置不适合您的项目或模块，您可以自定义运行/调试配置，也可以在项目、默认和模块级别创建新配置。要编辑运行/调试配置，请选择 Run > Edit Configurations。如需了解详细信息，请参阅创建和编辑运行/调试配置。

更改构建变体

默认情况下，在您点击 Run 后，Android Studio 可以构建应用的调试版本，不过仅用于测试目的。您需要构建发布版本，为应用公开发布做准备。

要更改 Android Studio 使用的构建变体，请转到 Build > Select Build Variant，然后从下拉菜单中选择不同的变体。默认情况下，新项目使用调试和发布构建变体进行设置。

使用产品定制，您可以为不同版本的应用（每个版本的应用均具有不同功能或设备要求）创建其他的构建变体。要了解有关构建变体和产品定制的详细信息，请参阅配置构建。

监控构建流程

您可以通过点击 Gradle Console [image] 来查看与构建流程相关的详细信息。控制台会显示为构建应用 Gradle 执行的每个任务，如图 1 所示。

图 1.Android Studio 中的 Gradle 控制台。

如果您的构建变体使用产品定制，Gradle 也会调用任务来构建这些产品定制。要查看所有可用构建任务的列表，请点击 IDE 窗口右侧的 Gradle [image] 。

如果构建过程中出现错误，会出现 Messages 窗口，对问题进行具体描述。Gradle 会建议一些命令行选项来帮助您解决问题，例如 --stacktrace 或 --debug。要在构建流程中使用命令行选项，请执行以下操作：

  1. 打开 Settings 或 Preferences 对话框：
    • 在 Windows 或 Linux 上，从主菜单中选择 File > Settings。
    • 在 Mac OSX 上，从主菜单中选择 Android Studio > Preferences。
  2. 导航至 Build, Execution, Deployment > Compiler。
  3. 在 Command-line Options 旁的文本字段中，输入您的命令行选项。
  4. 点击 OK 保存，然后退出。

Gradle 会在下次您尝试构建应用时应用这些命令行选项。

生成 APK

点击 Run 时，Android Studio 会生成调试 APK 并将其部署至您的目标设备。在您生成用于公开分发的应用发布版本前，必须首先学习如何签署应用。然后，您可以生成多个调试或发布构建变体的签署 APK。要定位生成的 APK 文件，请点击弹出对话框中的链接，如图 2 所示。

图 2.点击链接定位已生成的 APK 文件。

关于 Instant Run

Android Studio 2.0 中引入的 Instant Run 是 Run [image] 和 Debug [image] 命令的行为，可以大幅缩短应用更新的时间。尽管首次构建可能需要花费较长的时间，Instant Run 在向应用推送后续更新时则无需构建新的 APK，因此，这样可以更快地看到更改。

仅在您部署调试构建变体、使用 Android Plugin for Gradle 版本 2.0.0 或更高版本，以及在应用的模块级别 build.gradle 文件中将 minSdkVersion 设置为 15 或以上时，Instant Run 才受支持。为获得最佳性能，可以将minSdkVersion 设置为 21 或更高。

部署应用后，Run [image] 按钮（或 Debug [image] 按钮）中会出现黄色的小闪电图标，表明 Instant Run 已经准备好在您下次点击按钮时推送更新。无需构建新的 APK 即可推送新的更改，一些情况下，应用甚至无需重启就可以立即显示代码更改的效果。

Instant Run 通过执行热交换、温和交换或冷交换向连接的设备或模拟器推送更新的代码和资源。它会根据所做更改的类型自动确定要执行的交换类型。上面的视频提供了有关所有这些如何在后台运行的十分有趣的详细信息。要获得您将特定代码更改推送至目标设备时 Instant Run 如何工作的快速摘要，请参见下表。

代码更改 Instant Run 行为
  • 更改现有方法的实现代码

通过热交换支持：这是最快的交换类型，使更改能够更快地显示。您的应用保持运行，下次调用存根方法时会使用具有新实现的存根方法。

热交换不会重新初始化您正在运行的应用中的对象。您需要重新启动当前的活动，或者重新启动应用才能看到特定更新。默认情况下，Android Studio 在执行热交换后会自动重新启动当前的活动。如果您不想重新启动，可以停用自动活动重新启动。

  • 更改或移除现有资源
通过温和交换支持：这种交换速度也非常快，但 Instant Run 在将更改的资源推送至您的应用时必须重新启动当前的活动。您的应用保持运行，活动重新启动时屏幕上会出现小闪烁 - 这是正常情况。
结构性的代码更改，例如：
  • 添加、移除或更改：
    • 注释
    • 实例字段
    • 静态字段
    • 静态方法签名
    • 实例方法签名
  • 更改当前类从其继承的父类
  • 更改实现的界面列表
  • 更改类的静态初始值设定项
  • 对使用动态资源 ID 的布局元素重新排序

通过冷交换支持（API 级别 21 或更高）：这种交换速度有点慢，因为尽管不需要新的 APK，Instant Run 在推送结构性的代码更改时必须重新启动整个应用。

对于运行 API 级别 20 或更低的目标设备，Android Studio 会部署完整的 APK。

  • 更改应用清单
  • 更改应用清单引用的资源
  • 更改 Android 小部件 UI 元素（需要清除并重新运行）

对应用的清单或清单引用的资源进行更改时，Android Studio 会自动部署新构建以应用这些更改。这是因为设备上安装了 APK 时应用相关的特定信息（如它的名称、应用图标资源和 Intent 过滤器）均通过清单确定。

如果您的构建流程自动更新应用清单的任何部分，如自动循环访问 versionCode 或versionName，您将无法体验到 Instant Run 的全部性能优势。使用 Instant Run 时，您应该在调试构建变体中停用对应用清单的任何部分进行自动更新。

更新 Android 小部件 UI 元素时，您需要执行清除并重新运行以查看更改。或者，因为使用 Instant Run 时执行整洁的构建可能需要花费较长时间，您也可以在对小部件 UI 进行更新时暂时停用 Instant Run。

注：如果您需要在崩溃后重新启动应用，请不要从目标设备启动应用。从目标设备重启应用将不会应用自上次冷交换或增量构建之后的任何代码更改。要启动应用并应用所有最近的更改，请在 Android Studio 中点击 Run [image] （或 Debug [image] ）。

使用重新运行

推送影响特定初始值设定项的代码更改（例如对应用的 onCreate() 方法的更改）时，您需要重新启动应用，以便使更改生效。要执行增量构建并重新启动应用，请点击 Rerun [image] 。

如果您需要部署整洁的构建，请从主菜单中选择 Run > Clean and Rerun [image] ，也可以在点击 Rerun [image] 时按住 Shift 键。此操作会停止运行的应用，执行完整、整洁的构建，然后将新的 APK 部署至您的目标设备。

停用活动自动重新启动

执行热交换时，您的应用会保持运行，但 Android Studio 会自动重新启动当前的活动。要停用此默认设置，请执行以下操作：

  1. 打开 Settings 或 Preferences 对话框：
    • 在 Windows 或 Linux 上，从主菜单中选择 File > Settings。
    • 在 Mac OSX 上，从主菜单中选择 Android Studio > Preferences。
  2. 导航至 Build, Execution, Deployment > Instant Run。
  3. 取消选中 Restart activity on code changes 旁边的方框。

如果停用活动自动重新启动，您可以选择 Run > Restart Activity，从菜单栏中手动重新启动当前的活动。

针对 Instant Run 配置和优化您的项目

默认情况下，Android Studio 会为使用 Android Plugin for Gradle 2.0.0 及更高版本构建的项目启用 Instant Run。

要使用最新版本的插件更新现有项目，请执行以下操作：

  1. 打开 Settings 或者 Preferences 对话框。

  2. 导航至 Build, Execution, Deployment > Instant Run，然后点击 Update Project，如图 3 所示。

    如果用于更新项目的选项未显示，则说明项目已经带有最新版本的 Android Plugin for Gradle，处于最新状态。

    图 3.更新现有项目的 Android Plugin for Gradle。

您还需要更改构建变体才能开始使用 Instant Run，将变体改为应用的调试版本。

通过配置 DEX 资源缩短构建时间

部署整洁的构建时，Android Studio 会将您的应用设置为允许 Instant Run 推送代码和资源更新。尽管更新正在运行的应用要快得多，第一次构建却可能需要较长的时间才能完成。您可以通过配置多个 DexOptions 设置来加快构建流程：

maxProcessCount
设置可以并行启动的 DEX 进程的最大数量。如果 Gradle 后台进程已在运行，您需要先停止此进程，然后使用新的最大进程数进行初始化。您可以从 Terminal 窗口中调用下面的一种函数来终止 Gradle 后台进程：
  • 在 Windows 上，请调用 gradlew --stop
  • 在 Linux/Mac OSX 上，请调用 ./gradlew --stop
javaMaxHeapSize
设置 dex 操作的最大内存分配池大小。传递值时，您可以附加字母“k”来表示千字节，附加“m”表示兆字节，或者附加“g”表示千兆字节。

下面的示例会在模块级别的 build.gradle 文件中将 maxProcessCount 设为 4，以及将 javaMaxHeapSize 设为“2g”：

android {
  ...
  dexOptions {
    maxProcessCount 4 // this is the default value
    javaMaxHeapSize "2g"
  }
}

您应增大设置的值并观察对构建时间产生的影响，对这些设置进行测试。如果您向 dexing 进程分配过多的资源，则可能导致性能下降。

启用 dexing-in-process 和增量 Java 编译

Android Plugin for Gradle 版本 2.1.0 及更高版本还引入了其他的构建流程改进，包括增量 Java 编译和 dexing-in-process。增量 Java 编译默认情况下处于启用状态，这种编译方式仅对发生变化或需要重新编译的源代码部分进行重新编译，可以缩短开发过程中的编译时间。

dexing-in-process 在构建流程而不是单独的外部 VM 流程中执行 dexing。这样不仅可以让增量构建更快，也可以显著提高完整构建的速度。要启用此功能，您需要将 Gradle 后台进程的最大堆大小设置为至少 2048 MB。要进行设置，您可以将以下代码包含到项目的 gradle.properties 文件中：

org.gradle.jvmargs = -Xmx2048m

如果您已经在模块级别的 build.gradle 文件中为 javaMaxHeapSize 定义值，则需要将后台进程的最大堆大小设置为 javaMaxHeapSize 的值 + 1024 MB。例如，如果您已将 javaMaxHeapSize 设为“2g”，则需要将以下代码添加到项目的 gradle.properties 文件中：

org.gradle.jvmargs = -Xmx3072m

从 Windows Defender 中排除您的项目

在 Windows 系统上，Windows Defender 可能导致 Instant Run 的运行速度变慢。如果您正在使用 Windows Defender，应当从 Windows Defender 恶意软件扫描中排除您的 Android Studio 项目文件夹。

缩短使用 Crashlytics 时的构建时间

如果您的 Fabric Gradle 插件版本低于 1.21.6，Crashlytics 可能会导致构建时间变长。要提升应用开发期间的构建性能，您可以将插件升级到最新版本或者为您的调试构建变体停用 Crashlytics。

Instant Run 的限制

大多数情况下，Instant Run 可以加快构建和部署流程的速度。不过，使用 Instant Run 时有一些限制因素可能影响其行为以及与您应用的兼容性。如果您在使用 Instant Run 时遇到其他问题，请提交错误。

部署到多种设备

Instant Run 使用多种不同的技术执行特定于目标设备 API 级别的热交换、温和交换和冷交换。因此，同时将应用部署到多种设备时，Android Studio 会暂时关闭 Instant Run。

应用的 Dalvik 可执行文件分包

如果您的项目面向旧版 Dalvik 可执行文件分包（即，使用 multiDexEnabled true 和 minSdkVersion 20 或更低版本配置 build.gradle）配置并且您将其部署到运行 Android 4.4（API 级别 20）或更低版本系统的目标设备上，Android Studio 会停用 Instant Run。

如果将 minSdkVersion 设为 21 或更高，Instant Run 会自动将应用配置为进行 Dalvik 可执行文件分包。由于 Instant Run 仅适用于调试版本的应用，在部署发布构建变体时，您需要配置应用进行 Dalvik 可执行文件分包。

运行仪器测试和性能分析器

仪器测试会将调试 APK 和测试 APK 同时加载到测试设备上的相同进程中，这样，控制方法可以替换应用的正常生命周期并执行测试。在运行或调试仪器测试时，Android Studio 不会注入 Instant Run 需要的其他方法并将此功能关闭。

分析应用时，您应停用 Instant Run。使用 Instant Run 会轻微影响性能，而替换具有热交换的方法则会产生稍大的影响。这种性能影响会干扰性能分析工具提供的信息。此外，每次热交换生成的存根方法都会使堆叠追踪变得复杂。

使用第三方插件

使用 Instant Run 时，Android Studio 会暂时停用 Java Code Coverage Library (JaCoCo) 和 ProGuard。由于 Instant Run 仅适用于调试版本，停用不会影响您的发布版本。

某些执行字节码增强的第三方插件可能会对 Instant Run 设置应用的方式造成影响。如果您遇到这些问题，但是想要继续使用 Instant Run，那么应针对您的调试构建变体停用这些插件。您还可以通过提交错误的方式帮助提升与第三方插件的兼容性。

将更改推送至多进程应用

为了执行热交换和温和交换，Instant Run 仅设置应用的主进程。将代码更改（例如对方法实现或现有资源的更改）推送至其他应用进程时，Instant Run 会执行冷交换。

停用 Instant Run

要停用 Instant Run，请执行以下操作：

  1. 打开 Settings 或者 Preferences 对话框。
  2. 导航至 Build, Execution, Deployment > Instant Run。
  3. 取消选中 Enable Instant Run 旁边的方框。
    来源： https://developer.android.com/studio/run/index.html


Configure Your Build

  1. The Build Process
  2. Custom Build Configurations
  3. Build Configuration Files
    1. The Gradle Settings File
    2. The Top-level Build File
    3. The Module-level Build File
    4. Gradle Properties Files
    5. Syncing Project with Gradle Files
    6. Source Sets

See also

  • Create and Edit Run/Debug Configurations

VIDEO

The New Android SDK Build System

The Android build system compiles app resources and source code, and packages them into APKs that you can test, deploy, sign, and distribute. Android Studio uses Gradle, an advanced build toolkit, to automate and manage the build process, while allowing you to define flexible custom build configurations. Each build configuration can define its own set of code and resources, while reusing the parts common to all versions of your app. The Android Plugin for Gradle works with the build toolkit to provide processes and configurable settings that are specific to building and testing Android applications.

Gradle and the Android plugin run independent of Android Studio. This means that you can build your Android apps from within Android Studio, the command line on your machine, or on machines where Android Studio is not installed (such as continuous integration servers). If you are not using Android Studio, you can learn how to build and run your app from the command line. The output of the build is the same whether you are building a project from the command line, on a remote machine, or using Android Studio.

Note: Because Gradle and the Android plugin run independently from Android Studio, you need to update the build tools separately. Read the release notes to learn how to update Gradle and the Android plugin.

The flexibility of the Android build system enables you to perform custom build configurations without modifying your app's core source files. This section helps you understand how the Android build system works, and how it can help you customize and automate multiple build configurations. If you simply want to learn more about deploying your app, see Building and Running from Android Studio. To start creating custom build configurations right away using Android Studio, see Configuring Build Variants.

The Build Process

The build process involves many tools and processes that convert your project into an Android Application Package (APK). The build process is very flexible, so it's useful to understand some of what is happening under the hood.

Figure 1. The build process of a typical Android app module.

The build process for a typical Android app module, as shown in figure 1, follows these general steps:

  1. The compilers convert your source code into DEX (Dalvik Executable) files, which include the bytecode that runs on Android devices, and everything else into compiled resources.
  2. The APK Packager combines the DEX files and compiled resources into a single APK. Before your app can be installed and deployed onto an Android device, however, the APK must be signed.
  3. The APK Packager signs your APK using either the debug or release keystore:
    1. If you are building a debug version of your app, that is, an app you intend only for testing and profiling, the packager signs your app with the debug keystore. Android Studio automatically configures new projects with a debug keystore.
    2. If you are building a release version of your app that you intend to release externally, the packager signs your app with the release keystore. To create a release keystore, read about signing your app in Android Studio.
  4. Before generating your final APK, the packager uses the zipalign tool to optimize your app to use less memory when running on a device.

At the end of the build process, you have either a debug APK or release APK of your app that you can use to deploy, test, or release to external users.

Custom Build Configurations

Gradle and the Android plugin help you configure the following aspects of your build:

Build Types
Build types define certain properties that Gradle uses when building and packaging your app, and are typically configured for different stages of your development lifecycle. For example, the debug build type enables debug options and signs the APK with the debug key, while the release build type may shrink, obfuscate, and sign your APK with a release key for distribution. You must define at least one build type in order to build your app—Android Studio creates the debug and release build types by default. To start customizing packaging settings for your app, learn how toConfigure Build Types.
Product Flavors
Product flavors represent different versions of your app that you may release to users, such as free and paid versions of your app. You can customize product flavors to use different code and resources, while sharing and reusing the parts that are common to all versions of your app. Product flavors are optional and you must create them manually. To start creating different versions of your app, learn how to Configure Product Flavors.
Build Variants
A build variant is a cross product of a build type and product flavor, and is the configuration Gradle uses to build your app. Using build variants, you can build the debug version of your product flavors during development, or signed release versions of your product flavors for distribution. Although you do not configure build variants directly, you do configure the build types and product flavors that form them. Creating additional build types or product flavors also creates additional build variants. To learn how to create and manage build variants, read the Configure Build Variants overview.
Manifest Entries
You can specify values for some properties of the manifest file in the build variant configuration. These build values override the existing values in the manifest file. This is useful if you want to generate multiple APKs for your modules where each of the apk files has a different application name, minimum SDK version, or target SDK version. When multiple manifests are present, Gradle merges manifest settings.
Dependencies
The build system manages project dependencies from your local filesystem and from remote repositories. This prevents you from having to manually search, download, and copy binary packages of your dependencies into your project directory. To find out more, learn how to Declare Dependencies.
Signing
The build system enables you to specify signing settings in the build configuration, and it can automatically sign your APKs during the build process. The build system signs the debug version with a default key and certificate using known credentials to avoid a password prompt at build time. The build system does not sign the release version unless you explicitly define a signing configuration for this build. If you do not have a release key, you can generate one as described in Sign Your App.
ProGuard
The build system enables you to specify a different ProGuard rules file for each build variant. The build system can run ProGuard to shrink and obfuscate your classes during the build process.
APK Splits
The build system enables you to automatically build different APKs that each contain only the code and resources needed for a specific screen density or Application Binary Interface (ABI). For more information see Configure APK Splits.

Build Configuration Files

Creating custom build configurations requires you to make changes to one or more build configuration files, or build.gradle files. These plain text files use Domain Specific Language (DSL) to describe and manipulate the build logic using Groovy, which is a dynamic language for the Java Virtual Machine (JVM). You don’t need to know Groovy to start configuring your build because the Android Plugin for Gradle introduces most of the DSL elements you need. To learn more about the Android plugin DSL, read the DSL reference documentation.

When starting a new project, Android Studio automatically creates some of these files for you, as shown in figure 2, and populates them based onsensible defaults.

Figure 2. The default project structure for an Android app module.

There are a few Gradle build configuration files that are a part of the standard project structure for an Android app. Before you can start configuring your build, it is important to understand the scope and purpose of each of these files, and the basic DSL elements they should define.

The Gradle Settings File

The settings.gradle file, located in the root project directory, tells Gradle which modules it should include when building your app. For most projects, the file is simple and only includes the following:

include ‘:app’

However, multi-module projects need to specify each module that should go into the final build.

The Top-level Build File

The top-level build.gradle file, located in the root project directory, defines build configurations that apply to all modules in your project. By default, the top-level build file uses the buildscript {} block to define the Gradle repositories and dependencies that are common to all modules in the project. The following code sample describes the default settings and DSL elements you can find in the top-level build.gradle after creating a new project.

/**
 * The buildscript {} block is where you configure the repositories and
 * dependencies for Gradle itself--meaning, you should not include dependencies
 * for your modules here. For example, this block includes the Android plugin for
 * Gradle as a dependency because it provides the additional instructions Gradle
 * needs to build Android app modules.
 */

buildscript {

    /**
     * The repositories {} block configures the repositories Gradle uses to
     * search or download the dependencies. Gradle pre-configures support for remote
     * repositories such as JCenter, Maven Central, and Ivy. You can also use local
     * repositories or define your own remote repositories. The code below defines
     * JCenter as the repository Gradle should use to look for its dependencies.
     */

    repositories {
        jcenter()
    }

    /**
     * The dependencies {} block configures the dependencies Gradle needs to use
     * to build your project. The following line adds Android Plugin for Gradle
     * version 2.0.0 as a classpath dependency.
     */

    dependencies {
        classpath 'com.android.tools.build:gradle:2.0.0'
    }
}

/**
 * The allprojects {} block is where you configure the repositories and
 * dependencies used by all modules in your project, such as third-party plugins
 * or libraries. Dependencies that are not required by all the modules in the
 * project should be configured in module-level build.gradle files. For new
 * projects, Android Studio configures JCenter as the default repository, but it
 * does not configure any dependencies.
 */

allprojects {
   repositories {
       jcenter()
   }
}

The Module-level Build File

The module-level build.gradle file, located in each <project>/<module>/ directory, allows you to configure build settings for the specific module it is located in. Configuring these build settings allows you to provide custom packaging options, such as additional build types and product flavors, and override settings in the main/ app manifest or top-level build.gradle file.

This sample Android app module build.gradle file outlines some of the basic DSL elements and settings that you should know.

/**
 * The first line in the build configuration applies the Android plugin for
 * Gradle to this build and makes the android {} block available to specify
 * Android-specific build options.
 */

apply plugin: 'com.android.application'

/**
 * The android {} block is where you configure all your Android-specific
 * build options.
 */

android {

  /**
   * compileSdkVersion specifies the Android API level Gradle should use to
   * compile your app. This means your app can use the API features included in
   * this API level and lower.
   *
   * buildToolsVersion specifies the version of the SDK build tools, command-line
   * utilities, and compiler that Gradle should use to build your app. You need to
   * download the build tools using the SDK Manager.
   */

  compileSdkVersion 23
  buildToolsVersion "23.0.3"

  /**
   * The defaultConfig {} block encapsulates default settings and entries for all
   * build variants, and can override some attributes in main/AndroidManifest.xml
   * dynamically from the build system. You can configure product flavors to override
   * these values for different versions of your app.
   */

  defaultConfig {

    /**
     * applicationId uniquely identifies the package for publishing.
     * However, your source code should still reference the package name
     * defined by the package attribute in the main/AndroidManifest.xml file.
     */

    applicationId 'com.example.myapp'

    // Defines the minimum API level required to run the app.
    minSdkVersion 14

    // Specifies the API level used to test the app.
    targetSdkVersion 23

    // Defines the version number of your app.
    versionCode 1

    // Defines a user-friendly version name for your app.
    versionName "1.0"
  }

  /**
   * The buildTypes {} block is where you can configure multiple build types.
   * By default, the build system defines two build types: debug and release. The
   * debug build type is not explicitly shown in the default build configuration,
   * but it includes debugging tools and is signed with the debug key. The release
   * build type applies Proguard settings and is not signed by default.
   */

  buildTypes {

    /**
     * By default, Android Studio configures the release build type to enable code
     * shrinking, using minifyEnabled, and specifies the Proguard settings file.
     */

    release {
        minifyEnabled true // Enables code shrinking for the release build type.
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
  }

  /**
   * The productFlavors {} block is where you can configure multiple product
   * flavors. This allows you to create different versions of your app that can
   * override defaultConfig {} with their own settings. Product flavors are
   * optional, and the build system does not create them by default. This example
   * creates a free and paid product flavor. Each product flavor then specifies
   * its own application ID, so that they can exist on the Google Play Store, or
   * an Android device, simultaneously.
   */

  productFlavors {
    free {
      applicationId 'com.example.myapp.free'
    }

    paid {
      applicationId 'com.example.myapp.paid'
    }
  }

  /**
   * The splits {} block is where you can configure different APK builds that
   * each contain only code and resources for a supported screen density or
   * ABI. You'll also need to configure your build so that each APK has a
   * different versionCode.
   */

  splits {
    // Screen density split settings
    density {

      // Enable or disable the density split mechanism
      enable false

      // Exclude these densities from splits
      exclude "ldpi", "tvdpi", "xxxhdpi", "400dpi", "560dpi"
    }
  }
}

/**
 * The dependencies {} block in the module-level build configuration file
 * only specifies dependencies required to build the module itself.
 */

dependencies {
    compile project(":lib")
    compile 'com.android.support:appcompat-v7:22.0.1'
    compile fileTree(dir: 'libs', include: ['*.jar'])
}

Gradle Properties Files

Gradle also includes two properties files, located in your root project directory, that you can use to specify settings for the Gradle build toolkit itself:

gradle.properties
This is where you can configure project-wide Gradle settings, such as the Gradle daemon's maximum heap size. For more information, see The Build Environment.
local.properties
Configures local environment properties for the build system, such as the path to the SDK installation. Because the content of this file is automatically generated by Android Studio and is specific to the local developer environment, you should not modify this file manually or check it into your version control system.

Syncing Project with Gradle Files

When you make changes to the build configuration files in your project, Android Studio requires that you sync your project files so that it can import your build configuration changes and run some checks to make sure your configuration won't create build errors.

To sync your project files, click Sync Now in the notification bar that appears when you make a change, as shown in figure 3, or click Sync Project [image] from the menu bar. If Android Studio notices any errors with your configuration, for example, your source code uses API features that are only available in an API level higher than your compileSdkVersion, the Messages window appears to describe the issue.

Figure 3. Syncing the project with build configuration files in Android Studio.

Source Sets

Android Studio logically groups source code and resources for each module into source sets. A module’s main/ source set includes the code and resources used by all its build variants. Additional source set directories are optional, and Android Studio does not automatically create them for you when you configure new build variants. However, creating source sets, similar to main/, helps organize files and resources that Gradle should only use when building certain versions of your app:

src/main/
This source set includes code and resources common to all build variants.
src/<buildType>/
Create this source set to include code and resources only for a specific build type.
src/<productFlavor>/
Create this source set to include code and resources only for a specific product flavor.
src/<productFlavorBuildType>/
Create this source set to include code and resources only for a specific build variant.

For example, to generate the "fullDebug" version of your app, the build system merges code, settings, and resources from following source sets:

  • src/fullDebug/ (the build variant source set)
  • src/debug/ (the build type source set)
  • src/full/ (the product flavor source set)
  • src/main/ (the main source set)

Note: When you create a new file or directory in Android Studio, using the File > New menu options, you can create it for a specific source set. The source sets you can choose from are based on your build configurations, and Android Studio automatically creates the required directories if they don't already exist.

If different source sets contain different versions of the same file, Gradle uses the following priority order when deciding which file to use (source sets on the left override the files and settings of source sets to the right):

build variant > build type > product flavor > main source set > library dependencies

This allows Gradle to use files that are specific to the build variant you are trying to build while reusing activities, application logic, and resources that are common to other versions of your app. When merging multiple manifests, Gradle uses the same priority order, so each build variant can define different components or permissions in the final manifest. To learn more about creating custom source sets, go to Create Source Sets for Build Variants.

来源： https://developer.android.com/studio/build/index.html


Configure Build Variants

  1. Configure Build Types
  2. Configure Product Flavors
  3. Create Source Sets for Build Variants
  4. Declare Dependencies
  5. Configure Signing Settings

See also

  • Configure Your Build Overview
  • Manifest Merger

This page builds on the Configure Your Build Overview to show you how you can configure build variants to create different versions of your app from a single project, and how to properly manage your dependencies and signing configurations.

Each build variant represents a different version of your app that you can build. For example, you might want to build one version of your app that's free, with a limited set of content, and another paid version that includes more. You can also build different versions of your app that target different devices, based on API level or other device variations. However, if you want to build different versions based on the device ABI or screen density, instead use APK splits.

Build variants are the result of Gradle using a specific set of rules to combine settings, code, and resources configured in your build types and product flavors. Although you do not configure build variants directly, you do configure the build types and product flavors that form them.

For example, a "demo" product flavor can specify different features and device requirements, such as custom source code, resources, and minimum API levels, while the "debug" build type applies different build and packaging settings, such as debug options and signing keys. The resulting build variant is the "demoDebug" version of your app, and it includes a combination of the configurations and resources included in the "demo" product flavor, "debug" build type, and main/ source set.

Configure Build Types

You can create and configure build types in the module-level build.gradle file inside the android {} block. When you create a new module, Android Studio automatically creates the debug and release build types for you. Although the debug build type doesn't appear in the build configuration file, Android Studio configures it with debuggable true. This allows you to debug the app on secure Android devices and configures APK signing with a generic debug keystore.

You can add the the debug build type to your configuration if you want to add or change certain settings. The following sample specifies anapplicationIdSuffix for the debug build type, and configures a "jnidebug" build type that is initialized using settings from the debug build type.

android {
    ...
    defaultConfig {...}
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

        debug {
            applicationIdSuffix ".debug"
        }

        /**
         * The 'initWith' property allows you to copy configurations from other build types,
         * so you don't have to configure one from the beginning. You can then configure
         * just the settings you want to change. The following line initializes
         * 'jnidebug' using the debug build type, and changes only the
         * applicationIdSuffix and versionNameSuffix settings.
         */

        jnidebug {

            // This copies the debuggable attribute and debug signing configurations.
            initWith debug

            applicationIdSuffix ".jnidebug"
            jniDebuggable true
        }
    }
}

Note: When you make changes to a build configuration file, Android Studio requires that you sync your project with the new configuration. To sync your project, you can click Sync Now in the notification bar that appears as soon as you make a change or Sync Project [image] from the toolbar. If Android Studio notices any errors with your configuration, the Messages window appears to describe the issue.

To learn more about all the properties you can configure with build types, read the build type DSL reference.

Configure Product Flavors

Creating product flavors is similar to creating build types: add them to the productFlavors {} block and configure the settings you want. The product flavors support the same properties as defaultConfig—this is because defaultConfig actually belongs to the ProductFlavor class. This means you can provide the base configuration for all flavors in the defaultConfig {} block, and each flavor can override any of these default values, such as theapplicationId.

Note: You still need to specify a package name using the package attribute in the main/ manifest file. You must also use that package name in your source code to refer to the R class, or resolve any relative activity or service registration. This allows you to use applicationId to give each product flavor a unique ID for packaging and distribution, without having to change your source code.

The following code sample creates a "demo" and "full" product flavor with their own applicationId and versionName

android {
    ...
    defaultConfig {...}
    buildTypes {...}
    productFlavors {
        demo {
            applicationId "com.example.myapp.demo"
            versionName "1.0-demo"
        }
        full {
            applicationId "com.example.myapp.full"
            versionName "1.0-full"
        }
    }
}

Note: To distribute your app using Multiple APK Support in Google Play, assign the same applicationId value to all variants and give each variant a different versionCode. To distribute different variants of your app as separate apps in Google Play, you need to assign a different applicationId to each variant.

After you create and configure your product flavors, click Sync Now in the notification bar. After the sync completes, Gradle automatically creates build variants based on your build types and product flavors, and names them according to <product-flavor><Build-Type>. For example, if you created 'demo' and 'full' product flavors, and kept the default 'debug' and 'release' build types, Gradle creates the following build variants:

  • demoDebug
  • demoRelease
  • fullDebug
  • fullRelease

You can change the build variant to whichever one you want to build and run—just go to Build > Select Build Variant and select a one from the drop-down menu. To start customizing each build variant with its own features and resources, however, you'll need to know how to create and manage source sets.

Create Source Sets for Build Variants

By default, Android Studio creates the main/ source set and directories for everything you want to share between all your build variants. However, you can create new source sets to control exactly what files Gradle compiles and packages for specific build types, product flavors, and build variants. For example, you can define basic functionality in the main/ source set and use product flavor source sets to change the branding of your app for different clients, or include special permissions and logging functionality only for build variants that use the debug build type.

Gradle expects you to organize source set files and directories a certain way, similar to the main/ source set. For example, Gradle expects Java class files that are specific to your "debug" build type to be located in the src/debug/java/ directory.

The Android Plugin for Gradle provides a useful Gradle task that shows you how to organize your files for each of your build types, product flavors, and build variants. For example, the following section of the report describes where Gradle expects to find certain files for the "debug" build type:

------------------------------------------------------------
Project :app
------------------------------------------------------------

...

debug
----
Compile configuration: compile
build.gradle name: android.sourceSets.debug
Java sources: [app/src/debug/java]
Manifest file: app/src/debug/AndroidManifest.xml
Android resources: [app/src/debug/res]
Assets: [app/src/debug/assets]
AIDL sources: [app/src/debug/aidl]
RenderScript sources: [app/src/debug/rs]
JNI sources: [app/src/debug/jni]
JNI libraries: [app/src/debug/jniLibs]
Java-style resources: [app/src/debug/resources]

To generate and view this report for your build configuration, proceed as follows:

  1. Click Gradle [image] on the right side of the IDE window.
  2. Navigate to MyApplication > Tasks > android and double-click sourceSets.
  3. To view the report, click Gradle Console [image] at the bottom of the IDE window.

Note: The report also shows you how to organize source sets for files you want to use to run tests for your app, such as the test/ and androidTest/ testing source sets.

When you create a new build variant, Android Studio doesn't create the source set directories for you, but it does give you a few options to help you. For example, to create just the java/ directory for your "debug" build type:

  1. Open the Project pane and select the Project view from the drop-down menu at the top of the pane.
  2. Navigate to MyProject/app/src/.
  3. Right-click the src directory and select New > Folder > Java Folder.
  4. From the drop-down menu next to Target Source Set, select debug.
  5. Click Finish.

Android Studio creates a source set directory for your debug build type, and then creates the java/ directory inside it. Alternatively, you can also make Android Studio create the directories for you when create a new file for a specific build variant. For example, to create a values XML file for your "debug" build type:

  1. In the same Project pane, right-click the src directory and select New > XML > Values XML File.
  2. Enter the name for the XML file or keep the default name.
  3. From the drop-down menu next to Target Source Set, select debug.
  4. Click Finish.

Because the "debug" build type was specified as the target source set, Android Studio automatically creates the necessary directories when it creates the XML file. The resulting directory structure should look like figure 2.

Figure 2. New source set directories for the debug build type.

Using the same procedure, you can also create source set directories for product flavors, such as src/demo/, and build variants, such as src/demoDebug/. Additionally, you can create testing source sets that target specific build variants, such as src/androidTestDemoDebug/. To learn more, go to Testing source sets.

Build with source sets

You can use source set directories to contain the the code and resources you want packaged only with certain configurations. For example, if you are building the "demoDebug" build variant, which is the crossproduct of a "demo" product flavor and "debug" build type, Gradle looks at these directories, and gives them the following priority:

  1. src/demoDebug/ (build variant source set)
  2. src/debug/ (build type source set)
  3. src/demo/ (product flavor source set)
  4. src/main/ (main source set)

The order listed above determines which source set has a higher priority when Gradle combines code and resources. Because the demoDebug/ source set directory likely contains files that are specific to that build variant, if demoDebug/ includes a file that is also defined in debug/, Gradle uses the file in thedemoDebug/ source set. Similarly, Gradle gives files in the build type and product flavor source sets a higher priority over the same files in main/. Gradle considers this priority order when applying the following build rules:

  • All source code in the java/ directories are compiled together to generate a single output.

    Note: For a given build variant, Gradle throws a build error if it encounters two or more source set directories that have defined the same Java class. For example, when building a debug APK, you cannot define both src/debug/Utility.java and src/main/Utility.java. This is because Gradle looks at both these directories during the build process and throws a 'duplicate class' error. If you want different versions of Utility.javafor different build types, you can have each build type define its own version of the file and not include it in the main/ source set.

  • Manifests are merged together into a single manifest. Priority is given in the same order as the list above. That is, manifest settings for a build type override the manifest settings for a product flavor, and so on. To learn more, read about manifest merging.
  • Similarly, files in the values/ directories are merged together. If two files share the same name, such as two strings.xml files, priority is given in the same order as the list above. That is, values defined in a file in the build type source set override the values defined in the same file in a product flavor, and so on.
  • Resources in the res/ and asset/ directories are packaged together. If there are resources with the same name defined in two or more source sets, priority is given in the same order as the list above.
  • Finally, Gradle gives resources and manifests included with library module dependencies the lowest priority when building the APK.

Declare Dependencies

The following example declares three different types of direct dependencies in the app/ module's build.gradle file:

android {...}
...
dependencies {
    // The 'compile' configuration tells Gradle to add the dependency to the
    // compilation classpath and include it in the final package.

    // Dependency on the "mylibrary" module from this project
    compile project(":mylibrary")

    // Remote binary dependency
    compile 'com.android.support:appcompat-v7:23.4.0'

    // Local binary dependency
    compile fileTree(dir: 'libs', include: ['*.jar'])
}

Each of these direct dependencies is described below.

Module dependencies
The compile project(':mylibrary') line declares a local Android library module named "mylibrary" as a dependency, and requires the build system to compile and include the local module when building your app.
Remote binary dependencies
The compile 'com.android.support:appcompat-v7:23.4.0' line declares a dependency on version 23.4.0 of the Android Support Library by specifying its JCenter coordinates. By default, Android Studio configures projects to use the JCenter Repository in the top-level build file. Gradle automatically pulls the dependency from JCenter when you sync your project with the build configuration files. Alternatively, you can download and install certain dependencies by using the SDK Manager.
Local binary dependencies
The compile fileTree(dir: 'libs', include: ['*.jar']) line tells the build system to include any JAR files inside the app/libs/ directory in the compilation classpath and in the final package of your app. If you have modules that require local binary dependencies, copy the JAR files for these dependencies into <moduleName>/libs inside your project.

Some direct dependencies of the module may have dependencies of their own, called transitive dependencies of the module. Rather than having to manually declare each transitive dependency, Gradle automatically gathers and adds them for you. The Android Plugin for Gradle provides a useful Gradle task that can generate a dependency tree for each build variant and testing source set, so you can easily visualize both the direct and transitive dependencies of your module. To generate this report, proceed as follows:

  1. Click Gradle [image] on the right side of the IDE window.
  2. Navigate to MyApplication > Tasks > android and double-click androidDependencies.
  3. To view the report, click Gradle Console [image] at the bottom of the IDE window.

The following sample report shows the dependency tree for the debug build variant, and includes the local module dependency and remote dependency from the previous example.

Executing tasks: [androidDependencies]
:app:androidDependencies
debug
/**
 * Both the library module dependency and remote binary dependency are listed
 * with their transitive dependencies.
 */
+--- MyApp:mylibrary:unspecified
|    \--- com.android.support:appcompat-v7:23.4.0
|         +--- com.android.support:animated-vector-drawable:23.4.0
|         |    \--- com.android.support:support-vector-drawable:23.4.0
|         |         \--- com.android.support:support-v4:23.4.0
|         |              \--- LOCAL: internal_impl-23.4.0.jar
|         +--- com.android.support:support-v4:23.4.0
|         |    \--- LOCAL: internal_impl-23.4.0.jar
|         \--- com.android.support:support-vector-drawable:23.4.0
|              \--- com.android.support:support-v4:23.4.0
|                   \--- LOCAL: internal_impl-23.4.0.jar
\--- com.android.support:appcompat-v7:23.4.0
     +--- com.android.support:animated-vector-drawable:23.4.0
     |    \--- com.android.support:support-vector-drawable:23.4.0
     |         \--- com.android.support:support-v4:23.4.0
     |              \--- LOCAL: internal_impl-23.4.0.jar
     +--- com.android.support:support-v4:23.4.0
     |    \--- LOCAL: internal_impl-23.4.0.jar
     \--- com.android.support:support-vector-drawable:23.4.0
          \--- com.android.support:support-v4:23.4.0
               \--- LOCAL: internal_impl-23.4.0.jar
...

For more information about managing dependencies in Gradle, see Dependency Management Basics in the Gradle User Guide.

Configure dependencies

You can use certain configuration keywords to tell Gradle how and when to use a dependency, such as the compile keyword from previous examples. The following describes some of the keywords you can use to configure your dependencies:

compile
Specifies a compile time dependency. Gradle adds dependencies with this configuration to both the classpath and your app’s APK. This is the default configuration.
apk
Specifies a runtime-only dependency that Gradle needs to package with your app’s APK. You can use this configuration with JAR binary dependencies, but not with other library module dependencies or AAR binary dependencies.
provided
Specifies a compile time dependency that Gradle does not package with your app’s APK. This helps reduce the size of your APK if the dependency is not required during runtime. You can use this configuration with JAR binary dependencies, but not with other library module dependencies or AAR binary dependencies.

Additionally, you can configure a dependency for a specific build variant or testing source set by applying the name of the build variant or testing source set to the configuration keyword, as shown in the following sample.

dependencies {
    ...
    // Adds specific library module dependencies as compile time dependencies
    // to the fullRelease and fullDebug build variants.
    fullReleaseCompile project(path: ':library', configuration: 'release')
    fullDebugCompile project(path: ':library', configuration: 'debug')

    // Adds a compile time dependency for local tests.
    testCompile 'junit:junit:4.12'

    // Adds a compile time dependency for the test APK.
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'
}

Configure Signing Settings

Gradle does not sign your release build's APK unless you explicitly define a signing configuration for this build. You can easily create a release key andsign your release build type using Android Studio.

To manually configure the signing configurations for your release build type using Gradle build configurations:

  1. Create a keystore. A keystore is a binary file that contains a set of private keys. You must keep your keystore in a safe and secure place.
  2. Create a private key. A private key represents the entity to be identified with the app, such as a person or a company.

  3. Add the signing configuration to the module-level build.gradle file:

    ...
    android     {
            ...
        defaultConfig     {...}
        signingConfigs     {
            release     {
                storeFile file    ("myreleasekey.keystore")
                storePassword     "password"
                keyAlias     "MyReleaseKey"
                keyPassword     "password"
                }
            }
        buildTypes     {
            release     {
                    ...
                signingConfig signingConfigs    .release
                }
            }
    }

To generate a signed APK, select Build > Generate Signed APK from the main menu. The package in app/build/apk/app-release.apk is now signed with your release key.

Note: Including the passwords for your release key and keystore inside the build file is not a good security practice. Alternatively, you can configure the build file to obtain these passwords from environment variables or have the build process prompt you for these passwords.

To obtain these passwords from environment variables:

storePassword System.getenv("KSTOREPWD")
keyPassword System.getenv("KEYPWD")

To have the build process prompt you for these passwords if you are invoking the build from the command line:

storePassword System.console().readLine("\nKeystore password: ")
keyPassword System.console().readLine("\nKey password: ")

After you complete this process, you can distribute your app and publish it on Google Play.

Warning: Keep your keystore and private key in a safe and secure place, and ensure that you have secure backups of them. If you publish an app to Google Play and then lose the key with which you signed your app, you will not be able to publish any updates to your app, since you must always sign all versions of your app with the same key.

Signing Android Wear Apps

When publishing Android Wear apps, you package the wearable app inside of a handheld app, because users cannot browse and install apps directly on the wearable. Both apps must be signed. For more information on packaging and signing Android Wear apps, see Packaging Wearable Apps.

来源： https://developer.android.com/studio/build/build-variants.html


Configure APK Splits

Although you should build a single APK to support all your target devices whenever possible, that might result in a very large APK due to files needed to support multiple screen densities or Application Binary Interfaces (ABIs). One way to reduce the size of your APK is to create multiple APKs that contain files for specific screen densities or ABIs.

Gradle uses APK splits to create separate APKs that contain only code and resources specific to each density or ABI. This page describes how to configure your build to generate APK splits. If you need to create different versions of your app that are not based on screen density or ABI, you can instead use build variants.

Configure Your Build for APK Splits

To enable APK splits, add a splits {} block to your module-level build.gradle file. Within the splits {}block, provide a density {} block that specifies how Gradle should generate per-density APKs, or an abi {}block that specifies how Gradle should generate per-ABI APKs. You can provide both density and ABI blocks, and the build system will create a split APK for each density and ABI combination.

Configure density APK splits

To create separate APKs for different screen densities, add a density {} block inside your splits {} block. In your density {} block, provide a list of desired screen densities and compatible screen sizes. The list of compatible screen sizes should only be used if you need specific <compatible-screens>elements in each APK's manifest.

The following Gradle DSL options are used to configure per-density APK splits:

enable
If you set this element to true, Gradle generates APK splits based on the screen densities you define. The default value is false.
exclude
Specifies a comma-separated list of densities that Gradle should not generate separate APKs for. Use exclude if you want to generate APKs for most densities, but need to exclude a few densities that your app doesn't support.
reset()
Clears the default list of screen densities. Only use when combined with the include element to specify the densities you would like to add. The following snippet sets the list of densities to just ldpi and xxhdpi by calling reset() to clear the list, and then using include:
reset()  // clear the default list from all densities to no densities
include "ldpi", "xxhdpi" // specify the two densities we want to generate APKs for
include
Specifies a comma-separated list of densities that Gradle should generate APKs for. Only use in combination with reset() to specify an exact list of densities.
compatibleScreens
Specifies a comma-separated list of compatible screen sizes. This will inject a matching <compatible-screens> node in the manifest for each split APK. This optional setting provides a convenient way to manage both screen densities and screen sizes in the same build.gradle section, however using <compatible-screens> can limit the types of devices your app will work with. For alternative ways to support different screen sizes, see Support Multiple Screens.

Because each split APK that's based on screen density includes a <compatible-screens> tag with specific restrictions about which screen types the APK supports, even if you publish several APKs, some new devices will not match your multiple APK filters. As such, Gradle always generates an additional universal APK that contains assets for all screen densities and does not include a <compatible-screens> tag. You should publish this universal APK along with your split APKs to provide a fallback for devices that do not match the APKs with a <compatible-screens> tag.

The following example generates a separate APK for each screen density listed in Range of screens supported, except ldpi, xxhdpi, and xxxhdpi. This is done by using exclude to remove three densities from the default list of all densities:

android {
  ...
  splits {

    // Configures screen density split settings
    density {

      // Enables density APK splits
      enable true

      // Specifies a list of screen densities Gradle should not create APK splits for
      exclude "ldpi", "xxhdpi", "xxxhdpi"

      // Specifies a list of compatible screen size settings for the manifest
      compatibleScreens 'small', 'normal', 'large', 'xlarge'
    }
  }
}

For a list of density names and screen size names, see How to Support Multiple Screens. For more details on distributing your app to specific screen types and devices, see Distributing to Specific Screens.

Configure ABI APK splits

To create separate APKs for different ABIs, add an abi {} block inside your splits {} block. In your abi {} block, provide a list of desired ABIs.

The following Gradle DSL options are used to configure per-ABI APK splits:

enable
If you set this element to true, Gradle generates APK splits based on the ABIs you define. The default value is false
exclude
Specifies a comma-separated list of ABIs that Gradle should not generate separate APKs for. Use exclude if you want to generate APKs for most ABIs, but need to exclude a few ABIs that your app doesn't support.
reset()
Clears the default list of ABIs. Only use when combined with the include element to specify the ABIs you would like to add. The following snippet sets the list of ABIs to just x86 and mips by calling reset() to clear the list, and then using include:
reset()  // clear the default list from all ABIs to no ABIs
include "x86", "mips" // specify the two ABIs we want to generate APKs for
include
Specifies a comma-separated list of ABIs that Gradle should generate APKs for. Only use in combination with reset() to specify an exact list of ABIs.
universalApk
If true, Gradle generates a universal APK in addition to split APKs. A universal APK contains code and resources for all ABIs in a single APK. The default value is false. Note that this option is only available for per-ABI APK splits. Density APK splits always generate a universal APK that contains code and resources for all screen densities.

The following example generates a separate APK for each ABI: x86, armeabi-v7a, and mips. This is done by using reset() to start with an empty list of ABIs, followed by include with a list of three ABIs that will each get an APK:

android {
  ...
  splits {

    // Configures screen ABI split settings
    abi {

      // Enable ABI APK splits
      enable true

      // By default all ABIs are included, so use reset() and include to specify that we only
      // want APKs for x86, armeabi-v7a, and mips

      // Resets the list of ABIs that Gradle should create APKs for to none
      reset()

      // Specifies a list of ABIs that Gradle should create APKs for
      include "x86", "armeabi-v7a", "mips"

      // Specify that we do not want to also generate a universal APK that includes all ABIs
      universalApk false
    }
  }
}

For a list of supported ABIs, see Supported ABIs.

Configure versioning of APK splits

By default, when Gradle generates APK splits, each APK will have the same version information, as specified in the module-level build.gradle file. Because the Google Play Store does not allow multiple APKs for the same app that all have the same version information, you need to ensure each split APK has its own unique versionCode before you upload to the Play Store.

You can configure your module-level build.gradle file to override the versionCode for every split APK. Assign a unique numeric value for each ABI and density used in APK splits, and then override the output version code with a value that combines defaultConfig.versionCode with the numeric value assigned to the density or ABI.

The following example creates a mapping that assigns a unique numeric value to each ABI being used for APK splits. Using this mapping, a per-split APK version code is created that combines the mapped ABI value with defaultConfig.versionCode. In this example, the split APK for the x86 ABI would get aversionCode of 304. If defaultConfig.versionCode iterates to 5, Gradle would assign a versionCode of 305 to the x86 split APK.

android {
  ...
  defaultConfig {
    ...
    versionCode 4
  }
  splits {
    ...
  }
}

// map for the version code that gives each ABI a value
ext.versionCodes = ['armeabi-v7a':1, mips:2, x86:3]

// For each APK output variant, override versionCode with a combination of
// ABI APK value * 100 + defaultConfig.versionCode
android.applicationVariants.all { variant ->
    // assign different version code for each output
    variant.outputs.each { output ->
        output.versionCodeOverride =
                project.versionCodes.get(output.getFilter(OutputFile.ABI)) * 100
                + android.defaultConfig.versionCode
    }
}

For more examples of alternate version code schemes, see Assigning version codes.

Build APK Splits

Once you configure your module-level build.gradle file to build APK splits, click Build > Build APK to build all APKs for the currently selected module in the Project pane. Gradle creates the APKs for each density or ABI into the project's build/outputs/apk/ directory.

Gradle builds an APK for each configured density or ABI split. If you've enabled splits for both densities and ABIs, Gradle will create an APK for each density and ABI combination. For example, the following build.gradle snippet enables building APK splits for mdpi and hdpi densities, and also x86 and mips ABIs:

...
  splits {
    density {
      enable true
      reset()
      include "mdpi", "hdpi"
    }
    abi {
      enable true
      reset()
      include "x86", "mips"
    }
  }

The output from the example configuration would include the following 4 split APKs:

  • app-hdpiX86-release.apk: Contains code and resources for hdpi density and x86 ABI only.
  • app-hdpiMips-release.apk: Contains code and resources for hdpi density and mips ABI only.
  • app-mdpiX86-release.apk: Contains code and resources for mdpi density and x86 ABI only.
  • app-mdpiMips-release.apk: Contains code and resources for mdpi density and mips ABI only.

Depending on how you've configured APK splits, Gradle will also generate a universal APK that contains code and resources for all densities or ABIs. For density APK splits, Gradle will always generate a universal APK that includes code and resources for all densities, in addition to the per-density APKs. For ABI splits, Gradle only generates an APK that includes code and resources for all ABIs if you specify universalApk true in the abi section of the splits {} block in your build.gradle file.

APK file name format

For APK splits, Gradle uses APK filenames using the following scheme:

modulename-screendensityABI-buildvariant.apk

The scheme components are:

modulename
Specifies the module name being built.
screendensity
If screen density APK splits are enabled, specifies the screen density for the APK, such as "mdpi".
ABI
If ABI APK splits are enabled, specifies the ABI for the APK, such as "x86". If both screen density and ABI APK splits are enabled, Gradle concatenates the density name with the ABI name, for example "mdpiX86". If universalApk is enabled for ABI APK splits, Gradle uses "universal" as the ABI portion of the universal APK filename.
buildvariant
Specifies the build variant being built, such as "debug".

For example, a debug build of "myApp" that has APK splits enabled for the mdpi screen density would use an APK filename of myApp-mdpi-debug.apk. A release build of "myApp" that has APK splits enabled for both the mdpi screen density and the x86 ABI would use an APK filename of myApp-mdpiX86-release.apk.

来源： https://developer.android.com/studio/build/configure-apk-splits.html


Merge Multiple Manifest Files

  1. Merge Conflict Rules
  2. Merge Conflict Markers and Selectors
  3. Injecting Build Values into a Manifest
  4. Manifest Merging Across Product Flavor Groups
  5. Implicit Permissions
  6. Handling Manifest Merge Build Errors

See also

  1. Build System Overview
  2. Configuring Gradle Builds

With Android Studio and Gradle-based builds, each app can contain manifest files in multiple locations, such as the src/main/ folder for the productFlavor, libraries, Android ARchive (AAR) bundles of Android Library projects, and dependencies. During the build process, manifest merging combines the settings from the various AndroidManifest.xml files included in your app into a single, generated APK manifest file for app packaging and distribution. Manifest settings are merged based on the manifest priority, determined by the manifest's file location. Building your app merges the manifest elements, attributes, and sub-elements from these manifests for the specified build variant.

Merge Conflict Rules

Merge conflicts occur when merged manifests contain the same manifest element but with a different attribute value that does not resolve based on the default merge conflict rules. Conflict markers and selectors can also define custom merge rules, such as allowing an imported library to have a minSdkVersionhigher than the version defined in the other higher priority manifests.

The manifest merge priority determines which manifest settings are retained in merge conflicts, with the settings in higher priority manifest overwriting those in lower priority manifests. The following list details which manifest settings are are the highest priority during the merge process:

  • Highest priority: buildType manifest settings
  • Higher priority: productFlavor manifest settings
  • Medium priority: Manifests in the src/main/ directory of an app project
  • Low priority: Dependency and library manifest settings

Manifest merge conflicts are resolved at the XML node and attribute levels based on the following merge rules.

High Priority Element | Low Priority Element | Manifest Merge Result
no attribute | no attribute | no attribute
 | attribute set to default | default attribute
 | attribute set to non-default | low priority attribute
attribute set to default | no attribute | default attribute
attribute set to non-default |  | high priority attribute
attribute set to default | attribute set to default | default attribute
attribute set to default | attribute set to non-default | low priority attribute
attribute set to non-default | attribute set to default | high priority attribute
attribute set to non-default | attribute set to non-default | Merge if settings match, otherwise causes conflict error.

Exceptions to the manifest merge rules:

  • The uses-feature android:required; and uses-library android:required elements default to true and use an OR merge so that any required feature or library is included in the generated APK.
  • If not declared, the <uses-sdk> elements, minSdkVersion and targetSdkVersion, default to a value of 1. When merge conflicts occur, the value in the higher priority manifest version is used.
  • Importing a library with a minSdkVersion value higher than the app's src/main/ manifest manifest generates an error unless the overrideLibraryconflict marker is used.

    Note: If not explicitly declared, the targetSdkVersion defaults to the minSdkVersion value. When no element is present in any manifest or thebuild.gradle file, the minSdkVersion defaults to 1.

  • When importing a library with a targetSdkVersion value lower than the app's src/main/ manifest, the manifest merge process explicitly grants permissions and ensures that the imported library functions properly.
  • The manifest element only merges with child manifest elements.
  • The intent-filter element is never changed and is always added to the common parent node in the merged manifest.

Important: After the manifests are merged, the build process overrides the final manifest settings with any settings that are also in the build.gradlefile. For more details, see Configuring Gradle Builds.

Merge Conflict Markers and Selectors

Manifest markers and selectors override the default merge rules through specific conflict resolutions. For example, use a conflict marker to merge a library manifest with a higher minSdkVersion value than the higher priority manifest, or to merge manifests with the same activity but differentandroid:theme values.

Merge Conflict Markers

A merge conflict marker is a special attribute in the Android tools namespace that defines a specific merge conflict resolution. Create a conflict marker to avoid a merge conflict error for conflicts not resolved by the default merge rules. Supported merge conflict markers include:

merge
Merges attributes when there are no conflicts with the merge rules. The default merge action.
replace
Replaces attributes in the lower priority manifest with those from the higher priority manifest.
strict
Sets the merge policy level so that merged elements with same attributes, but different values generate a build failure, unless resolved through the conflict rules.
merge-only
Allows merge actions for only lower priority attributes.
remove
Removes the specified lower priority element from the merged manifest.
remove-All
Removes all lower priority elements of the same node type from the merged manifest.

By default, the manifest merge process applies the merge conflict marker to the node level. All declared manifest attributes default to a strict merging policy.

To set a merge conflict marker, first declare the namespace in the AndroidManifest.xml file. Then, enter the merge conflict marker in the manifest to specify a custom merge conflict action. This example inserts the replace marker to set a replace action to resolve conflicts between the android:iconand android:label manifest elements.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.android.tests.flavorlib.app"
   xmlns:tools="http://schemas.android.com/tools">

   <application
       android:icon="@drawable/icon"
       android:label="@string/app_name"
       tools:replace="icon, label">
       ...

Marker attributes

Conflict markers use tools:node and tools:attr attributes to restrict merge actions at the XML node or attribute level.

The tools:attr markers use only the restrict, remove, and replace merge actions. Multiple tools:attr marker values can be applied to a specific element. For example, use tools:replace="icon, label, theme" to replace lower priority icon, label, and theme attributes.

Merge conflict marker for imported libraries

The overrideLibrary conflict marker applies to the <uses-sdk> manifest declaration and is used to import a library even though the library's <uses-sdk>values, such as minSdkVersion are set to different values than those in the other higher priority manifests.

Without this marker, library manifest merge conflicts from the <uses-sdk> values cause the merge process to fail.

This example applies the overrideLibrary conflict marker to resolve the merge conflict between minSdkVersion values in the src/main/ manifest and an imported library manifest.

src/main/ manifest:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.android.example.app"
   xmlns:tools="http://schemas.android.com/tools">
   ...
   <uses-sdk android:targetSdkVersion="22" android:minSdkVersion="2"
             tools:overrideLibrary="com.example.lib1, com.example.lib2"/>
   ...

Library manifest:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
         package="com.example.lib1">
     ...
         <uses-sdk android:minSdkVersion="4" />
     ...
    </manifest>

Note: The default merge process does not allow importing a library with a higher minSdkVersion than the app's src/main/ manifest unless theoverrideLibrary conflict marker is used.

Marker Selectors

Marker selectors limit a merge action to a specific lower priority manifest. For example, a marker selector can be used to remove a permission from only one library, while allowing the same permission from other libraries.

This example uses the tools:node marker to remove the permisionOne attribute, while the tools:selector selector specifies the specific library ascom.example.lib1. The permisionOne permission is filtered from only the lib1 library manifests.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.android.example.app"
   xmlns:tools="http://schemas.android.com/tools">
   ...
   <permission
         android:name="permissionOne"
         tools:node="remove"
         tools:selector="com.example.lib1">
   ...

Injecting Build Values into a Manifest

Manifest merging can also be configured to use manifest placeholders to inject property values from the build.gradle file into the manifest attributes.

Manifest placeholders use the syntax ${name} for attribute values, where name is the injected build.gradle property. The build.gradle file uses themanifestPlaceholders property to define the placeholder values.

Note: Unresolved placeholder names in apps cause build failures. Unresolved placeholder names in libraries generate warnings and need to be resolved when importing the library into an app.

This example shows the manifest placeholder ${applicationId} used to inject the build.gradle applicationId property value in to android:nameattribute value.

Note: Android Studio provides a default ${applicationId} placeholder for the build.gradle applicationId value that is not shown in the build file. When building an AAR (Android ARchive) package for library modules, do not provide an automatic @{applicationId} placeholder in the manifest merge settings. Instead, use a different placeholder, such as @{libApplicationId} and provide a value for it if you want to include application Ids in the archive library.

Manifest entry:

<activity
android:name=".Main">
     <intent-filter>
     <action android:name="${applicationId}.foo">
         </action>
</intent-filter>
</activity>

Gradle build file:

android {
   compileSdkVersion 22
   buildToolsVersion "22.0.1"

   productFlavors {
       flavor1 {
           applicationId = "com.mycompany.myapplication.productFlavor1"
       }
}

Merged manifest value:

<action android:name="com.mycompany.myapplication.productFlavor1.foo">

The manifest placeholder syntax and build file manifestPlaceholders property can be used to inject other manifest values. For properties other than theapplicationId, the manifestPlaceholders property is explicitly declared in the build.gradle file. This example shows the manifest placeholder for injecting activityLabel values.

Gradle build file:

android {
    defaultConfig {
        manifestPlaceholders = [ activityLabel:"defaultName"]
    }
    productFlavors {
        free {
        }
        pro {
            manifestPlaceholders = [ activityLabel:"proName" ]
        }
    }

Placeholder in the manifest file:

<activity android:name=".MainActivity" android:label="${activityLabel}" >

Note: The placeholder value supports partial value injection, for example android:authority="com.acme.${localApplicationId}.foo".

Manifest Merging Across Product Flavor Groups

When using the GroupableProductFlavor property, the manifest merge priority of any manifests in the product flavor groups follows the order in which the product flavor groups are listed in the build file. The manifest merge process creates a single merged manifest for the product flavor groups based on the configured build variant.

For example, if a build variant references the product flavors x86, mdpi, 21, and paid from the respective product flavor groups ABI, Density, API, and Prod, listed in this order in the build.gradle file, then the manifest merge process merges the manifests in this priority order, which follows how the product flavors are listed in the build file.

To illustrate this example, the following table shows how the product flavors are listed for each product flavor group. This combination of product flavors and groups defines the build variant.

Product Flavor Group | Product Flavor
ABI | x86
density | mdpi
API | 22
prod | paid

Manifest merge order:

  • prod-paid AndroidManifest.xml (lowest priority) merges into API-22 AndroidManifest.xml
  • API-22 AndroidManifest.xml merges into density-mpi AndroidManifest.xml
  • density-mpi AndroidManifest.xml merges into ABI-x86 AndroidManifest.xml (highest priority)

Implicit Permissions

Importing a library that targets an Android runtime with implicitly granted permissions may automatically add the permissions to the resulting merged manifest. For example, if an application with a targetSdkVersion of 16 imports a library with a targetSdkVersion of 2, Android Studio adds theWRITE_EXTERNAL_STORAGE permission to ensure permission compatibility across the SDK versions.

Note: More recent Android releases replace implicit permissions with permission declarations.

This table lists the importing library versions and the declared permissions.

Importing this library version | Declares this permission in the manifest
targetSdkVersion < 2 | WRITE_EXTERNAL_STORAGE
targetSdkVersion < 4 | WRITE_EXTERNAL_STORAGE, READ_PHONE_STATE
Declared WRITE_EXTERNAL_STORAGE | READ_EXTERNAL_STORAGE
targetSdkVersion < 16 and using the READ_CONTACTS permission | READ_CALL_LOG
targetSdkVersion < 16 and using the WRITE_CONTACTS permission | WRITE_CALL_LOG

Handling Manifest Merge Build Errors

During the build process, the manifest merge process stores a record of each merge transaction in the manifest-merger-<productFlavor>-report.txtfile in the module build/outputs/logs folder. A different log file is generated for each of the module's build variants.

When a manifest merge build error occurs, the merge process records the error message describing the merge conflict in the log file. For example, theandroid:screenOrientation merge conflict between the following manifests causes a build error.

Higher priority manifest declaration:

<activity
   android:name="com.foo.bar.ActivityOne"
   android:screenOrientation="portrait"
   android:theme="@theme1"/>

Lower priority manifest declaration:

<activity
   android:name="com.foo.bar.ActivityOne"
   android:screenOrientation="landscape"/>

Error log:

/project/app/src/main/AndroidManifest.xml:3:9 Error:
 Attribute activity@screenOrientation value=(portrait) from AndroidManifest.xml:3:9
 is also present at flavorlib:lib1:unspecified:3:18 value=(landscape)
 Suggestion: add 'tools:replace="icon"' to  element at AndroidManifest.xml:1:5 to override

来源： https://developer.android.com/studio/build/manifest-merge.html


Shrink Your Code and Resources

  1. Shrink Your Code
    1. Customize which code to keep
    2. Decode an obfuscated stack trace
  2. Shrink Your Resources
    1. Customize which resources to keep
    2. Enable strict reference checks
    3. Remove unused alternative resources
    4. Merge duplicate resources
    5. Troubleshoot resource shrinking

See also

  • ProGuard Manual

To make your APK file as small as possible, you should enable shrinking to remove unused code and resources in your release build. This page describes how to do that and how to specify what code and resources to keep or discard during the build.

Code shrinking is available with ProGuard, which detects and removes unused classes, fields, methods, and attributes from your packaged app, including those from included code libraries (making it a valuable tool for working around the 64k reference limit). ProGuard also optimizes the bytecode, removes unused code instructions, and obfuscates the remaining classes, fields, and methods with short names. The obfuscated code makes your APK difficult to reverse engineer, which is especially valuable when your app uses security-sensitive features, such as licensing verification.

Resource shrinking is available with the Android Plugin for Gradle, which removes unused resources from your packaged app, including unused resources in code libraries. It works in conjunction with code shrinking such that once unused code has been removed, any resources no longer referenced can be safely removed as well.

Features in this document depend on:

  • SDK Tools 25.0.10 or higher
  • Android Plugin for Gradle 2.0.0 or higher

Shrink Your Code

To enable code shrinking with ProGuard, add minifyEnabled true to the appropriate build type in your build.gradle file.

Be aware that code shrinking slows down the build time, so you should avoid using it on your debug build if possible. However, it's important that you do enable code shrinking on your final APK used for testing, because it might introduce bugs if you do not sufficiently customize which code to keep.

For example, the following snippet from a build.gradle file enables code shrinking for the release build:

android {
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile(‘proguard-android.txt'),
                    'proguard-rules.pro'
        }
    }
    ...
}

Note: Android Studio disables ProGuard when using Instant Run.

In addition to the minifyEnabled property, the proguardFiles property defines the ProGuard rules:

  • The getDefaultProguardFile(‘proguard-android.txt') method gets the default ProGuard settings from the Android SDK tools/proguard/ folder.

    Tip: For even more code shrinking, try the proguard-android-optimize.txt file that's in the same location. It includes the same ProGuard rules, but with other optimizations that perform analysis at the bytecode level—inside and across methods—to reduce your APK size further and help it run faster.

  • The proguard-rules.pro file is where you can add custom ProGuard rules. By default, this file is located at the root of the module (next to thebuild.gradle file).

To add more ProGuard rules that are specific to each build variant, add another proguardFiles property in the corresponding productFlavor block. For example, the following Gradle file adds flavor2-rules.pro to the flavor2 product flavor. Now flavor2 uses all three ProGuard rules because those from the release block are also applied.

android {
    ...
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'),
                   'proguard-rules.pro'
        }
    }
    productFlavors {
        flavor1 {
        }
        flavor2 {
            proguardFile 'flavor2-rules.pro'
        }
    }
}

With each build, ProGuard outputs the following files:

dump.txt
Describes the internal structure of all the class files in the APK.
mapping.txt
Provides a translation between the original and obfuscated class, method, and field names.
seeds.txt
Lists the classes and members that were not obfuscated.
usage.txt
Lists the code that was removed from the APK.

These files are saved at <module-name>/build/outputs/mapping/release/.

Customize which code to keep

For some situations, the default ProGuard configuration file (proguard-android.txt) is sufficient and ProGuard removes all—and only—the unused code. However, many situations are difficult for ProGuard to analyze correctly and it might remove code your app actually needs. Some examples of when it might incorrectly remove code include:

  • When your app references a class only from the AndroidManifest.xml file
  • When your app calls a method from the Java Native Interface (JNI)
  • When your app manipulates code at runtime (such as with reflection or introspection)

Testing your app should reveal any errors caused by inappropriately removed code, but you can also inspect what code was removed by reviewing theusage.txt output file saved in <module-name>/build/outputs/mapping/release/.

To fix errors and force ProGuard to keep certain code, add a -keep line in the ProGuard configuration file. For example:

-keep public class MyClass

Alternatively, you can add the @Keep annotation to the code you want to keep. Adding @Keep on a class keeps the entire class as-is. Adding it on a method or field will keep the method/field (and it's name) as well as the class name intact. Note that this annotation is available only when using the Annotations Support Library.

There are many considerations you should make when using the -keep option; for more information about customizing your configuration file, read theProGuard Manual. The Troubleshooting section outlines other common problems you might encounter when your code gets stripped away.

Decode an obfuscated stack trace

After ProGuard shrinks your code, reading a stack trace is difficult (if not impossible) because the method names are obfuscated. Fortunately, ProGuard creates a mapping.txt file each time it runs, which shows the original class, method, and field names mapped to the obfuscated names. ProGuard saves the file in the app <module-name>/build/outputs/mapping/release/ directory.

Be aware that the mapping.txt file is overwritten every time you create a release build with ProGuard, so you must carefully save a copy each time you publish a new release. By retaining a copy of the mapping.txt file for each release build, you'll be able to debug a problem if a user submits an obfuscated stack trace from an older version of your app.

When publishing your app on Google Play, you can upload the mapping.txt file for each version of your APK. Then Google Play will deobfuscate incoming stack traces from user-reported issues so you can review them in the Google Play Developer Console. For more information, see the Help Center article about how to deobfuscate crash stack traces.

To convert an obfuscated stack trace to a readable one yourself, use the retrace script (retrace.bat on Windows; retrace.sh on Mac/Linux). It is located in the <sdk-root>/tools/proguard/ directory. The script takes the mapping.txt file and your stack trace, producing a new, readable stack trace. The syntax for using the retrace tool is:

retrace.bat|retrace.sh [-verbose] mapping.txt [<stacktrace_file>]

For example:

retrace.bat -verbose mapping.txt obfuscated_trace.txt

If you do not specify the stack trace file, the retrace tool reads from standard input.

Shrink Your Resources

Resource shrinking works only in conjunction with code shrinking. After the code shrinker removes all unused code, the resource shrinker can identify which resources the app still uses. This is especially true when you add code libraries that include resources—you must remove unused library code so the library resources become unreferenced and, thus, removable by the resource shrinker.

To enable resource shrinking, set the shrinkResources property to true in your build.gradle file (alongside minifyEnabled for code shrinking). For example:

android {
    ...
    buildTypes {
        release {
            shrinkResources true
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'),
                    'proguard-rules.pro'
        }
    }
}

If you haven't already built your app using minifyEnabled for code shrinking, then try that before enabling shrinkResources, because you might need to edit your proguard-rules.pro file to keep classes or methods that are created or invoked dynamically before you start removing resources.

Note: The resource shrinker currently does not remove resources defined in a values/ folder (such as strings, dimensions, styles, and colors). This is because the Android Asset Packaging Tool (AAPT) does not allow the Gradle Plugin to specify predefined versions for resources. For details, seeissue 70869.

Customize which resources to keep

If there are specific resources you wish to keep or discard, create an XML file in your project with a <resources> tag and specify each resource to keep in the tools:keep attribute and each resource to discard in the tools:discard attribute. Both attributes accept a comma-separated list of resource names. You can use the asterisk character as a wild card.

For example:

<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools"
    tools:keep="@layout/l_used*_c,@layout/l_used_a,@layout/l_used_b*"
    tools:discard="@layout/unused2" />

Save this file in your project resources, for example, at res/raw/keep.xml. The build does not package this file into your APK.

Specifying which resources to discard might seem silly when you could instead delete them, but this can be useful when using build variants. For example, you might put all your resources into the common project directory, then create a different keep.xml file for each build variant when you know that a given resource appears to be used in code (and therefore not removed by the shrinker) but you know it actually won't be used for the given build variant.

Enable strict reference checks

Normally, the resource shrinker can accurately determine whether a resource is used. However, if your code makes a call to Resources.getIdentifier()(or if any of your libraries do that—the AppCompat library does), that means your code is looking up resource names based on dynamically-generated strings. When you do this, the resource shrinker behaves defensively by default and marks all resources with a matching name format as potentially used and unavailable for removal.

For example, the following code causes all resources with the img_ prefix to be marked as used.

String name = String.format("img_%1d", angle + 1);
res = getResources().getIdentifier(name, "drawable", getPackageName());

The resource shrinker also looks through all the string constants in your code, as well as various res/raw/ resources, looking for resource URLs in a format similar to file:///android_res/drawable//ic_plus_anim_016.png. If it finds strings like this or others that look like they could be used to construct URLs like this, it doesn't remove them.

These are examples of the safe shrinking mode that is enabled by default. You can, however, turn off this "better safe than sorry" handling, and specify that the resource shrinker keep only resources that it's certain are used. To do this, set shrinkMode to strict in the keep.xml file, as follows:

<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools"
    tools:shrinkMode="strict" />

If you do enable strict shrinking mode and your code also references resources with dynamically-generated strings, as shown above, then you must manually keep those resources using the tools:keep attribute.

Remove unused alternative resources

The Gradle resource shrinker removes only resources that are not referenced by your app code, which means it will not remove alternative resources for different device configurations. If necessary, you can use the Android Gradle plugin's resConfigs property to remove alternative resource files that your app does not need.

For example, if you are using a library that includes language resources (such as AppCompat or Google Play Services), then your APK includes all translated language strings for the messages in those libraries whether the rest of your app is translated to the same languages or not. If you'd like to keep only the languages that your app officially supports, you can specify those languages using the resConfig property. Any resources for languages not specified are removed.

The following snippet shows how to limit your language resources to just English and French:

android {
    defaultConfig {
        ...
        resConfigs "en", "fr"
    }
}

Similarly, you can customize which screen density or ABI resources to include in your APK using APK splits to build different APKs for different devices.

Merge duplicate resources

By default, Gradle also merges identically named resources, such as drawables with the same name that might be in different resource folders. This behavior is not controlled by the shrinkResources property and cannot be disabled, because it is necessary to avoid errors when multiple resources match the name your code is looking up.

Resource merging occurs only when two or more files share an identical resource name, type, and qualifier. Gradle selects which file it considers to be the best choice among the duplicates (based on a priority order described below) and passes only that one resource to the AAPT for distribution in the APK file.

Gradle looks for duplicate resources in the following locations:

  • The main resources, associated with the main source set, generally located in src/main/res/.
  • The variant overlays, from the build type and build flavors.
  • The library project dependencies.

Gradle merges duplicate resources in the following cascading priority order:

Dependencies → Main → Build flavor → Build type

For example, if a duplicate resource appears in both your main resources and a build flavor, Gradle selects the one in the build flavor.

If identical resources appear in the same source set, Gradle cannot merge them and emits a resource merge error. This can happen if you define multiple source sets in the sourceSet property of your build.gradle file—for example if both src/main/res/ and src/main/res2/ contain identical resources.

Troubleshoot resource shrinking

When you shrink resources, the Gradle Console shows a summary of the resources that it removed from the app package. For example:

:android:shrinkDebugResources
Removed unused resources: Binary resource data reduced from 2570KB to 1711KB: Removed 33%
:android:validateDebugSigning

Gradle also creates a diagnostic file named resources.txt in <module-name>/build/outputs/mapping/release/ (the same folder as ProGuard's output files). This file includes details such as which resources reference other resources and which resources are used or removed.

For example, to find out why @drawable/ic_plus_anim_016 is still in your APK, open the resources.txt file and search for that file name. You might find that it's referenced from another resource, as follows:

16:25:48.005 [QUIET] [system.out] @drawable/add_schedule_fab_icon_anim : reachable=true
16:25:48.009 [QUIET] [system.out]     @drawable/ic_plus_anim_016

You now need to know why @drawable/add_schedule_fab_icon_anim is reachable—and if you search upwards you'll find that resource is listed under "The root reachable resources are:". This means there is a code reference to add_schedule_fab_icon_anim (that is, its R.drawable ID was found in the reachable code).

If you are not using strict checking, resource IDs can be marked as reachable if there are string constants that look like they might be used to construct resource names for dynamically loaded resources. In that case, if you search the build output for the resource name, you might find a message like this:

10:32:50.590 [QUIET] [system.out] Marking drawable:ic_plus_anim_016:2130837506
    used because it format-string matches string pool constant ic_plus_anim_%1$d.

If you see one of these strings and you are certain that the string is not being used to load the given resource dynamically, you can use the tools:discardattribute to inform the build system to remove it, as described in the section about how to customize which resources to keep.

来源： https://developer.android.com/studio/build/shrink-code.html


Configure Apps with Over 64K Methods

  1. About the 64K Reference Limit
    1. Multidex support prior to Android 5.0
    2. Multidex support for Android 5.0 and higher
  2. Avoiding the 64K Limit
  3. Configuring Your App for Multidex with Gradle
    1. Limitations of the multidex support library
  4. Optimizing Multidex Development Builds
    1. Using Build Variants in Android Studio
  5. Testing Multidex Apps

See Also

  1. ProGuard

As the Android platform has continued to grow, so has the size of Android apps. When your application and the libraries it references reach a certain size, you encounter build errors that indicate your app has reached a limit of the Android app build architecture. Earlier versions of the build system report this error as follows:

Conversion to Dalvik format failed:
Unable to execute dex: method ID not in [0, 0xffff]: 65536

More recent versions of the Android build system display a different error, which is an indication of the same problem:

trouble writing output:
Too many field references: 131000; max is 65536.
You may try using --multi-dex option.

Both these error conditions display a common number: 65,536. This number is significant in that it represents the total number of references that can be invoked by the code within a single Dalvik Executable (dex) bytecode file. If you have built an Android app and received this error, then congratulations, you have a lot of code! This document explains how to move past this limitation and continue building your app.

Note: The guidance provided in this document supersedes the guidance given in the Android Developers blog post Custom Class Loading in Dalvik.

About the 64K Reference Limit

Android application (APK) files contain executable bytecode files in the form of Dalvik Executable (DEX) files, which contain the compiled code used to run your app. The Dalvik Executable specification limits the total number of methods that can be referenced within a single DEX file to 65,536—including Android framework methods, library methods, and methods in your own code. In the context of computer science, the term Kilo, K, denotes 1024 (or 2^10). Because 65,536 is equal to 64 X 1024, this limit is referred to as the '64K reference limit'.

Getting past this limit requires that you configure your app build process to generate more than one DEX file, known as a multidex configuration.

Multidex support prior to Android 5.0

Versions of the platform prior to Android 5.0 (API level 21) use the Dalvik runtime for executing app code. By default, Dalvik limits apps to a single classes.dex bytecode file per APK. In order to get around this limitation, you can use the multidex support library, which becomes part of the primary DEX file of your app and then manages access to the additional DEX files and the code they contain.

Note: If your project is configured for multidex with minSdkVersion 20 or lower, and you deploy to target devices running Android 4.4 (API level 20) or lower, Android Studio disables Instant Run.

Multidex support for Android 5.0 and higher

Android 5.0 (API level 21) and higher uses a runtime called ART which natively supports loading multiple dex files from application APK files. ART performs pre-compilation at application install time which scans for classes(..N).dex files and compiles them into a single .oat file for execution by the Android device. For more information on the Android 5.0 runtime, see Introducing ART.

Note: While using Instant Run, Android Studio automatically configures your app for multidex when your app's minSdkVersion is set to 21 or higher. Because Instant Run only works with the debug version of your app, you still need to configure your release build for multidex to avoid the 64K limit.

Avoiding the 64K Limit

Before configuring your app to enable use of 64K or more method references, you should take steps to reduce the total number of references called by your app code, including methods defined by your app code or included libraries. The following strategies can help you avoid hitting the dex reference limit:

  • Review your app's direct and transitive dependencies - Ensure any large library dependency you include in your app is used in a manner that outweighs the amount of code being added to the application. A common anti-pattern is to include a very large library because a few utility methods were useful. Reducing your app code dependencies can often help you avoid the dex reference limit.
  • Remove unused code with ProGuard - Configure the ProGuard settings for your app to run ProGuard and ensure you have shrinking enabled for release builds. Enabling shrinking ensures you are not shipping unused code with your APKs.

Using these techniques can help you avoid the build configuration changes required to enable more method references in your app. These steps can also decrease the size of your APKs, which is particularly important for markets where bandwidth costs are high.

Configuring Your App for Multidex with Gradle

The Android plugin for Gradle available in Android SDK Build Tools 21.1 and higher supports multidex as part of your build configuration. Make sure you update the Android SDK Build Tools tools and the Android Support Repository to the latest version using the SDK Manager before attempting to configure your app for multidex.

Setting up your app development project to use a multidex configuration requires that you make a few modifications to your app development project. In particular you need to perform the following steps:

  • Change your Gradle build configuration to enable multidex
  • Modify your manifest to reference the MultiDexApplication class

Modify the module-level build.gradle file configuration to include the support library and enable multidex output, as shown in the following code snippet:

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.0"

    defaultConfig {
        ...
        minSdkVersion 14
        targetSdkVersion 21
        ...

        // Enabling multidex support.
        multiDexEnabled true
    }
    ...
}

dependencies {
  compile 'com.android.support:multidex:1.0.0'
}

In your manifest add the MultiDexApplication class from the multidex support library to the application element.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.multidex.myapplication">
    <application
        ...
        android:name="android.support.multidex.MultiDexApplication">
        ...
    </application>
</manifest>

When these configuration settings are added to an app, the Android build tools construct a primary dex (classes.dex) and supporting (classes2.dex, classes3.dex) as needed. The build system will then package them into an APK file for distribution.

Note: If your app uses extends the Application class, you can override the attachBaseContext() method and call MultiDex.install(this) to enable multidex. For more information, see the MultiDexApplication reference documentation.

Limitations of the multidex support library

The multidex support library has some known limitations that you should be aware of and test for when you incorporate it into your app build configuration:

  • The installation of .dex files during startup onto a device's data partition is complex and can result in Application Not Responding (ANR) errors if the secondary dex files are large. In this case, you should apply code shrinking techniques with ProGuard to minimize the size of dex files and remove unused portions of code.
  • Applications that use multidex may not start on devices that run versions of the platform earlier than Android 4.0 (API level 14) due to a Dalvik linearAlloc bug (Issue 22586). If you are targeting API levels earlier than 14, make sure to perform testing with these versions of the platform as your application can have issues at startup or when particular groups of classes are loaded. Code shrinking can reduce or possibly eliminate these potential issues.
  • Applications using a multidex configuration that make very large memory allocation requests may crash during run time due to a Dalvik linearAlloc limit (Issue 78035). The allocation limit was increased in Android 4.0 (API level 14), but apps may still run into this limit on Android versions prior to Android 5.0 (API level 21).
  • There are complex requirements regarding what classes are needed in the primary dex file when executing in the Dalvik runtime. The Android build tooling updates handle the Android requirements, but it is possible that other included libraries have additional dependency requirements including the use of introspection or invocation of Java methods from native code. Some libraries may not be able to be used until the multidex build tools are updated to allow you to specify classes that must be included in the primary dex file.

Optimizing Multidex Development Builds

A multidex configuration requires significantly increased build processing time because the build system must make complex decisions about what classes must be included in the primary DEX file and what classes can be included in secondary DEX files. This means that routine builds performed as part of the development process with multidex typically take longer and can potentially slow your development process.

In order to mitigate the typically longer build times for multidex output, you should create two variations on your build output using the Android plugin for Gradle productFlavors: a development flavor and a production flavor.

For the development flavor, set a minimum SDK version of 21. This setting generates multidex output much faster using the ART-supported format. For the release flavor, set a minimum SDK version which matches your actual minimum support level. This setting generates a multidex APK that is compatible with more devices, but takes longer to build.

The following build configuration sample demonstrates the how to set up these flavors in a Gradle build file:

android {
    productFlavors {
        // Define separate dev and prod product flavors.
        dev {
            // dev utilizes minSDKVersion = 21 to allow the Android gradle plugin
            // to pre-dex each module and produce an APK that can be tested on
            // Android Lollipop without time consuming dex merging processes.
            minSdkVersion 21
        }
        prod {
            // The actual minSdkVersion for the application.
            minSdkVersion 14
        }
    }
          ...
    buildTypes {
        release {
            runProguard true
            proguardFiles getDefaultProguardFile('proguard-android.txt'),
                                                 'proguard-rules.pro'
        }
    }
}
dependencies {
  compile 'com.android.support:multidex:1.0.0'
}

After you have completed this configuration change, you can use the devDebug variant of your app, which combines the attributes of the devproductFlavor and the debug buildType. Using this target creates a debug app with proguard disabled, multidex enabled, and minSdkVersion set to Android API level 21. These settings cause the Android gradle plugin to do the following:

  1. Build each module of the application (including dependencies) as separate dex files. This is commonly referred to as pre-dexing.
  2. Include each dex file in the APK without modification.
  3. Most importantly, the module dex files will not be combined, and so the long-running calculation to determine the contents of the primary dex file is avoided.

These settings result in fast, incremental builds, because only the dex files of modified modules are recomputed and repackaged into the APK file. The APK that results from these builds can be used to test on Android 5.0 devices only. However, by implementing the configuration as a flavor, you preserve the ability to perform normal builds with the release-appropriate minimum SDK level and proguard settings.

You can also build the other variants, including a prodDebug variant build, which takes longer to build, but can be used for testing outside of development. Within the configuration shown, the prodRelease variant would be the final testing and release version. If you are executing gradle tasks from the command line, you can use standard commands with DevDebug appended to the end (such as ./gradlew installDevDebug). For more information about using flavors with Gradle tasks, see the Gradle Plugin User Guide.

Tip: You can also provide a custom manifest, or a custom application class for each flavor, allowing you to use the support library MultiDexApplication class, or calling MultiDex.install() only for the variants that need it.

Using Build Variants in Android Studio

Build variants can be very useful for managing the build process when using multidex. Android Studio allows you to select these build variants in the user interface.

To have Android Studio build the "devDebug" variant of your app:

  1. Open the Build Variants window from the left-sidebar. The option is located next to Favorites.
  2. Click the name of the build variant to select a different variant, as shown in Figure 1.

Figure 1. Screen shot of the Android Studio left panel showing a build variant.

Note: The option to open this window is only available after you have successfully synchronized Android Studio with your Gradle build file using theTools > Android > Sync Project with Gradle Files command.

Testing Multidex Apps

When writing instrumentation tests for multidex apps, no additional configuration is required. AndroidJUnitRunner supports multidex out of the box, as long as you use MultiDexApplication or override the attachBaseContext() method in your custom Application object and call MultiDex.install(this)to enable multidex.

Alternatively, you can override the onCreate() method in AndroidJUnitRunner:

public void onCreate(Bundle arguments) {
    MultiDex.install(getTargetContext());
    super.onCreate(arguments);
    ...
}

Note: Use of multidex for creating a test APK is not currently supported.

来源： https://developer.android.com/studio/build/multidex.html


Run Gradle from the Command Line

  1. Building in Debug Mode
  2. Building in Release Mode
    1. Build unsigned
    2. Build signed and aligned
    3. Once built and signed in release mode
  3. Running on the Emulator
  4. Running on a Device
  5. Application Signing
  6. Plugin Language Reference

See also

  1. Build System
  2. Using the Android Emulator
  3. Signing Your Applications

By default, there are two build types to build your application using the Gradle build settings: one for debugging your application — debug — and one for building your final package for release — release mode. Regardless of which build type your modules use, the app must be signed before it can install on an emulator or device—with a debug key when building in debug mode and with your own private key when building in release mode.

Whether you're building with the debug or release build type, you need to run and build your module. This will create the .apk file that you can install on an emulator or device. When you build using the debug build type, the .apk file is automatically signed by the SDK tools with a debug key based on the debuggable true setting in the module's build.gradle file, so it's instantly ready for installation onto an emulator or attached development device. You cannot distribute an application that is signed with a debug key. When you build using the release build type, the .apk file is unsigned, so you must manually sign it with your own private key, using Keytool and Jarsigner settings in the module's build.gradle file.

It's important that you read and understand Signing Your Applications, particularly once you're ready to release your application and share it with end-users. That document describes the procedure for generating a private key and then using it to sign your APK file. If you're just getting started, however, you can quickly run your applications on an emulator or your own development device by building in debug mode.

If you don't have Gradle, you can obtain it from the Gradle home page. Install it and make sure it is in your executable PATH. Before calling Gradle, you need to declare the JAVA_HOME environment variable to specify the path to where the JDK is installed.

Note: When using ant and installing JDK on Windows, the default is to install in the "Program Files" directory. This location will cause ant to fail, because of the space. To fix the problem, you can specify the JAVA_HOME variable like this:

set JAVA_HOME=c:\Progra~1\Java\<jdkdir>

The easiest solution, however, is to install JDK in a non-space directory, for example:

c:\java\jdk1.7

You should also set up your project to use the Gradle wrapper, which is a tool that allows others to build your project in a consistent environment. The Gradle wrapper provides a batch file for Windows, and a shell script for Linux and Mac OSX, that automatically downloads and uses the version of Gradle that you specify for your project. This way, you can run gradle tasks on your project through the wrapper without having to consider compatibility issues with other versions of the build system.

Note: If you create a new project using Android Studio, the IDE automatically sets up the Gradle wrapper for you, so you do not need to follow these setup instructions.

To specify a version of Gradle for your project and initialize the gradle wrapper, run the following command from your project's root directory:

gradle wrapper --gradle-version version-number

Gradle executes the wrapper task and generates the following files:

  • ./gradlew.bat and ./gradlew: the wrapper's batch file and shell script file, respectively.
  • ./gradle/wrapper/gradle-wrapper.jar: a JAR file that the batch file and shell script file use.
  • ./gradle/wrapper/gradle-wrapper.properties: a properties file that includes configurations for the wrapper, such as the distribution URL and the version of Gradle you specify for your project.

Note: You should include the files listed above in your version control system. That way, anyone using your project will also have the wrapper files and configurations they need to reproduce your build.

You can now use the Gradle wrapper to run gradle tasks on your project—the wrapper automatically delegates the task to the correct version of Gradle. To run a task with the wrapper, use one of the following commands:

  • On Windows: gradlew.bat task-name
  • On Mac OSX or Linux: ./gradlew task-name

Building in Debug Mode

For immediate application testing and debugging, you can build your application in debug mode and immediately install it on an emulator. In debug mode, the build tools automatically sign your application with a debug key and optimize the package with zipalign.

To build in debug mode, open a command-line and navigate to the root of your project directory. Use Gradle to build your project in debug mode, invoke the assembleDebug build task using the Gradle wrapper script (gradlew assembleRelease).

This creates your debug .apk file inside the module build/ directory, named <your_module_name>-debug.apk. The file is already signed with the debug key and has been aligned with zipalign.

On Windows platforms, type this command:

> gradlew.bat assembleDebug

On Mac OS and Linux platforms, type these commands:

$ chmod +x gradlew
$ ./gradlew assembleDebug

The first command (chmod) adds the execution permission to the Gradle wrapper script and is only necessary the first time you build this project from the command line.

After you build the project, the output APK for the app module is located in app/build/outputs/apk/, and the output AAR for any lib modules is located inlib/build/outputs/libs/.

To see a list of all available build tasks for your project, type this command:

$ ./gradlew tasks

Each time you change a source file or resource, you must run Gradle again in order to package up the latest version of the application.

To install and run your application on an emulator, see the section about Running on the Emulator.

Building in Release Mode

When you're ready to release and distribute your application to end-users, you must build your application in release mode. Once you have built in release mode, it's a good idea to perform additional testing and debugging with the final .apk.

Before you start building your application in release mode, be aware that you must sign the resulting application package with your private key, and should then align it using the zipalign tool. There are two approaches to building in release mode: build an unsigned package in release mode and then manually sign and align the package, or allow the build script to sign and align the package for you.

Build unsigned

If you build your application unsigned, then you will need to manually sign and align the package.

To build an unsigned .apk in release mode, open a command-line and navigate to the root of your module directory. Invoke the assembleRelease build task.

On Windows platforms, type this command:

> gradlew.bat assembleRelease

On Mac OS and Linux platforms, type this command:

$ ./gradlew assembleRelease

This creates your Android application .apk file inside the project bin/ directory, named <your_module_name>-unsigned.apk.

Note: The .apk file is unsigned at this point and can't be installed until signed with your private key.

Once you have created the unsigned .apk, your next step is to sign the .apk with your private key and then align it with zipalign. To complete this procedure, read Signing Your Applications.

When your .apk has been signed and aligned, it's ready to be distributed to end-users. You should test the final build on different devices or AVDs to ensure that it runs properly on different platforms.

Build signed and aligned

If you would like, you can configure the Android build script to automatically sign and align your application package. To do so, you must provide the path to your keystore and the name of your key alias in your modules's build.gradle file. With this information provided, the build will prompt you for your keystore and alias password when you build using the release build type and produce your final application package, which will be ready for distribution.

To specify your keystore and alias, open the module build.gradle file (found in the root of the module directory) and add entries for storeFile,storePassword, keyAlias and keyPassword. For example:

storeFile file("myreleasekey.keystore")
keyAlias "MyReleaseKey"

Save your changes. Now you can build a signed .apk in release mode:

  1. Open a command-line and navigate to the root of your module directory.
  2. Edit the build.gradle file to build your project in release mode:

    ...
    android     {
            ...
        defaultConfig     { ... }
        signingConfigs     {
            release     {
                storeFile file    ("myreleasekey.keystore")
                storePassword     "password"
                keyAlias     "MyReleaseKey"
                keyPassword     "password"
                }
            }
        buildTypes     {
            release     {
                    ...
                signingConfig signingConfigs    .release
                }
            }
    }
    ...

  3. When prompted, enter you keystore and alias passwords.

    Caution: As described above, your password will be visible on the screen.

This creates your Android application .apk file inside the module build/ directory, named <your_module_name>-release.apk. This .apk file has been signed with the private key specified in build.gradle file and aligned with zipalign. It's ready for installation and distribution.

Once built and signed in release mode

Once you have signed your application with a private key, you can install and run it on an emulator or device. You can also try installing it onto a device from a web server. Simply upload the signed .apk to a web site, then load the .apk URL in your Android web browser to download the application and begin installation. (On your device, be sure you have enabled Settings > Applications > Unknown sources.)

Running on the Emulator

Before you can run your application on the Android Emulator, you must create an AVD.

To run your application:

  1. Open the AVD Manager and launch a virtual device

    In the Virtual Devices view, select an AVD and click Start.

  2. Install your application

    From your SDK's tools/ directory, install the .apk on the emulator:

    adb install <path_to_your_bin>.apk

    Your .apk file (signed with either a release or debug key) is in your module build/ directory after you build your application.

    If there is more than one emulator running, you must specify the emulator upon which to install the application, by its serial number, with the -soption. For example:

    adb -s emulator-5554 install path/to/your/app.apk

    To see a list of available device serial numbers, execute adb devices.

If you don't see your application on the emulator, try closing the emulator and launching the virtual device again from the AVD Manager. Sometimes when you install an application for the first time, it won't show up in the application launcher or be accessible by other applications. This is because the package manager usually examines manifests completely only on emulator startup.

Be certain to create multiple AVDs upon which to test your application. You should have one AVD for each platform and screen type with which your application is compatible. For instance, if your application compiles against the Android 4.0 (API Level 14) platform, you should create an AVD for each platform equal to and greater than 4.0 and an AVD for each screen type you support, then test your application on each one.

Tip: If you have only one emulator running, you can build your application and install it on the emulator in one simple step. Navigate to the root of your project directory and use Ant to compile the project with install mode: ant install. This will build your application, sign it with the debug key, and install it on the currently running emulator.

Running on a Device

Before you can run your application on a device, you must perform some basic setup for your device:

  • Enable USB debugging on your device. You can find the option under Settings > Developer options.

    Note: On Android 4.2 and newer, Developer options is hidden by default. To make it available, go to Settings > About phone and tap Build number seven times. Return to the previous screen to find Developer options.

  • Ensure that your development computer can detect your device when connected via USB

Read Setting up a Device for Development for more information.

Once your device is set up and connected via USB, navigate to your SDK's platform-tools/ directory and install the .apk on the device:

adb -d install path/to/your/app.apk

The -d flag specifies that you want to use the attached device (in case you also have an emulator running).

For more information on the tools used above, please see the following documents:

  • Android Emulator
  • Android Debug Bridge (ADB)

Application Signing

As you begin developing Android applications, understand that all Android applications must be digitally signed before the system will install them on an emulator or device. There are two ways to do this: with a debug key (for immediate testing on an emulator or development device) or with a private key(for application distribution).

The Android build tools help you get started by automatically signing your .apk files with a debug key at build time. This means that you can build your application and install it on the emulator without having to generate your own private key. However, please note that if you intend to publish your application, you must sign the application with your own private key, rather than the debug key generated by the SDK tools.

Please read Signing Your Applications, which provides a thorough guide to application signing on Android and what it means to you as an Android application developer. The document also includes a guide to publishing and signing your application.

Android Plugin for Gradle

The Android build system uses the Android plugin for Gradle to support the Gradle Domain Specific Language (DSL) and declarative language elements. See the Android Plug-in for Gradle section for a description of the plugin and a link to the complete list of the supported Gradle DSL elements.

来源： https://developer.android.com/studio/build/building-cmdline.html


Debug Your App

  1. Use the System Log
    1. Write log messages in your code
    2. View the system log
  2. Work with Breakpoints
    1. View and configure breakpoints
    2. Debug Window Frames
  3. View Variables and Evaluate Expressions
  4. Track Object Allocation
  5. Analyze Runtime Metrics to Optimize your App
  6. Capture Screenshots and Videos

See also

  • Android Monitor
  • Device Monitor
  • Using DDMS
  • Create and Edit Run/Debug Configurations

Android Studio includes a debugger that allows you to debug apps running on the Android Emulator or a connected Android device. With the Android Studio debugger, you can:

  • Select a device to debug your app on.
  • Set breakpoints in your code.
  • Examine variables and evaluate expressions at runtime.
  • Capture screenshots and videos of your app.

To start debugging, click Debug [image] in the toolbar. Android Studio builds an APK, signs it with a debug key, installs it on your selected device, then runs it and opens the Debug window.

If no devices appear in the Select Deployment Target window after you click Debug, then you need to eitherconnect a device or click Create New Emulator to setup the Android Emulator.

Figure 1. The Debugger window, showing the current thread and the object tree for a variable.

If your app is already running on a connected device or emulator, you can start debugging as follows:

  1. Click Attach debugger to Android process [image] .
  2. In the Choose Process dialog, select the process you want to attach the debugger to.

    3. By default, the debugger shows the device and app process for the current project, as well as any connected hardware devices or virtual devices on your computer. Select Show all processes to show all processes on all devices; the display includes any services that your app created as well as system processes, for example.

    From the Debugger menu, you can select Java, Native, or Hybrid. The latter two options are available only if your project contains some native C or C++ source code.

  3. Click OK.

    4. The Debug window appears. In this case, notice the two tabs to the right of the Debug window title: one tab is for debugging native code and the other for Java code, as indicated by -java.

    Separate debugging sessions have separate tabs and different port numbers, which are displayed in parentheses in the tab.

  4. To end a debugging session, click the tab for the session, and then click Terminate [image] .

Note: The Android Studio debugger and garbage collector are loosely integrated. The Andriod virtual machine guarantees that any object the debugger is aware of is not garbage collected until after the debugger disconnects. This can result in a buildup of objects over time while the debugger is connected. For example, if the debugger sees a running thread, the associated Thread object is not garbage collected even after the thread terminates.

Use the System Log

The system log shows system messages while you debug your app. These messages include information from apps running on the device. If you want to use the system log to debug your app, make sure your code writes log messages and prints the stack trace for exceptions while your app is in the development phase.

Write log messages in your code

To write log messages in your code, use the Log class. Log messages help you understand the execution flow by collecting the system debug output while you interact with your app. Log messages can tell you what part of your application failed. For more information about logging, see Reading and Writing Logs.

The following example shows how you might add log messages to determine if previous state information is available when your activity starts:

import android.util.Log;
...
public class MyActivity extends Activity {
    private static final String TAG = MyActivity.class.getSimpleName();
    ...
    @Override
    public void onCreate(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            Log.d(TAG, "onCreate() Restoring previous state");
            /* restore state */
        } else {
            Log.d(TAG, "onCreate() No saved state available");
            /* initialize app */
        }
    }
}

During development, your code can also catch exceptions and write the stack trace to the system log:

void someOtherMethod() {
    try {
        ...
    } catch (SomeException e) {
        Log.d(TAG, "someOtherMethod()", e);
    }
}

Note: Remove debug log messages and stack trace print calls from your code when you are ready to publish your app. You could do this by setting aDEBUG flag and placing debug log messages inside conditional statements.

View the system log

Both the Android DDMS (Dalvik Debug Monitor Server) and the Android Monitor windows show logs from the system and any particular app process. To view the system log on the Android DDMS tool window:

  1. Start your app as described in Run your App in Debug Mode.
  2. Click Android Monitor [image] .
  3. If the system log is empty in the Logcat view, click Restart [image] .

Figure 2. The system log in the Android DDMS tool window.

The Android DDMS tool window gives you access to some DDMS features from Android Studio. For more information about DDMS, see Using DDMS.

The system log shows messages from Android services and other Android apps. To filter the log messages to view only the ones you are interested in, use the tools in the Android DDMS window:

  • To show only log messages for a particular process, select the process in the Devices view and then click Only Show Logcat from Selected Process [image] . If the Devices view is not available, click Restore Devices View [image] on the right of the Android DDMS tool window. This button is only visible when you hide the Devices window.
  • To filter log messages by log level, select a level from the Log Level drop-down on the top of the Android DDMS window.
  • To show only log messages that contain a particular string, enter the string in the search box and press Enter.

Work with Breakpoints

Android Studio supports several types of breakpoints that trigger different debugging actions. The most common type is a line breakpoint that pauses the execution of your app at a specified line of code. While paused, you can examine variables, evaluate expressions, then continue execution line by line to determine the causes of runtime errors.

To add a line breakpoint, proceed as follows:

  1. Locate the line of code where you want to pause execution, then either click the left gutter along that line of code or place the caret on the line and press Control+F8 (on Mac, Command+F8).
  2. If your app is already running, you don't need to update it to add the breakpoint—just click Attach debugger to Android proccess [image] . Otherwise, start debugging by clicking Debug [image] .

Figure 3. A red dot appears next to the line when you set a breakpoint.

When your code execution reaches the breakpoint, Android Studio pauses execution of your app. You can then use the tools in the Debugger tab to identify the state of the app:

  • To examine the object tree for a variable, expand it in the Variables view. If the Variables view is not visible, click Restore Variables View [image] .

  • To evaluate an expression at the current execution point, click Evaluate Expression [image] .

  • To advance to the next line in the code (without entering a method), click Step Over [image] .

  • To advance to the first line inside a method call, click Step Into [image] .

  • To advance to the next line outside the current method, click Step Out [image] .

  • To continue running the app normally, click Resume Program [image] .

View and configure breakpoints

To view all the breakpoints and configure breakpoint settings, click View Breakpoints [image] on the left side of the Debug window. The Breakpoints window appears, as shown in figure 4.

Figure 4. The Breakpoints window lists all the current breakpoints and includes behavior settings for each.

The Breakpoints window lets you enable or disable each breakpoint from the list on the left. If a breakpoint is disabled, Android Studio does not pause your app when it hits that breakpoint. Select a breakpoint from the list to configure its settings. You can configure a breakpoint to be disabled at first and have the system enable it after a different breakpoint is hit. You can also configure whether a breakpoint should be disabled after it is hit. To set a breakpoint for any exception, select Exception Breakpoints in the list of breakpoints.

Debug Window Frames

In the Debugger window, the Frames pane allows you to inspect the stack frame that caused the current breakpoint to be hit. This enables you to navigate and examine the stack frame and also inspect the list of threads in your Android app. To select a thread, use the thread selector dropdown and view it's stack frame. Clicking on the elements in the frame opens the source in the editor. You can also customize the thread presentation and export the stack frame as discussed in the Window Frames guide.

View Variables and Evaluate Expressions

In the Debugger window, the Variables pane allows you to inspect variables when the app has stopped on a breakpoint and you select a frame from theFrames pane. The Variables pane also allows you to evaluate ad-hoc expressions using static methods and/or variables available within the selected frame.

The Watches pane provides similar functionality except that expressions added to the Watches pane persist between debugging sessions. You should add watches for variables and fields that you access frequently or that provide state that is helpful for the current debugging session. The Variables andWatches panes appear as shown in figure 5.

To add a variable or expression to the Watches list, follow these steps:

  1. Begin debugging.
  2. In the Watches pane, click Add [image] .
  3. In the text box that appears, type the name of the variable or expression you want to watch and then press Enter.

To remove an item from the Watches list, select the item and then click Remove [image] .

You can reorder the elements in the Watches list by selecting an item and then clicking Up [image] or Down [image] .

Figure 5. The Variables and Watches panes in the Debugger window.

Track Object Allocation

Android Studio lets you track objects that are being allocated on the Java heap and see which classes and threads are allocating these objects. This allows you to see the list of objects allocated during a period of interest. This information is valuable for assessing memory usage that can affect application performance.

To track memory allocation of objects:

  1. Start your app as described in Run Your App in Debug Mode.
  2. Click Android [image] to open the Android DDMS tool window.
  3. On the Android DDMS tool window, select the Devices | logcat tab.
  4. Select your device from the dropdown list.
  5. Select your app by its package name from the list of running apps.
  6. Click Start Allocation Tracking
  7. Interact with your app on the device.
  8. Click Stop Allocation Tracking

Android Studio shows the objects that the system allocated with the following information:

  • Allocation order
  • Allocated class
  • Allocation size
  • Thread ID
  • Allocation method, class, and line number
  • Stack trace at the point of allocation

Figure 6. Object allocation tracking in Android Studio.

Analyze Runtime Metrics to Optimize your App

Even if your application does not generate runtime errors, this does not mean it is free of problems. You should also consider the following issues:

  • Does your app use memory efficiently?
  • Does your app generate unnecessary network traffic?
  • What methods should you focus your attention on to improve the performance of your app?
  • Does your app behave properly when the user receives a phone call or a message?

The Android Device Monitor is a stand-alone tool with a graphical user interface for serveral Android application debugging and analysis tools, including the Dalvik Debug Monitor Server (DDMS). You can use the Android Device Monitor to analyze memory usage, profile methods, monitor network traffic and simulate incoming calls and messages.

To open the Android Device Monitor from Android Studio, click Monitor [image] on the toolbar. The Android Device Monitor opens in a new window.

For more information about the Android Device Monitor and DDMS, see Device Monitor and Using DDMS.

Capture Screenshots and Videos

Android Studio enables you to capture a screenshot or a short video of the device screen while your app is running. Screenshots and videos are useful as promotional materials for your app, and you can also attach them to bug reports that you send to your development team.

To take a screenshot of your app:

  1. Start your app as described in Run your App in Debug Mode.
  2. Click Android Monitor [image] .
  3. Click Screen Capture [image] on the left.
  4. Optional: To add a device frame around your screenshot, click Frame screenshot.
  5. Click Save.

To take a video recording of your app:

  1. Start your app as described in Run your App in Debug Mode.
  2. Click Android Monitor [image] .
  3. Click Screen Record [image] on the left.
  4. Click Start Recording.
  5. Interact with your app.
  6. Click Stop Recording.
  7. Enter a file name for the recording and click OK.
    来源： https://developer.android.com/studio/debug/index.html


Write and View Logs with Logcat

  1. Writing Log Messages
  2. logcat Message Format
  3. Displaying a Running App in the logcat Monitor
  4. Setting the Log Level
  5. Searching logcat Messages
  6. Filtering logcat Messages
  7. Configuring the logcat Header Display
  8. Moving Up and Down the Stack Trace
  9. Moving to the End of the Log
  10. Printing and Writing to a File
  11. Clearing and Restarting the Log

Android Studio includes a logcat tab inside Android Monitor that prints system events, such as when a garbage collection occurs, as well as messages your app prints with the Log class to assist with debugging. Logcat displays messages in real time and also keeps a history so you can view older messages.

To display just the information of interest, you can create filters, modify how much information is displayed in messages, set priority levels, display messages produced by app code only, and search the log. By default, the logcat Monitor shows the log output related to the most recently run app only.

When an app throws an exception, the logcat Monitor shows a message followed by the associated stack trace containing links to the code. This feature can help you fix errors and improve app operation.

Writing Log Messages

The Log class allows you to create log messages that appear in the logcat window. Generally, you should use the following log methods, listed in order from the highest to lowest priority (or, least to most verbose):

  • Log.e(String, String) (error)
  • Log.w(String, String) (warning)
  • Log.i(String, String) (information)
  • Log.d(String, String) (debug)
  • Log.v(String, String) (verbose)

You should never compile versbose logs into your app, except during development. Debug logs are compiled in but stripped at runtime, while error, warning and info logs are always kept.

For each log method, the first parameter should be a unique tag and the second parameter is the message. The tag of a system log message is a short string indicating the system component from which the message originates (for example, ActivityManager ). Your tag can be any string that you find helpful, such as the name of the current class.

A good convention is to declare a TAG constant in your class to use in the first parameter. For example, you might create an information log message as follows:

private static final String TAG = "MyActivity";
...
Log.i(TAG, "MyClass.getView() — get item number " + position);

Note: Tag names greater than 23 characters are truncated in the logcat output.

logcat Message Format

The printed log message appears in logcat as follows:

date time PID-TID/package priority/tag: message

For example, the Log.i() code example above has a priority of I (for "information") and a tag of MyActivity:

12-10 13:02:50.071 1901-4229/com.google.android.gms I/MyActivity: MyClass.getView() — get item number 1

PID stands for process identifier and TID is thread identifier; they can be the same if there’s only one thread.

Displaying a Running App in the logcat Monitor

To display the log messages for a particular app:

  1. Meet the prerequisites and dependencies.
  2. Open an app project.
  3. Run the app on a hardware device or emulator.
  4. Display Android Monitor.
  5. Click the logcat tab.

    6. By default, the logcat Monitor displays just the log messages for your app running on the device or emulator:

    To change this default, see Filtering logcat Messages.

  6. Optionally select a different device, emulator, or process.

Setting the Log Level

You can control how many messages appear in the logcat Monitor by setting the log level. You can display all messages, or just the messages indicating the most severe conditions.

Remember that the logcat Monitor continues to collect all messages regardless of the log level setting. The setting just determines what the logcat Monitor displays.

To set the log level:

  • In the Log level menu, select one of the following values:
    • Verbose - Show all log messages (the default).
    • Debug - Show debug log messages that are useful during development only, as well as the message levels lower in this list.
    • Info - Show expected log messages for regular usage, as well as the message levels lower in this list.
    • Warn - Show possible issues that are not yet errors, as well as the message levels lower in this list.
    • Error - Show issues that have caused errors, as well as the message level lower in this list.
    • Assert - Show issues that the developer expects should never happen.

Searching logcat Messages

To search the messages currently displayed in the logcat Monitor:

  1. Optionally select Regex if you want to use a regular expression search pattern.
  2. Type a character sequence in the search field [image] .

    3. The logcat Monitor display changes accordingly.

  3. Press Enter to store the search string in the menu during this session.
  4. To repeat a search, choose it from the search menu. Select or deselect Regex as needed (the setting isn’t remembered).

Filtering logcat Messages

One way to reduce the log output to a manageable level is to restrict it by using a filter.

Note: The filter applies to your full logcat history, not just those messages currently displayed in the logcat Monitor. Make sure your other display options are set appropriately so you can see the filter output you want to examine.

To define and apply a filter:

  1. In the filter menu, select a filter option:
    • Show only selected application - Display the messages produced by the app code only (the default). The logcat Monitor filters the log messages using the PID of the active app.
    • No Filters - Apply no filters. The logcat Monitor displays all log messages from the device, regardless of which process you selected.
    • Edit Filter Configuration - Create or modify a custom filter. For example, you could create a filter to view log messages from two apps at the same time.

    After you define filters, you can also select them in the menu. To remove them from the menu, delete them.

  2. If you selected Edit Filter Configuration, create or modify a filter.
    1. Specify the filter parameters in the Create New Logcat Filter dialog:
      • Filter Name - Type the name of a filter you want to define, or select it in the left pane to modify an existing filter. The name can contain lowercase characters, underscores, and digits only.
      • Log Tag - Optionally specify a tag. For more information, see logcat Message Format.
      • Log Message - Optionally specify log message text. For more information, see logcat Message Format.
      • Package Name - Optionally specify a package name. For more information, see logcat Message Format.
      • PID - Optionally specify a process ID. For more information, see logcat Message Format.
      • Log Level - Optionally select a log level. For more information, see Setting the Log Level.
      • Regex - Select this option to use regular expression syntax for that parameter.
    2. Click + to add the filter definition to the left pane.

      3. To remove a filter, select it in the left pane and click -.

    3. When you’re finished, click OK. If you click Cancel, any filter additions or modifications are lost.
  3. Make sure you see the log messages you want to examine.

    4. If you don't think you see the log messages you want, try selecting No filters and searching for particular log messages.

Configuring the logcat Header Display

To customize the header display to show just the information you’re interested in:

  • Select Use Soft Wraps [image] to see the entire message and prevent it from running off of the right edge.
  • Click Configure Logcat Header [image] to specify elements of the messages that you want to show or hide, and then click OK.

For more information about message elements, see logcat Message Format.

Moving Up and Down the Stack Trace

When the app throws an exception, the message includes a stack trace of method calls. logcat Monitor lets you quickly locate stack traces in the log and view the associated code in the Code Editor. If needed (and possible), the decompiler derives source code that you can view.

To move up and down the stack trace, and view the associated code in the Code Editor:

  • Click Up the Stack Trace [image] to move to the previous method in relation to the current position in the log.
  • Click Down the Stack Trace [image] to move to the next method in relation to the current position in the log.

Moving to the End of the Log

Clicking a particular message stops the display of messages.

To quickly move to the end of the log to see the real-time message flow:

  • Click Scroll to the End [image] .
  • Press the End key.
  • Scroll or press the Page Down key until you reach the end.

Printing and Writing to a File

To preserve log information, you can send the log to a printer, write the log to a PDF file, or copy and paste the log into a text file.

To print the log or write it to a PDF file:

  1. Click Print [image] .
  2. In the Android Studio Print dialog, optionally change print parameters, and then click Print.
  3. In the operating system Print dialog, optionally change print parameters, and then click Print.

    4. You can set the parameters to send the log to a printer or write it to a PDF file.

To copy the log to a text file:

  1. In the logcat Monitor, select and then copy log text.

    2. Press Ctrl+A (?A) to select all.

  2. Open a text editor and paste the text into a file.

Clearing and Restarting the Log

To clear (flush) the entire log:

  • Click Clear logcat [image] .

If there's a problem and the log is no longer progressing, you can restart the log:

  • Click Restart

来源： https://developer.android.com/studio/debug/am-logcat.html


Analyze a Stack Trace

In This Document

  1. Open Stack Traces from External Sources
  2. Monitor the Clipboard for New Stacktraces

Debugging an app often requires working with stack traces. A stack trace is generated whenever your app crashes because of an error or an exception. You can also print a stack trace at any point in your app code using methods such as Thread.dumpStack().

While your app is running in debug mode on a connected device or emulator, Android Studio prints and highlights stack traces in the Android Monitor logcat view, as shown in figure 1.

Figure 1. A stacktrace in the Android Monitor logcat.

A stack trace shows a list of method calls that lead to the exception being thrown, together with the filenames and line numbers where the calls happened. You can click on the highlighted filenames to open the files and examine the source of the method invocation. Click Up the stack trace [image] andDown the stack trace [image] to quickly move between stack trace lines displayed in the logcat window.

Open Stack Traces from External Sources

Sometimes you want to analyze stack traces that were shared with you in a bug report as opposed to those you found while debugging. For example, you might be collecting stack traces generated on your users’ devices from the Google Play Console or from some other tool such as Firebase Crash Reporting.

To get the same highlighted and clickable view of an external stack trace from a bug report, follow these steps:

  1. Open your project in Android Studio.

    Note: Make sure the source code you're viewing is from the exact same version of your app which generated the stack trace. If the code is different, you will get mismatches between the filenames and line numbers, or the order of calls in the stack trace and your project.

  2. From the Analyze menu, click Analyze stacktrace.

  3. Paste the stack trace text into the Analyze Stacktrace window and click OK.
  4. Android Studio opens a new <Stacktrace> tab with the stack trace you pasted under the Run window.

Monitor the Clipboard for New Stacktraces

If you work with external stack traces a lot, you can improve your productivity by allowing Android Studio to continuously monitor the system clipboard for new stacktraces:

  1. Open the Analyze Stacktrace tool.
  2. Check the Automatically detect and analyze thread dumps copied to the clipboard outside of IntelliJ IDEA checkbox.
  3. Copy a stack trace in another application (such as from a web browser) to the system clipboard.
  4. When you come back to the Android Studio window, the stack trace opens automatically under the Run window, without you having to paste it in the Analyze Stacktrace window.

    来源： https://developer.android.com/studio/debug/stacktraces.html


Take a Screenshot

Android Monitor lets you take a PNG screenshot of the display on a connected device or the emulator. You can use the images for your marketing materials as well as for debugging, for example.

Taking a Screen Capture of the Device

To take a screen capture:

  1. Meet the prerequisites and dependencies.
  2. Open an app project.
  3. Run the app on a hardware device or emulator.
  4. Display Android Monitor.
  5. Interact with the display on the device or emulator to stage the image you want.
  6. Click Screen Capture [image] in the Android Monitor toolbar.

    7. The screenshot appears in a Screenshot Editor window.

  7. Optionally change the image:
    • Recapture - Click to take a new screenshot.
    • Rotate - Click to rotate the image 90 degrees clockwise.
    • Frame Screenshot - Select this option and choose a device to add an image of the device to the outside of the screenshot. Select Drop Shadow,Screen Glare, or both to add these effects to your image.
    • Chessboard and Grid - Select an option to display these behind your image.
    • Zoom In, Zoom Out, or Actual Size - Click these options to get different perspectives of your image without changing the image itself.
  8. Click Save to save the image.
  9. In the Save as PNG dialog, specify the location and filename, and then click OK.

    10. The screenshot file appears in the Code Editor area.

    来源： https://developer.android.com/studio/debug/am-screenshot.html


Record a Video

Android Monitor lets you record an MP4 video from your hardware device for a maximum of three minutes. You can use the video for your marketing materials as well as for debugging, for example.

Recording a Video from the Screen

To record a video from a hardware device:

  1. Meet the prerequisites and dependencies.
  2. Open an app project.
  3. Run the app on a hardware device.
  4. Display Android Monitor.
  5. Interact with the display on the hardware device to stage the start of the video.
  6. Click Screen Record [image] in the Android Monitor toolbar.
  7. In the Screen Recorder Options dialog, optionally change the recording options:
    • Bit Rate - Type a bit rate. The default is 4 Mbps.
    • Resolution - Type a width and height value in pixels. The value must be a multiple of 16. The default is the resolution of the device.
  8. Click Start Recording to start the recording.
  9. Click Stop Recording to stop the recording.
  10. In the Save As dialog, save the MP4 file.
  11. In the Screen Recorder dialog, click one of the buttons to show the file location, open the recording in a player, or to dismiss the dialog.

    来源： https://developer.android.com/studio/debug/am-video.html


monkeyrunner

  1. A Simple monkeyrunner Program
  2. The monkeyrunner API
  3. Running monkeyrunner
  4. monkeyrunner Built-in Help
  5. Extending monkeyrunner with Plugins

See Also

  1. Testing Fundamentals

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
from com.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:

from com.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 themonkeyrunner command which is found in the tools/ subdirectory of your SDK directory. If you provide a filename as an argument, the monkeyrunnercommand 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, seeExtending 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 incom.android.monkeyrunner (see The monkeyrunner 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 keyMonkeyRunnerStartupRunner 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:

package com.android.example;

import com.google.common.base.Predicate;
import org.python.util.PythonInterpreter;

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

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

        return true;
    }
}

来源： https://developer.android.com/studio/test/monkeyrunner/index.html


MonkeyDevice

A monkeyrunner class that represents a device or emulator accessible by the workstation running monkeyrunner.

This class is used to control an Android device or emulator. The methods send UI events, retrieve information, install and remove applications, and run applications.

You normally do not have to create an instance of MonkeyDevice. Instead, you use MonkeyRunner.waitForConnection() to create a new object from a connection to a device or emulator. For example, instead of using:

newdevice = MonkeyDevice()

you would use:

newdevice = MonkeyRunner.waitForConnection()

Summary

Constants
string | DOWN | Use this with the type argument of press() or touch() to send a DOWN event.
string | UP | Use this with the type argument of press() or touch() to send an UP event.
string | DOWN_AND_UP | Use this with the type argument of press() or touch() to send a DOWN event immediately followed by an UP event.
Methods
void | broadcastIntent (string uri, string action, string data, string mimetype, iterable categories dictionary extras, component component, iterable flags) Broadcasts an Intent to this device, as if the Intent were coming from an application.
void | drag (tuple start, tuple end, float duration, integer steps) Simulates a drag gesture (touch, hold, and move) on this device's screen.
object | getProperty (string key) Given the name of a system environment variable, returns its value for this device. The available variable names are listed in the detailed description of this method.
object | getSystemProperty (string key) . The API equivalent of adb shell getprop <key>. This is provided for use by platform developers.
void | installPackage (string path) Installs the Android application or test package contained in packageFile onto this device. If the application or test package is already installed, it is replaced.
dictionary | instrument (string className, dictionary args) Runs the specified component under Android instrumentation, and returns the results in a dictionary whose exact format is dictated by the component being run. The component must already be present on this device.
void | press (string name, dictionary type) Sends the key event specified by type to the key specified by keycode.
void | reboot (string into) Reboots this device into the bootloader specified by bootloadType.
void | removePackage (string package) Deletes the specified package from this device, including its data and cache.
object | shell (string cmd) Executes an adb shell command and returns the result, if any.
void | startActivity (string uri, string action, string data, string mimetype, iterable categories dictionary extras, component component, flags) Starts an Activity on this device by sending an Intent constructed from the supplied arguments.
MonkeyImage | takeSnapshot() Captures the entire screen buffer of this device, yielding a MonkeyImage object containing a screen capture of the current display.
void | touch (integer x, integer y, integer type) Sends a touch event specified by type to the screen location specified by x and y.
void | type (string message) Sends the characters contained in message to this device, as if they had been typed on the device's keyboard. This is equivalent to callingpress() for each keycode in message using the key event type DOWN_AND_UP.
void | wake () Wakes the screen of this device.

Constants

string DOWN

press() or touch() value. Specifies that a DOWN event type should be sent to the device, corresponding to pressing down on a key or touching the screen.

string UP

press() or touch() value. Specifies that an UP event type should be sent to the device, corresponding to releasing a key or lifting up from the screen.

string DOWN_AND_UP

press(), touch() or type() value. Specifies that a DOWN event type followed by an UP event type should be sent to the device, corresponding to typing a key or clicking the screen.

Public Methods

void broadcastIntent ( string uri, string action, string data, string mimetype, iterable categories dictionary extras,component component, iterable flags)

Broadcasts an Intent to this device, as if the Intent were coming from an application. See Intent for more information about the arguments.

Arguments
uri | The URI for the Intent. (see Intent.setData()).
action | The action for this Intent (see Intent.setAction()).
data | The data URI for this Intent (see Intent.setData()).
mimetype | The MIME type for the Intent (see Intent.setType()).
categories | An iterable data structure containing strings that define categories for this Intent (see Intent.addCategory()).
extras | A dictionary of extra data for this Intent (see Intent.putExtra() for an example). The key for each dictionary item should be a string. The item's value can be any simple or structured data type.
component | The component for this Intent (see ComponentName). Using this argument will direct the Intent to a specific class within a specific Android package.
flags | An iterable data structure containing flags that control how the Intent is handled (see Intent.setFlags()).

void drag ( tuple start, tuple end, float duration, integer steps)

Simulates a drag gesture (touch, hold, and move) on this device's screen.

Arguments
start | The starting point of the drag gesture, in the form of a tuple (x,y) where x and y are integers.
end | The end point of the drag gesture, in the form of a tuple (x,y) where x and y are integers.
duration | The duration of the drag gesture in seconds. The default is 1.0 seconds.
steps | The number of steps to take when interpolating points. The default is 10.

object getProperty (string key)

Given the name of a system environment variable, returns its value for this device.

Arguments
key The name of the system environment variable. The available variable names are listed in Table 1. Property variable names at the end of this topic.
Returns
  • The value of the variable. The data format varies according to the variable requested.

object getSystemProperty (string key)

Synonym for getProperty().

Arguments
key The name of the system environment variable. The available variable names are listed in Table 1. Property Variable Names.
Returns
  • The value of the variable. The data format varies according to the variable requested.

void installPackage (string path)

Installs the Android application or test package contained in packageFile onto this device. If the application or test package is already installed, it is replaced.

Arguments
path The fully-qualified path and filename of the .apk file to install.

dictionary instrument ( string className, dictionary args)

Runs the specified component with Android instrumentation, and returns the results in a dictionary whose exact format is dictated by the component being run. The component must already be present on this device.

Use this method to start a test case that uses one of Android's test case classes. See Testing Fundamentals to learn more about unit testing with the Android testing framework.

Arguments
className | The name of an Android component that is already installed on this device, in the standard form packagename/classname, where packagename is the Android package name of a .apk file on this device, and classname is the class name of an Android component (Activity, ContentProvider, Service, or BroadcastReceiver) in that file. Both packagename and classname must be fully qualified. See ComponentName for more details.
args | A dictionary containing flags and their values. These are passed to the component as it is started. If the flag does not take a value, set its dictionary value to an empty string.
Returns

  • A dictionary containing the component's output. The contents of the dictionary are defined by the component itself.

    If you use InstrumentationTestRunner as the class name in the componentName argument, then the result dictionary contains the single key "stream". The value of "stream" is a string containing the test output, as if InstrumentationTestRunner was run from the command line. The format of this output is described in Testing in Other IDEs.

void press (string name, integer type)

Sends the key event specified by type to the key specified by keycode.

Arguments
name | The name of the keycode to send. See KeyEvent for a list of keycode names. Use the keycode name, not its integer value.
type | The type of key event to send. The allowed values are DOWN, UP, and DOWN_AND_UP.

void reboot (string bootloadType)

Reboots this device into the bootloader specified by bootloadType.

Arguments
into The type of bootloader to reboot into. The allowed values are "bootloader", "recovery", or "None".

void removePackage (string package)

Deletes the specified package from this device, including its data and cache.

Arguments
package The Android package name of an .apk file on this device.

object shell (string cmd)

Executes an adb shell command and returns the result, if any.

Arguments
cmd The command to execute in the adb shell. The form of these commands is described in the topic Android Debug Bridge.
Returns
  • The results of the command, if any. The format of the results is determined by the command.

void startActivity ( string uri, string action, string data, string mimetype, iterable categories dictionary extras, componentcomponent, iterable flags)

Starts an Activity on this device by sending an Intent constructed from the supplied arguments.

Arguments
uri | The URI for the Intent. (see Intent.setData()).
action | The action for the Intent (see Intent.setAction()).
data | The data URI for the Intent (see Intent.setData()).
mimetype | The MIME type for the Intent (see Intent.setType()).
categories | An iterable data structure containing strings that define categories for the Intent (see Intent.addCategory()).
extras | A dictionary of extra data for the Intent (see Intent.putExtra() for an example). The key for each dictionary item should be a string. The item's value can be any simple or structured data type.
component | The component for the Intent (see ComponentName). Using this argument will direct the Intent to a specific class within a specific Android package.
flags | An iterable data structure containing flags that control how the Intent is handled (see Intent.setFlags()).

MonkeyImage takeSnapshot ()

Captures the entire screen buffer of this device, yielding a screen capture of the current display.

Returns
  • A MonkeyImage object containing the image of the current display.

void touch ( integer x, integer y, string type)

Sends a touch event specified by type to the screen location specified by x and y.

Arguments
x | The horizontal position of the touch in actual device pixels, starting from the left of the screen in its current orientation.
y | The vertical position of the touch in actual device pixels, starting from the top of the screen in its current orientation.
type | The type of key event to send. The allowed values are DOWN, UP, and DOWN_AND_UP.

void type (string message)

Sends the characters contained in message to this device, as if they had been typed on the device's keyboard. This is equivalent to calling press() for each keycode in message using the key event type DOWN_AND_UP.

Arguments
message A string containing the characters to send.

void wake ()

Wakes the screen of this device.

Appendix

Table 1.Property variable names used with getProperty() and getSystemProperty().

Property Group | Property | Description | Notes
build | board | Code name for the device's system board | See Build
 | brand | The carrier or provider for which the OS is customized.
 | device | The device design name.
 | fingerprint | A unique identifier for the currently-running build.
 | host |
 | ID | A changelist number or label.
 | model | The end-user-visible name for the device.
 | product | The overall product name.
 | tags | Comma-separated tags that describe the build, such as "unsigned" and "debug".
 | type | The build type, such as "user" or "eng".
 | user |
 | CPU_ABI | The name of the native code instruction set, in the form CPU type plus ABI convention.
 | manufacturer | The product/hardware manufacturer.
 | version.incremental | The internal code used by the source control system to represent this version of the software.
 | version.release | The user-visible name of this version of the software.
 | version.sdk | The user-visible SDK version associated with this version of the OS.
 | version.codename | The current development codename, or "REL" if this version of the software has been released.
display | width | The device's display width in pixels. | SeeDisplayMetrics for details.
 | height | The device's display height in pixels.
 | density | The logical density of the display. This is a factor that scales DIP (Density-Independent Pixel) units to the device's resolution. DIP is adjusted so that 1 DIP is equivalent to one pixel on a 160 pixel-per-inch display. For example, on a 160-dpi screen, density = 1.0, while on a 120-dpi screen, density = .75. The value does not exactly follow the real screen size, but is adjusted to conform to large changes in the display DPI. See density for more details.
am.current | package | The Android package name of the currently running package. | The am.currentkeys return information about the currently-running Activity.
 | action | The current activity's action. This has the same format as the name attribute of theaction element in a package manifest.
 | comp.class | The class name of the component that started the current Activity. Seecomp.package for more details.
 | comp.package | The package name of the component that started the current Activity. A component is specified by a package name and the name of class that the package contains.
 | data | The data (if any) contained in the Intent that started the current Activity.
 | categories | The categories specified by the Intent that started the current Activity.
clock | realtime | The number of milliseconds since the device rebooted, including deep-sleep time. | See SystemClockfor more information.
 | uptime | The number of milliseconds since the device rebooted, not including deep-sleep time
 | millis | current time since the UNIX epoch, in milliseconds.
来源： https://developer.android.com/studio/test/monkeyrunner/MonkeyDevice.html


MonkeyImage

A monkeyrunner class to hold an image of the device or emulator's screen. The image is copied from the screen buffer during a screenshot. This object's methods allow you to convert the image into various storage formats, write the image to a file, copy parts of the image, and compare this object to otherMonkeyImage objects.

You do not need to create new instances of MonkeyImage. Instead, use MonkeyDevice.takeSnapshot() to create a new instance from a screenshot. For example, use:

newimage = MonkeyDevice.takeSnapshot()

Summary

Methods
string | convertToBytes (string format) Converts the current image to a particular format and returns it as a string that you can then access as an iterable of binary bytes.
tuple | getRawPixel (integer x, integer y) Returns the single pixel at the image location (x,y), as an a tuple of integer, in the form (a,r,g,b).
integer | getRawPixelInt (integer x, integer y) Returns the single pixel at the image location (x,y), as a 32-bit integer.
MonkeyImage | getSubImage (tuple rect) Creates a new MonkeyImage object from a rectangular selection of the current image.
boolean | sameAs (MonkeyImage other, float percent) Compares this MonkeyImage object to another and returns the result of the comparison. The percent argument specifies the percentage difference that is allowed for the two images to be "equal".
void | writeToFile (string path, string format) Writes the current image to the file specified by filename, in the format specified by format.

Public Methods

string convertToBytes ( string format)

Converts the current image to a particular format and returns it as a string that you can then access as an iterable of binary bytes.

Arguments
format The desired output format. All of the common raster output formats are supported. The default value is "png" (Portable Network Graphics).

tuple getRawPixel (integer x, integer y)

Returns the single pixel at the image location (x,y), as an a tuple of integer, in the form (a,r,g,b).

Arguments
x | The horizontal position of the pixel, starting with 0 at the left of the screen in the orientation it had when the screenshot was taken.
y | The vertical position of the pixel, starting with 0 at the top of the screen in the orientation it had when the screenshot was taken.
Returns
  • A tuple of integers representing the pixel, in the form (a,r,g,b) where a is the alpha channel value, and r, g, and b are the red, green, and blue values, respectively.

tuple getRawPixelInt (integer x, integer y)

Returns the single pixel at the image location (x,y), as an an integer. Use this method to economize on memory.

Arguments
x | The horizontal position of the pixel, starting with 0 at the left of the screen in the orientation it had when the screenshot was taken.
y | The vertical position of the pixel, starting with 0 at the top of the screen in the orientation it had when the screenshot was taken.
Returns
  • The a,r,g, and b values of the pixel as 8-bit values combined into a 32-bit integer, with a as the leftmost 8 bits, r the next rightmost, and so forth.

MonkeyImage getSubImage (tuple rect)

Creates a new MonkeyImage object from a rectangular selection of the current image.

Arguments
rect A tuple (x, y, w, h) specifying the selection. x and y specify the 0-based pixel position of the upper left-hand corner of the selection. w specifies the width of the region, and h specifies its height, both in units of pixels.

The image's orientation is the same as the screen orientation at the time the screenshot was made.

Returns
  • A new MonkeyImage object containing the selection.

boolean sameAs ( MonkeyImage otherImage, float percent )

Compares this MonkeyImage object to another and returns the result of the comparison. The percent argument specifies the percentage difference that is allowed for the two images to be "equal".

Arguments
other | Another MonkeyImage object to compare to this one.
percent | A float in the range 0.0 to 1.0, inclusive, indicating the percentage of pixels that need to be the same for the method to return true. The default is 1.0, indicating that all the pixels must match.
Returns
  • Boolean true if the images match, or boolean false otherwise.

void writeToFile (string filename, string format)

Writes the current image to the file specified by filename, in the format specified by format.

Arguments
path | The fully-qualified filename and extension of the output file.
format | The output format to use for the file. If no format is provided, then the method tries to guess the format from the filename's extension. If no extension is provided and no format is specified, then the default format of "png" (Portable Network Graphics) is used.
来源： https://developer.android.com/studio/test/monkeyrunner/MonkeyImage.html


MonkeyRunner

A monkeyrunner class that contains static utility methods.

Summary

Methods
void | alert (string message, string title, string okTitle) Displays an alert dialog to the process running the current program.
integer | choice (string message, iterable choices, string title) Displays a dialog with a list of choices to the process running the current program.
void | help (string format) Displays the monkeyrunner API reference in a style similar to that of Python's pydoc tool, using the specified format.
string | input (string message, string initialValue, string title, string okTitle, string cancelTitle) Displays a dialog that accepts input.
void | sleep (float seconds) Pauses the current program for the specified number of seconds.
MonkeyDevice | waitForConnection (float timeout, string deviceId) Tries to make a connection between the monkeyrunner backend and the specified device or emulator.

Public Methods

string alert ( string message, string title, string okTitle)

Displays an alert dialog to the process running the current program. The dialog is modal, so the program pauses until the user clicks the dialog's button.

Arguments
message | The message to display in the dialog.
title | The dialog's title. The default value is "Alert".
okTitle | The text displayed in the dialog button. The default value is "OK".

integer choice (string message, iterable choices, string title)

Displays a dialog with a list of choices to the process running the current program. The dialog is modal, so the program pauses until the user clicks one of the dialog's buttons.

Arguments
message | The prompt message displayed in the dialog.
choices | A Python iterable containing one or more objects that are displayed as strings. The recommended form is an array of strings.
title | The dialog's title. The default is "Input".
Returns
  • If the user makes a selection and clicks the "OK" button, the method returns the 0-based index of the selection within the iterable. If the user clicks the "Cancel" button, the method returns -1.

void help (string format)

Displays the monkeyrunner API reference in a style similar to that of Python's pydoc tool, using the specified format.

Arguments
format The markup format to use in the output. The possible values are "text" for plain text or "html" for HTML.

string input (string message string initialValue, string title, string okTitle, string cancelTitle)

Displays a dialog that accepts input and returns it to the program. The dialog is modal, so the program pauses until the user clicks one of the dialog's buttons.

The dialog contains two buttons, one of which displays the okTitle value and the other the cancelTitle value. If the user clicks the okTitle button, the current value of the input box is returned. If the user clicks the cancelTitle button, an empty string is returned.

Arguments
message | The prompt message displayed in the dialog.
initialValue | The initial value to display in the dialog. The default is an empty string.
title | The dialog's title. The default is "Input".
okTitle | The text displayed in the okTitle button. The default is "OK".
cancelTitle | The text displayed in the cancelTitle button. The default is "Cancel".
Returns
  • If the user clicks the okTitle button, then the method returns the current value of the dialog's input box. If the user clicks the cancelTitle button, the method returns an empty string.

void sleep ( float seconds )

Pauses the current program for the specified number of seconds.

Arguments
seconds The number of seconds to pause.

MonkeyDevice waitForConnection (float timeout, string deviceId)

Tries to make a connection between the monkeyrunner backend and the specified device or emulator.

Arguments
timeout | The number of seconds to wait for a connection. The default is to wait forever.
deviceId | A regular expression that specifies the serial number of the device or emulator. See the topic Android Debug Bridge for a description of device and emulator serial numbers.
Returns
  • A MonkeyDevice instance for the device or emulator. Use this object to control and communicate with the device or emulator.

    来源： https://developer.android.com/studio/test/monkeyrunner/MonkeyRunner.html


Test Your App

  1. Test Types and Location
  2. Add a New Test
    1. Create instrumented test for a build variant
  3. Run a Test
  4. Change the Test Build Type

Android Studio is designed to make testing simple. With just a few clicks, you can set up a JUnit test that runs on the local JVM or an instrumented test that runs on a device. Of course, you can also extend your test capabilities by integrating test frameworks such as Mockito to test Android API calls in your local unit tests, and Espresso or UI Automator to exercise user interaction in your instrumented tests.

This page provides the basic information about how to add new tests to your app and run them from Android Studio.

For a more complete how-to guide for writing tests, see Getting Started with Testing.

Test Types and Location

The location of your test code depends on the type of test you are writing. Android Studio provides source code directories (source sets), for the following two types of tests:

Local unit tests

Located at module-name/src/test/java/.

These are tests that run on your machine's local Java Virtual Machine (JVM). Use these tests to minimize execution time when your tests have no Android framework dependencies or when you can mock the Android framework dependencies.

Instrumented tests

Located at module-name/src/androidTest/java/.

These are tests that run on a hardware device or emulator. These tests have access to Instrumentation APIs, give you access to information such as the Context of the app you are testing, and let you control the app under test from your test code. Use these tests when writing integration and functional UI tests to automate user interaction, or when your tests have Android dependencies that mock objects cannot satisfy.

Because instrumented tests are built into a stane-alone APK, they must have an AndroidManifest.xml file. However, Gradle automatically generates this file during the build so it is not visible in your project source set. You can add your own manifest file if necessary, such as to specify a different value for `minSdkVersion` or register run listeners just for your tests. When building your app, Gradle merges multiple manifest files into one manifest.

The Gradle build interprets these test source sets in the same manner as it does for your project's app source sets, which allows you to create tests based on build variants.

When you create a new project or add an app module, Android Studio creates the test source sets listed above and includes an example test file in each. You can see them in the Project window as shown in figure 1.

Figure 1. Your project's (1) instrumented tests and (2) local JVM tests are visible in either the Project view (left) or Android view (right).

Add a New Test

To create either a local unit test or an instrumented test, you can create a new test for a specific class or method by following these steps:

  1. Open the Java file containing the code you want to test.
  2. Click the class or method you want to test, then press Ctrl+Shift+T (??T).
  3. In the menu that appears, click Create New Test.
  4. In the Create Test dialog, edit any fields and select any methods to generate, and then click OK.
  5. In the Choose Destination Directory dialog, click the source set corresponding to the type of test you want to create: androidTest for an instrumented test or test for a local unit test. Then click OK.

Alternatively, you can create a generic Java file in the appropriate test source set as follows:

  1. In the Project window on the left, click the drop-down menu and select the Project view.
  2. Expand the appropriate module folder and the nested src folder. To add a local unit test, expand the test folder and the nested java folder; to add an instrumented test, expand the androidTest folder and the nested java folder.
  3. Right-click on the Java package directory and select New > Java Class.
  4. Name the file and then click OK.

For more information about how to write your tests, see Building Local Unit Tests and Building Instrumented Unit Tests.

Create instrumented test for a build variant

If your project includes build variants with unique source sets, then you might want corresponding instrumented test source sets. Creating instrumented tests in source sets that correspond to your build variants helps keep your test code organized and allows you to run only the tests that apply to a given build variant.

To add a testing source set for your build variant, follow these steps:

  1. In the Project window on the left, click the drop-down menu and select the Project view.
  2. Within the appropriate module folder, right-click the src folder and click New > Directory.
  3. For the directory name, enter "androidTestVariantName." For example, if you have a build variant called "MyFlavor" then the directory name should be "androidTestMyFlavor." Then click OK.
  4. Right-click on the new directory and click New > Directory.
  5. Enter "java" as the directory name, and then click OK.

Now you can add tests to this new source set by following the steps above to add a new test. When you reach the Choose Destination Directory dialog, select the new variant test source set.

The instrumented tests in src/androidTest/ source set are shared by all build variants. When building a test APK for the "MyFlavor" variant of your app, Gradle combines both the src/androidTest/ and src/androidTestMyFlavor/ source sets.

For example, the following table shows how instrumentation test files should reside in source sets that correspond to the app's code source sets.

Path to app class | Path to matching instrumentation test class
src/main/java/Foo.java | src/androidTest/java/AndroidFooTest.java
src/myFlavor/java/Foo.java | src/androidTestMyFlavor/java/AndroidFooTest.java

Just as it does for your app source sets, the Gradle build merges and overrides files from different test source sets. In this case, the AndroidFooTest.javafile in the "androidTestMyFlavor" source set overrides the version in the "androidTest" source set. For more information about how source sets are merged, see [Configure Your Build] (/studio/build/index.html#sourcesets).

Another reason you should use build variants for your app and test source sets is to create hermetic tests through mock dependencies. That is, you can create a product flavor for your app that contains fake implementations of dependencies (such as network requests or device sensor data that is ordinarily flaky), and then add a corresponding mock test source set. For more information, see the blog post about leveraging product flavors for hermetic testing.

Run a Test

To run a test, proceed as follows:

  1. Be sure your project is synchronized with Gradle by clicking Sync Project [image] in the toolbar.
  2. Run your test in one of the following ways:
    • In the Project window, right-click a test and click Run [image] .
    • In the Code Editor, right-click a class or method in the test file and click Run [image] to test all methods in the class.
    • To run all tests, right-click on the test directory and click Run tests [image] .

By default, your test runs using Android Studio's default run configuration. If you'd like to change some run settings such as the instrumentation runner and deployment options, you can edit the run configuration in the Run/Debug Configurations dialog (click Run > Edit Configurations).

Change the Test Build Type

By default, all tests run against the debug build type. You can change this to another build type by using the testBuildType property in your module-levelbuild.gradle file. For example if you want to run your tests against your "staging" build type, edit the file as shown in the following snippet.

android {
    ...
    testBuildType "staging"
}

来源： https://developer.android.com/studio/test/index.html


Test from the Command Line

  1. Running Tests
    1. Running unit tests with Gradle
    2. Running tests with adb
  2. Using the Instrument Command
    1. Instrument options
    2. Instrument examples

See Also

  1. Android Debug Bridge

This document describes how to create and run tests directly from the command line. This document assumes that you already know how to create a Android application in your programming environment.

Running Tests

You can run tests from the command-line, either with Gradle or with an Android Debug Bridge (adb) shell.

Running unit tests with Gradle

The Android Plugin for Gradle lets you run unit tests from your Gradle project via the command-line. For more information on how to build unit tests for your app, see Building Effective Unit Tests.

The table below summarizes how to run your unit tests with Gradle:

Unit Test Type Command To Run Test Result Location
Local unit test Call the test task:
./gradlew test
HTML test result files: <path_to_your_project>/app/build/reports/tests/ directory.

XML test result files: <path_to_your_project>/app/build/test-results/ directory.

Instrumented unit test Call the connectedAndroidTest(or cAT) task:
./gradlew cAT
HTML test result files:<path_to_your_project>/app/build/outputs/reports/androidTests/connected/directory.

XML test result files: <path_to_your_project>/app/build/outputs/androidTest-results/connected/ directory.

Running tests with ADB

When you run tests from the command-line with Android Debug Bridge (adb), you get more options for choosing the tests to run than with any other method. You can select individual test methods, filter tests according to their annotation, or specify testing options. Since the test run is controlled entirely from a command-line, you can customize your testing with shell scripts in various ways.

To run a test from the command-line, you run adb shell to start a command-line shell on your device or emulator, and then in the shell run the am instrument command. You control am and your tests with command-line flags.

As a shortcut, you can start an adb shell, call am instrument, and specify command-line flags all on one input line. The shell opens on the device or emulator, runs your tests, produces output, and then returns to the command-line on your computer.

To run a test with am instrument:

  1. If necessary, rebuild your main application and test package.
  2. Install your test package and main application Android package files (.apk files) to your current Android device or emulator
  3. At the command-line, enter:
    $ adb shell am instrument -w <test_package_name>/<runner_class>

    where <test_package_name> is the Android package name of your test application, and <runner_class> is the name of the Android test runner class you are using. The Android package name is the value of the package attribute of the manifest element in the manifest file (AndroidManifest.xml) of your test package. The Android test runner class is usually AndroidJUnitRunner.

    Your test results appear in STDOUT.

This operation starts an adb shell, then runs am instrument with the specified parameters. This particular form of the command will run all of the tests in your test package. You can control this behavior with flags that you pass to am instrument. These flags are described in the next section.

Using the am instrument Command

The general syntax of the am instrument command is:

am instrument [flags] <test_package>/<runner_class>

The main input parameters to am instrument are described in the following table:

Parameter | Value | Description
<test_package> | The Android package name of the test package. | The value of the package attribute of the manifest element in the test package's manifest file.
<runner_class> | The class name of the instrumented test runner you are using. | This is usually AndroidJUnitRunner.

The flags for am instrument are described in the following table:

Flag | Value | Description
-w | (none) | Forces am instrument to wait until the instrumentation terminates before terminating itself. The net effect is to keep the shell open until the tests have finished. This flag is not required, but if you do not use it, you will not see the results of your tests.
-r | (none) | Outputs results in raw format. Use this flag when you want to collect performance measurements, so that they are not formatted as test results. This flag is designed for use with the flag -e perf true (documented in the section Instrument options).
-e | <test_options> | Provides testing options as key-value pairs. The am instrument tool passes these to the specified instrumentation class via its onCreate() method. You can specify multiple occurrences of -e <test_options>. The keys and values are described in the section am instrument options. You can only use these key-value pairs with AndroidJUnitRunner or withInstrumentationTestRunner and its subclasses. Using them with any other class has no effect.

am instrument options

The am instrument tool passes testing options to AndroidJUnitRunner or InstrumentationTestRunner in the form of key-value pairs, using the -e flag, with this syntax:

-e <key> <value>

Some keys accept multiple values. You specify multiple values in a comma-separated list. For example, this invocation of AndroidJUnitRunner provides multiple values for the package key:

$ adb shell am instrument -w -e package com.android.test.package1,com.android.test.package2 \
> com.android.test/android.support.test.runner.AndroidJUnitRunner

The following table lists the key-value pairs you can use with your test runner.

Key | Value | Description
package | <Java_package_name> | The fully-qualified Java package name for one of the packages in the test application. Any test case class that uses this package name is executed. Notice that this is not an Android package name; a test package has a single Android package name but may have several Java packages within it.
class | <class_name> | The fully-qualified Java class name for one of the test case classes. Only this test case class is executed.
 | <class_name>#method name | A fully-qualified test case class name, and one of its methods. Only this method is executed. Note the hash mark (#) between the class name and the method name.
func | true | Runs all test classes that extend InstrumentationTestCase.
unit | true | Runs all test classes that do not extend either InstrumentationTestCase or PerformanceTestCase.
size | [small | medium | large] | Runs a test method annotated by size. The annotations are @SmallTest, @MediumTest, and @LargeTest.
perf | true | Runs all test classes that implement PerformanceTestCase. When you use this option, also specify the -r flag for am instrument, so that the output is kept in raw format and not re-formatted as test results.
debug | true | Runs tests in debug mode.
log | true | Loads and logs all specified tests, but does not run them. The test information appears in STDOUT. Use this to verify combinations of other filters and test specifications.
emma | true | Runs an EMMA code coverage analysis and writes the output to /data/<app_package>/coverage.ec on the device. To override the file location, use the coverageFile key that is described in the following entry. Note: This option requires an EMMA-instrumented build of the test application, which you can generate with the coverage target.
coverageFile | <filename> | Overrides the default location of the EMMA coverage file on the device. Specify this value as a path and filename in UNIX format. The default filename is described in the entry for the emma key.
-e Flag Usage Notes
  • am instrument invokes onCreate(Bundle) with a Bundle containing the key-value pairs.
  • The package key takes precedence over the class key. If you specifiy a package, and then separately specify a class within that package, Android will run all the tests in the package and ignore the class key.
  • The func key and unit key are mutually exclusive.

Usage examples

The following sections provide examples of using am instrument to run tests. They are based on the following structure:

  • The test package has the Android package name com.android.demo.app.tests
  • Two instrumented test classes:
    • Foo1 which contains the test method bar1, and
    • Foo2 which contains test methods bar2 and bar3
  • The test runner is AndroidJUnitRunner.

Running the entire test package

To run all of the test classes in the test package, enter:

$ adb shell am instrument -w com.android.demo.app.tests/android.support.test.runner.AndroidJUnitRunner

Running all tests in a test case class

To run all of the tests in the class UnitTests, enter:

$ adb shell am instrument -w  \
> -e class com.android.demo.app.tests.Foo \
> com.android.demo.app.tests/android.support.test.runner.AndroidJUnitRunner

am instrument gets the value of the -e flag, detects the class keyword, and runs all the methods in the UnitTests class.

Selecting a subset of tests

To run all of the tests in Foo1, and the bar3 method in Foo2, enter:

$ adb shell am instrument -w \
> -e class com.android.demo.app.tests.Foo1,com.android.demo.app.tests.Foo2#bar3 \
> com.android.demo.app.tests/android.support.test.runner.AndroidJUnitRunner

来源： https://developer.android.com/studio/test/command-line.html


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.

Overview

The Monkey is a command-line tool that you can run on any emulator instance or on a device. It sends a pseudo-random stream of user events into the system, which acts as a stress test on the application software you are developing.

The Monkey includes a number of options, but they break down into four primary categories:

  • Basic configuration options, such as setting the number of events to attempt.
  • Operational constraints, such as restricting the test to a single package.
  • Event types and frequencies.
  • Debugging options.

When the Monkey runs, it generates events and sends them to the system. It also watches the system under test and looks for three conditions, which it treats specially:

  • If you have constrained the Monkey to run in one or more specific packages, it watches for attempts to navigate to any other packages, and blocks them.
  • If your application crashes or receives any sort of unhandled exception, the Monkey will stop and report the error.
  • If your application generates an application not responding error, the Monkey will stop and report the error.

Depending on the verbosity level you have selected, you will also see reports on the progress of the Monkey and the events being generated.

Basic Use of the Monkey

You can launch the Monkey using a command line on your development machine or from a script. Because the Monkey runs in the emulator/device environment, you must launch it from a shell in that environment. You can do this by prefacing adb shell to each command, or by entering the shell and entering Monkey commands directly.

The basic syntax is:

$ adb shell monkey [options] <event-count>

With no options specified, the Monkey will launch in a quiet (non-verbose) mode, and will send events to any (and all) packages installed on your target. Here is a more typical command line, which will launch your application and send 500 pseudo-random events to it:

$ adb shell monkey -p your.package.name -v 500

Command Options Reference

The table below lists all options you can include on the Monkey command line.

Category | Option | Description
General | --help | Prints a simple usage guide.
 | -v | Each -v on the command line will increment the verbosity level. Level 0 (the default) provides little information beyond startup notification, test completion, and final results. Level 1 provides more details about the test as it runs, such as individual events being sent to your activities. Level 2 provides more detailed setup information such as activities selected or not selected for testing.
Events | -s <seed> | Seed value for pseudo-random number generator. If you re-run the Monkey with the same seed value, it will generate the same sequence of events.
 | --throttle <milliseconds> | Inserts a fixed delay between events. You can use this option to slow down the Monkey. If not specified, there is no delay and the events are generated as rapidly as possible.
 | --pct-touch <percent> | Adjust percentage of touch events. (Touch events are a down-up event in a single place on the screen.)
 | --pct-motion <percent> | Adjust percentage of motion events. (Motion events consist of a down event somewhere on the screen, a series of pseudo-random movements, and an up event.)
 | --pct-trackball <percent> | Adjust percentage of trackball events. (Trackball events consist of one or more random movements, sometimes followed by a click.)
 | --pct-nav <percent> | Adjust percentage of "basic" navigation events. (Navigation events consist of up/down/left/right, as input from a directional input device.)
 | --pct-majornav <percent> | Adjust percentage of "major" navigation events. (These are navigation events that will typically cause actions within your UI, such as the center button in a 5-way pad, the back key, or the menu key.)
 | --pct-syskeys <percent> | Adjust percentage of "system" key events. (These are keys that are generally reserved for use by the system, such as Home, Back, Start Call, End Call, or Volume controls.)
 | --pct-appswitch <percent> | Adjust percentage of activity launches. At random intervals, the Monkey will issue a startActivity() call, as a way of maximizing coverage of all activities within your package.
 | --pct-anyevent <percent> | Adjust percentage of other types of events. This is a catch-all for all other types of events such as keypresses, other less-used buttons on the device, and so forth.
Constraints | -p <allowed-package-name> | If you specify one or more packages this way, the Monkey will only allow the system to visit activities within those packages. If your application requires access to activities in other packages (e.g. to select a contact) you'll need to specify those packages as well. If you don't specify any packages, the Monkey will allow the system to launch activities in all packages. To specify multiple packages, use the -p option multiple times — one -p option per package.
 | -c <main-category> | If you specify one or more categories this way, the Monkey will only allow the system to visit activities that are listed with one of the specified categories. If you don't specify any categories, the Monkey will select activities listed with the category Intent.CATEGORY_LAUNCHER or Intent.CATEGORY_MONKEY. To specify multiple categories, use the -c option multiple times — one -c option per category.
Debugging | --dbg-no-events | When specified, the Monkey will perform the initial launch into a test activity, but will not generate any further events. For best results, combine with -v, one or more package constraints, and a non-zero throttle to keep the Monkey running for 30 seconds or more. This provides an environment in which you can monitor package transitions invoked by your application.
 | --hprof | If set, this option will generate profiling reports immediately before and after the Monkey event sequence. This will generate large (~5Mb) files in data/misc, so use with care. See Traceview for more information on trace files.
 | --ignore-crashes | Normally, the Monkey will stop when the application crashes or experiences any type of unhandled exception. If you specify this option, the Monkey will continue to send events to the system, until the count is completed.
 | --ignore-timeouts | Normally, the Monkey will stop when the application experiences any type of timeout error such as a "Application Not Responding" dialog. If you specify this option, the Monkey will continue to send events to the system, until the count is completed.
 | --ignore-security-exceptions | Normally, the Monkey will stop when the application experiences any type of permissions error, for example if it attempts to launch an activity that requires certain permissions. If you specify this option, the Monkey will continue to send events to the system, until the count is completed.
 | --kill-process-after-error | Normally, when the Monkey stops due to an error, the application that failed will be left running. When this option is set, it will signal the system to stop the process in which the error occurred. Note, under a normal (successful) completion, the launched process(es) are not stopped, and the device is simply left in the last state after the final event.
 | --monitor-native-crashes | Watches for and reports crashes occurring in the Android system native code. If --kill-process-after-error is set, the system will stop.
 | --wait-dbg | Stops the Monkey from executing until a debugger is attached to it.

来源： https://developer.android.com/studio/test/monkey.html


Android Monitor Overview

/

  1. Log Messages
  2. Performance Monitors
  3. Data Analysis
  4. Screen and Video Captures
  5. Get Started

Android Monitor helps you to profile the performance of your apps so you can optimize, debug, and improve them. It lets you monitor the following aspects of your apps from a hardware device or the Android Emulator:

  • Log messages, either system- or user-defined
  • Memory, CPU, and GPU usage
  • Network traffic (hardware device only)

Android Monitor provides various tools that provide real-time information about your app. It lets you capture data as your app runs and stores it in a file that you can analyze in various viewers. You can also capture screenshots and videos of your app as it runs.

Log Messages

View log messages — in real time and historically — which is useful for debugging.

logcat Monitor
Use the logcat Monitor to view system and user-defined log messages. You can filter the messages to display just the items that interest you.

Performance Monitors

Visualize the behavior and performance of your app.

Memory Monitor
Use the Memory Monitor to evaluate memory usage and find deallocated objects, locate memory leaks, and track the amount of memory the connected device is using.
CPU Monitor
Use the CPU Monitor to display CPU usage in real time and the percentage of total CPU time (including all cores) used in user and kernel mode.
GPU Monitor
Use the GPU Monitor for a visual representation of how much time it takes to render the frames of a UI window. Use this information to optimize the code that displays graphics and conserve memory.
Network Monitor
Use the Network Monitor to analyze network requests, including how and when your app transfers data. Preserve battery life by optimizing network use.

Data Analysis

Android Monitor lets you capture various types of data about your app while it's running and stores it in a file, which you can access whenever is convenient. It lists these files in the Captures window.

HPROF Viewer and Analyzer
Use the Memory Monitor to dump the Java heap to an HPROF file. The HPROF Viewer displays classes, instances of each class, and a reference tree to help you track memory usage and find memory leaks.
Allocation Tracker
Use the Memory Monitor to capture allocation data about your app. The Allocation Tracker displays each method responsible for an allocation, as well as the allocation size and number of instances.
Method Trace
Use the CPU Monitor to perform a method trace on your app. View call stack and timing information in the method trace display.
System Information
Use the System Information tool to capture dumpsys information about your app. View activity manager, package, memory usage, and graphics state information.

Screen and Video Captures

Create screen captures and videos of your app to help with marketing and debugging.

Screen Capture
Use the Screen Capture tool to take a screenshot of the display on a hardware device or the emulator. Optionally display the screenshot within a graphic of a device.
Video Capture
Use the Video tool to make a video of the display on a hardware device.

Get Started

To begin using Android Monitor, start with Android Monitor Basics.

来源： https://developer.android.com/studio/profile/android-monitor.html


Android Monitor Basics

  1. Prerequisites and Dependencies
  2. Displaying Android Monitor
  3. Profiling a Running App in Android Monitor
  4. Switching between Devices and Apps
  5. Rearranging Android Monitor Windows
  6. Terminating an App
  7. Removing an App from a Device
  8. Using Other Main Window Features

Android Monitor has a main window that contains the logcat, Memory, CPU, GPU, and Network Monitors. From this window, you can select a device and app process to work with, terminate an app, collect dumpsyssystem information, and create screenshots and videos of the running app.

Prerequisites and Dependencies

Before you start using Android Monitor, you need to set up your environment, as well as the hardware device or emulator. All of the monitors require the following:

  • If you want to run your app on a hardware device (as opposed to the emulator), connect it to the USB port. Make sure your development computer detects your device, which often happens automatically when you connect it.
  • Enable ADB integration by selecting Tools > Android > Enable ADB Integration. Enable ADB Integrationshould have a check mark next to it in the menu to indicate it's enabled.
  • Android Device Monitor can’t be running.

All but the logcat Monitor have these additional requirements:

  • Enable USB debugging in Developer Options on the device or emulator.
  • In your app, set the debuggable property to true in the manifest or build.gradle file (it’s initially set by default).

The GPU Monitor has this requirement as well:

  • For Android 5.0 (API level 21) and Android 5.1 (API level 22), in Developer Options on the device or emulator, set Profile GPU rendering to In adb shell dumpsys gfxinfo.

The Network Monitor and the Video Capture tool work with a hardware device only, not the emulator.

Displaying Android Monitor

Android Monitor is integrated into the Android Studio main window:

  • To display Android Monitor, click [image] , which by default is at the bottom of the main window.
  • To hide Android Monitor, click [image] again.
  • Or select View > Tool Windows > Android Monitor.

Note: If you don't see the sidebar buttons, you can display them by selecting View > Tool Buttons.

Android Monitor looks like the following figure:

Profiling a Running App in Android Monitor

After you've met the prerequisites and optionally connected a hardware device, you're ready to profile an app in Android Monitor:

  1. Open an app project and run the app on a device or emulator.
  2. Display Android Monitor and click the tab for the monitor you want to view.
  3. Follow the instructions about using the monitor:
    • logcat Monitor
    • Memory Monitor
    • CPU Monitor
    • GPU Monitor
    • Network Monitor

Switching between Devices and Apps

By default, Android Monitor displays data for your most recently run app. You can switch to another device and app as needed. In addition to currently running apps, you can view information about apps that are no longer running so you can continue to see any information about them that you gathered previously.

At the top of the Android Monitor main window are two menus listing devices and processes. To switch to another device, process, or both:

  1. Select the device or emulator.

    2. The Device menu lists the devices and emulators that are running or have run during your current session. There are various status messages that can appear in the Device menu:

    • DISCONNECTED - You closed an emulator or unplugged a device from the computer.
    • UNAUTHORIZED - A device needs you to accept the incoming computer connection. For example, if the connected device displays an Allow USB Debugging dialog, click OK to allow the connection.
    • OFFLINE - Android Monitor can’t communicate with a device, even though it has detected that device.
  2. Select the process.

    3. The Process menu lists the processes that are running or have run during your current session. If a process is no longer running, the menu displays a status of DEAD.

Rearranging Android Monitor Windows

You can rearrange the Android Monitor windows for optimal viewing during your tests:

  • To move a monitor up or down, click Move Monitor Up [image] or Move Monitor Down [image] .
  • To minimize or maximize a monitor, click Minimize Monitor [image] or Maximize Monitor [image] .

To rearrange the logcat and Monitors tabs:

  • To reorder the logcat or monitor group, move the tabs back and forth.
  • To move the logcat or monitor group to a standalone window, drag a tab to a different location on the screen. Or, select [image] > Floating Mode.
  • To dock a standalone window, drag it to the Android Monitor tab area.
  • To combine the logcat and monitor group displays together, drag a tab and move it onto another monitor.
  • To hide a tab, click the [image] icon. To make it reappear, click Restore Monitors View [image] or the Restore logcat View [image] on the far right of the row of tabs.

Terminating an App

To stop an app you’ve run from Android Studio:

  1. Select the device and the process in the Android Monitor menus, if needed.
  2. Click Terminate Application [image] .

    3. The process status changes to DEAD in the Processes menu. The emulator or device continues to run, but the app closes. Any running monitors in Android Monitor stop.

Removing an App from a Device

To remove an app from a device you use for development, use the normal uninstall procedure on the device.

If you run a new version of an app from Android Studio that’s been already installed on a hardware device, the device displays an Application Installation Failed dialog. Click OK to install the new version of the app.

Using Other Main Window Features

From the Android Monitor main window, you can also do the following:

  • Examine dumpsys system information.
  • Take a screen capture of the device.
  • Record a video from the screen.
    来源： https://developer.android.com/studio/profile/am-basics.html


Perfect GPU Use

You can use the following tools to help optimize the GPU performance of your app:

  • The GPU Monitor gives you a quick visual representation of how much time it takes to render the frames of a UI window. It profiles the amount of time it takes for the render thread to prepare, process, and execute the draw commands.
  • The Debug GPU Overdraw tool helps you visualize overdraw on your mobile device by color-coding interface elements based on how often they are drawn underneath.
  • The Profile GPU Rendering tool gives you a quick visual representation of how much time it takes to render the frames of a UI window relative to the 16-ms-per-frame benchmark..

    来源： https://developer.android.com/studio/profile/gpu.html


Analyze GPU Use with the GPU Monitor

GPU Monitor

  1. Displaying a Running App in the GPU Monitor

Android Monitor includes a GPU Monitor that gives you a quick visual representation of how much time it takes to render the frames of a UI window. It profiles the amount of time it takes for the render thread to prepare, process, and execute the draw commands. The GPU Monitor can help you to:

  • Quickly see how a UI window performs.
  • Identify whether any part of the rendering pipeline stands out in using processing time.
  • Look for spikes in frame rendering time associated with user or program actions.

For example, if displaying a static photo continues to take Graphics Processor Unit (GPU) resources long after it has finished drawing on the screen, that’s a likely candidate for optimization.

Displaying a Running App in the GPU Monitor

To display an app running on a particular device or emulator in the GPU Monitor:

  1. Meet the prerequisites and dependencies.
  2. Open an app project.
  3. Run the app on a hardware device or emulator.
  4. Display Android Monitor.
  5. Click the Monitors tab and display the GPU Monitor.
  6. Enable the GPU Monitor by clicking Pause [image] to deselect it.

    7. Any GPU usage begins to appear in the GPU Monitor:

    The y-axis is the amount of time it takes the GPU to execute, process, prepare, and draw frames, in milliseconds. The x-axis records the time elapsed; it starts with seconds, and then minutes and seconds, and so on. The green line indicates 60 frames per second (FPS), and the red line represents 30 FPS.

  7. To stop the GPU Monitor, click Pause [image] again to select it.

    来源： https://developer.android.com/studio/profile/am-gpu.html


Visualize GPU Overdraw

Debug GPU Overdraw Walkthrough

  • Prerequisites
  • Visualizing Overdraw

You should also read

  • Profile GPU Rendering Walkthrough
  • Hierarchy Viewer Walkthrough

This walkthrough shows how to visualize overdraw on your mobile device by color-coding interface elements based on how often they are drawn underneath.

What it's good for:

  • Showing where an app might be doing more rendering work than necessary.
  • Helping you see where you might be able to reduce rendering overhead.

Prerequisites

  • A mobile device with Developer Options enabled.

Visualizing Overdraw on Your Mobile Device

    • Figure 1. Steps for turning on Debug GPU Overdraw.

    1. On your mobile device, go to Settings and tap Developer Options.
    2. In the Hardware accelerated rendering section, select Debug GPU Overdraw.
    3. In the Debug GPU overdraw popup, select Show overdraw areas.

    • Figure 2. Example of
      Debug GPU Overdraw output.

    5. Don't panic as your screen turns into a delirium of colors. The coloring is provided to help you diagnose your app's display behavior.

    • Figure 3. Color key for Debug GPU Overdraw output.

    6. The colors are hinting at the amount of overdraw on your screen for each pixel, as follows:
      • True color: No overdraw
      • Blue: Overdrawn once
      • Green: Overdrawn twice
      • Pink: Overdrawn three times
      • Red: Overdrawn four or more times

    • Figure 4. Examples of undesirable and desirable
      Debug GPU Overdraw output.

      来源： https://developer.android.com/studio/profile/dev-options-overdraw.html


Profile GPU Rendering

Profiling GPU Rendering Walkthrough

  • Prerequisites
  • Profile GPU Rendering

You should also read

  • Debug GPU Overdraw Walkthrough
  • Hierarchy Viewer Walkthrough

This walkthrough shows how to use Profile GPU Rendering on your mobile device.

Profile GPU Rendering gives you a quick visual representation of how much time it takes to render the frames of a UI window relative to the 16-ms-per-frame benchmark.

What it's good for:

  • Quickly seeing how a UI window performs against the 16-ms-per-frame target.
  • Identifying whether any part of the rendering pipeline stands out in using processing time.
  • Looking for spikes in frame rendering time associated with user or program actions.

Prerequisites

  • A mobile device running at least Android 4.1 with Developer Options enabled.

Working with Profile GPU Rendering

    • Figure 1. Turning on Profile GPU Rendering.

    1. On your mobile device, go to Settings > Developer Options.
    2. In the Monitoring section, select Profile GPU Rendering.
    3. In the Profile GPU Rendering popup, choose On screen as bars to overlay the graphs on the screen of your mobile device.
    4. Go to the app that you want to profile.

  • Figure 2. Screen when Profile GPU Rendering is on.

    What you see:

    • For each visible application, the tool displays a graph.
    • The horizontal axis shows time elapsing, and the vertical axis time per frame in milliseconds.
    • As you interact with your application, vertical bars show up on your screen, appearing from left to right, graphing frame performance over time.
    • Each vertical bar represents one frame of rendering. The taller the bar, the longer it took to render.
    • The green line marks the 16 millisecond target. Every time a frame crosses the green line, your app is missing a frame, and your users may see this as stuttering images.

  • The Profile GPU Rendering Graph

    Figure 3. Enlarged Annotated Profile GPU Rendering graph.

    In this enlarged image of the Profile GPU Rending graph you can see the colored sections of the graph, and what phase of the rendering pipeline each color represents.

    • The green line represents 16 milliseconds. To achieve 60 frames per second, the vertical bar for each frame needs to stay below this 16 ms mark. Any time a bar pushes above this line, there may be pauses in the animations.
    • Each bar has a blue, purple (only for Android version 4.0 and higher), red, and orange component.

    • The blue section of the bar represents the time used to create and update the View's display lists. If this part of the bar is tall, there may be a lot of custom view drawing, or a lot of work in onDraw methods.
    • Android 4.0 and higher: The purple section of the bar represents the time spent transferring resources to the render thread.
    • The red section of the bar represents the time spent by Android's 2D renderer issuing commands to OpenGL to draw and redraw display lists. The height of this bar is directly proportional to the sum of the time it takes each display list to execute—more display lists equals a taller red bar.
    • The orange section of the bar represents the time the CPU is waiting for the GPU to finish its work. If this bar gets tall, it means the app is doing too much work on the GPU.

    Note: While this tool is named Profile GPU Rendering, all monitored processes actually occur in the CPU. Rendering happens by submitting commands to the GPU, and the GPU renders the screen asynchronously. In certain situations, the GPU can have too much work to do, and your CPU will have to wait before it can submit new commands. When this happens, you'll see spikes in the Process (orange bar) and Execute (red bar) stages, and the command submission will block until more room is made on the GPU command queue.

    来源： https://developer.android.com/studio/profile/dev-options-rendering.html


Batterystats and Battery Historian Walkthrough

You should also read

  • Battery Historian Charts
  • Systrace Walkthrough

This walkthrough shows the basic usage and workflow for the Batterystats tool and the Battery Historian script.

Batterystats collects battery data from your device, and Battery Historian converts that data into an HTML visualization that you can view in your Browser. Batterystats is part of the Android framework, and Battery Historian is open-sourced and available on GitHub at https://github.com/google/battery-historian.

What it's good for:

  • Showing you where and how processes are drawing current from the battery.
  • Identifying tasks in your app that could be deferred or even removed to improve battery life.

Prerequisites

  • A mobile device with Developer Options enabled running Android 5.0 or higher.

Working with Batterystats & Battery Historian

Summary

https://github.com/google/battery-historian

> adb kill-server

> adb devices

> adb shell dumpsys batterystats --reset

<disconnect and play with app>...<reconnect>

> adb devices

>adb shell dumpsys batterystats > batterystats.txt

> python historian.py batterystats.txt > batterystats.html

  1. Download the open-source Battery Historion Python script from GitHub (https://github.com/google/battery-historian).
  2. Unzip the file to extract the Battery Historian folder. Inside the folder, find thehistorian.py file and move it to the Desktop or another writable directory.
  3. Connect your mobile device to your computer.
  4. On your computer, open a Terminal window.
  5. Change to the directory where you've saved historian.py,
    for example: cd ~/Desktop
  6. Shut down your running adb server.
    > adb kill-server
  7. Restart adb and check for connected devices.
    > adb devices

    If you don't see any devices, make sure your phone is connected, and USB Debugging is turned on, and then kill and restart adb.
  8. Reset battery data gathering.
    > adb shell dumpsys batterystats --reset

    Resetting erases old battery collection data; otherewise, the output will be huge.

  9. Disconnect your device from your computer so that you are only drawing current from the device's battery.
  10. Play with your app for a short time.
  11. Reconnect your phone.
  12. Make sure your phone is recognized: > adb devices
  13. Dump all battery data. This can take a while:
    > adb shell dumpsys batterystats > batterystats.txt
  14. Create a HTML version of the data dump for Battery Historian:
    > python historian.py batterystats.txt > batterystats.html
  15. Open the batterystats.htm file in your browser.
  16. Continue with Battery Historian Charts.
    17. Figure 1. Battery Historian output.

    来源：
    https://developer.android.com/studio/profile/battery-historian.html


Understand Historian Charts

Battery Historian Charts

  • Battery Historian Charts
  • Filtering batterystats output

You should also read

  • Batterystats & Battery Historian Walkthrough
  • Systrace Walkthrough

The Battery Historian chart graphs power-relevant events over time.

Each row shows a colored bar segment when a system component is active and thus drawing current from the battery. The chart does not show how much battery was used by the component, only that the app was active. Charts are organized by category.

Figure 1. Example of Battery Historian output.

Battery usage categories

  • battery_level: When the battery level was recorded and logged. Reported in percent, where 093 is 93%. Provides an overall measure of how fast the battery is draining.
  • top: The application running at the top; usually, the application that is visible to the user. If you want to measure battery drain while your app is active, make sure it's the top app. If you want to measure battery drain while your app is in the background, make sure it's notthe top app.
  • wifi_running: Shows that the Wi-Fi network connection was active.
  • screen: Screen is turned on.
  • phone_in_call: Recorded when the phone is in a call.
  • wake_lock: App wakes up, grabs a lock, does small work, then goes back to sleep. This is one of the most important pieces of information. Waking up the phone is expensive, so if you see lots of short bars here, that might be a problem.
  • running: Shows when the CPU is awake. Check whether it is awake and asleep when you expect it to be.
  • wake_reason: The last thing that caused the kernel to wake up. If it's your app, determine whether it was necessary.
  • mobile_radio: Shows when the radio was on. Starting the radio is battery expensive. Many narrow bars close to each other can indicate opportunities for batching and other optimizations.
  • gps: Indicates when the GPS was on. Make sure this is what you expect.
  • sync: Shows when an app was syncing with a backend. The sync bar also shows which app did the syncing. For users, this can show apps where they might turn syncing off to save battery. Developers should sync as little as possible and only as often as necessary.

Note: Not every chart will show every category.

Filtering batterystats output

You can gather additional information from the batterystats.txt file where you saved the output from the batterystats command.

Figure 2.Example of filtered batterystats output.

Open the file in a text editor and search for:

  1. Battery History: A time series of power-relevant events, such as screen, Wi-Fi, and app launch. These are also visible through Battery Historian.
  2. Per-PID Stats: How long each process ran.
  3. Statistics since last charge: System-wide statistics, such as cell signal levels and screen brightness. Provides an overall picture of what's happening with the device. This information is especially useful to make sure no external events are affecting your experiment.
  4. Estimated power use (mAh) by UID and peripheral: This is currently an extremely rough estimate and should not be considered experiment data.
  5. Per-app mobile ms per packet: Radio-awake-time divided by packets sent. An efficient app will transfer all its traffic in batches, so the lower this number the better.
  6. All partial wake locks: All app-held wakelocks, by aggregate duration and count.
    来源： https://developer.android.com/studio/profile/battery-historian-charts.html


Profiling with Traceview and dmtracedump

  1. Traceview Layout
    1. Timeline Panel
    2. Profile Panel
  2. Creating Trace Files
  3. Copying Trace Files to a Host Machine
  4. Viewing Trace Files in Traceview
  5. Using dmtracedump
  6. Traceview Known Issues

Traceview is a graphical viewer for execution logs that you create by using the Debug class to log tracing information in your code. Traceview can help you debug your application and profile its performance.

Traceview Layout

When you have a trace log file (generated by adding tracing code to your application or by DDMS), you can load the log files in Traceview, which displays the log data in two panels:

  • A timeline panel -- describes when each thread and method started and stopped
  • A profile panel -- provides a summary of what happened inside a method

The sections below provide addition information about the traceview output panes.

Timeline Panel

Figure 1 shows a close up of the timeline panel. Each thread’s execution is shown in its own row, with time increasing to the right. Each method is shown in another color (colors are reused in a round-robin fashion starting with the methods that have the most inclusive time). The thin lines underneath the first row show the extent (entry to exit) of all the calls to the selected method.

Figure 1. The Traceview Timeline Panel

Profile Panel

Figure 2 shows the profile pane, a summary of all the time spent in a method. The table shows both the inclusive and exclusive times (as well as the percentage of the total time). Exclusive time is the time spent in the method. Inclusive time is the time spent in the method plus the time spent in any called functions. We refer to calling methods as "parents" and called methods as "children." When a method is selected (by clicking on it), it expands to show the parents and children. Parents are shown with a purple background and children with a yellow background. The last column in the table shows the number of calls to this method plus the number of recursive calls. The last column shows the number of calls out of the total number of calls made to that method. In this view, we can see that there were 14 calls to LoadListener.nativeFinished(); looking at the timeline panel shows that one of those calls took an unusually long time.

Figure 2. The Traceview Profile Panel

Creating Trace Files

To use Traceview, you need to generate log files containing the trace information you want to analyze.

There are two ways to generate trace logs:

  • Include the Debug class in your code and call its methods such as startMethodTracing() and stopMethodTracing(), to start and stop logging of trace information to disk. This option is very precise because you can specify exactly where to start and stop logging trace data in your code.
  • Use the method profiling feature of DDMS to generate trace logs. This option is less precise because you do not modify code, but rather specify when to start and stop logging with DDMS. Although you have less control on exactly where logging starts and stops, this option is useful if you don't have access to the application's code, or if you do not need precise log timing.

Before you start generating trace logs, be aware of the following restrictions:

  • If you are using the Debug class, your application must have permission to write to external storage (WRITE_EXTERNAL_STORAGE).
  • If you are using DDMS:
    • Android 2.1 and earlier devices must have an SD card present and your application must have permission to write to the SD card.
    • Android 2.2 and later devices do not need an SD card. The trace log files are streamed directly to your development machine.

This document focuses on using the Debug class to generate trace data. For more information on using DDMS to generate trace data, see Using the Dalvik Debug Monitor Server.

To create the trace files, include the Debug class and call one of the startMethodTracing() methods. In the call, you specify a base name for the trace files that the system generates. To stop tracing, call stopMethodTracing(). These methods start and stop method tracing across the entire virtual machine. For example, you could call startMethodTracing() in your activity's onCreate() method, and call stopMethodTracing() in that activity's onDestroy()method.

    // start tracing to "/sdcard/calc.trace"
    Debug.startMethodTracing("calc");
    // ...
    // stop tracing
    Debug.stopMethodTracing();

When your application calls startMethodTracing(), the system creates a file called <trace-base-name>.trace. This contains the binary method trace data and a mapping table with thread and method names.

The system then begins buffering the generated trace data, until your application calls stopMethodTracing(), at which time it writes the buffered data to the output file. If the system reaches the maximum buffer size before you call stopMethodTracing(), the system stops tracing and sends a notification to the console.

Interpreted code runs more slowly when profiling is enabled. Don't try to generate absolute timings from the profiler results (such as, "function X takes 2.5 seconds to run"). The times are only useful in relation to other profile output, so you can see if changes have made the code faster or slower relative to a previous profiling run.

In Android 4.4 and later, you can use sample-based profiling to profile with less runtime performance impact. To enable sample profiling, callstartMethodTracingSampling() with a specified sampling interval. The system will then gather samples periodically until tracing is stopped viastopMethodTracing().

Copying Trace Files to a Host Machine

After your application has run and the system has created your trace files <trace-base-name>.trace on a device or emulator, you must copy those files to your development computer. You can use adb pull to copy the files. Here's an example that shows how to copy an example file, calc.trace, from the default location on the emulator to the /tmp directory on the emulator host machine:

adb pull /sdcard/calc.trace /tmp

Viewing Trace Files in Traceview

To run Traceview and view the trace files:

  1. Start the Android Device Monitor.
  2. In the Android Device Monitor tool bar, click DDMS and select a process.
  3. Click the Start Method Profiling icon to start method profiling.
  4. After the profiling is complete, click the Stop Method Profiling icon to display the traceview.

Note: If you are trying to view the trace logs of an application that is built with ProGuard enabled (release mode build), some method and member names might be obfuscated. You can use the Proguard mapping.txt file to figure out the original unobfuscated names. For more information on this file, see the Proguard documentation.

Note: Running traceview from the command line has been deprecated.

Using dmtracedump

dmtracedump is a tool that gives you an alternate way of generating graphical call-stack diagrams from trace log files. The tool uses the Graphviz Dot utility to create the graphical output, so you need to install Graphviz before running dmtracedump.

The dmtracedump tool generates the call stack data as a tree diagram, with each call represented as a node. It shows call flow (from parent node to child nodes) using arrows. The diagram below shows an example of dmtracedump output.

Figure 3. Screenshot of dmtracedump

For each node, dmtracedump shows <ref> callname (<inc-ms>, <exc-ms>,<numcalls>), where

  • <ref> -- Call reference number, as used in trace logs
  • <inc-ms> -- Inclusive elapsed time (milliseconds spent in method, including all child methods)
  • <exc-ms> -- Exclusive elapsed time (milliseconds spent in method, not including any child methods)
  • <numcalls> -- Number of calls

The usage for dmtracedump is:

dmtracedump [-ho] [-s sortable] [-d trace-base-name] [-g outfile] <trace-base-name>

The tool then loads trace log data from <trace-base-name>.data and <trace-base-name>.key. The table below lists the options for dmtracedump.

Option | Description
-d <trace-base-name> | Diff with this trace name
-g <outfile> | Generate output to <outfile>
-h | Turn on HTML output
-o | Dump the trace file instead of profiling
-d <trace-base-name> | URL base to the location of the sortable javascript file
-t <percent> | Minimum threshold for including child nodes in the graph (child's inclusive time as a percentage of parent inclusive time). If this option is not used, the default threshold is 20%.

Traceview Known Issues

Threads
Traceview logging does not handle threads well, resulting in these two problems:
  1. If a thread exits during profiling, the thread name is not emitted (fixed in Android 5.1 and later);
  2. The VM reuses thread IDs. If a thread stops and another starts, they may get the same ID.
    来源： https://developer.android.com/studio/profile/traceview.html


Traceview Walkthrough

page.title=Traceview Walkthrough meta.tags="android, performance, profiling, tools, compute, traceview" page.tags="android", "performance", "profiling", "tools", "compute", "traceview" page.metaDescription=Log method execution over time and inspect execution data, per-thread timelines, and call stacks to track down performance issues in your source code. page.image=tools/performance/thumbnails/tools_traceview.png page.article=true @jd:body

In this document

  • Prerequisites
  • Working with Traceview

You should also read

  • Heap Viewer Walkthrough
  • Systrace Walkthrough

This walkthrough shows the basic usage and workflow for the Traceview tool. Traceview logs method execution over time and shows execution data, per-thread timelines, and call stacks.

What it's good for:

  • Tracking down performance problems in your source code.

Prerequisites

  • A mobile device with Developer Options enabled.
  • Application code. Use your own code, or the Sunshine sample app from the Android Fundamentals Udacity course.

Working with Traceview

    • Figure 1. Steps for starting Android Device Monitor.

    1. Connect your mobile device to your computer.
    2. Open your application in Android Studio, build the source, and run it on your device.
    3. Start the Android Device Monitor from Android Studio: Tools -> Android -> Android Device Monitor.

    • Figure 2. Steps for starting Traceview.

    4. Make sure your device and the package for your application are showing in the Devices (DDMS mode) or Windows (Hierarchy Viewer mode) tab.

      If necessary choose Window > Reset Perspective to get back to the default pane arrangement.

    5. Click the DDMS button, because Traceview is one of the DDMS tools.
    6. Select the app you want to profile.

    • Figure 3. Starting profiling.

    7. Click the Start method profiling [image] button.

    • Figure 4. Choosing profiling options.

    8. In the Profiling Options popup:
      • Choose Sample based profiling
      • Keep the default sampling rate of 1000 microseconds.
      • Click OK.

    • Figure 5. Stopping profiling.

    9. Interact with your application. If you are aware of performance issues that your users experience, perform those actions.
    10. Click the Stop method profiling [image] button.
    11. Wait for the trace to load. This may take a few seconds if you recorded for a long time.

    • Figure 6. Traceview output panes.

    12. Traceview has two panels: Timeline pane and Profile pane, which are described below.
    13. Use the Find box at the bottom to filter your profile results. For example, if you are interested in finding the running time for a function, you can search for it, and the tool will highlight it in the timeline.

    • Figure 7. Annotated timeline panel.

    14. The Timeline pane visualizes how your code executes over time.
      • Each row shows a thread.
      • Each bar on the timeline is a method executing.
      • Each color is for a different method; every time a method executes, you see a the same color bar.
      • The width of its bar indicates how long the method takes to execute.
    15. When you are zoomed out, a bar indicates when a method is executing.

    • Figure 8. Segment for method on the timeline.

    16. Zoom into the graph, and the bar for each method expands into a colored U-shape, where the left side of the U indicates the start, and the right side the end of the method's execution.

    • Figure 9. Traceview Profiling pane with callstack.

    17. The Profiling pane shows a list of methods.
      • Select a method to see who called it (Parent) and who it's calling (Children).
      • The selected method is also highlighted in the Timeline pane.
      • The columns show exclusive and inclusive CPU and real times, percentages, ratios, and how often a method was called.
      • The exclusive time is the time spent just in the method itself, which can help you find issues within that specific method.
      • The inclusive time is for the method and all methods it calls, which can help you find problems with your call tree.
      • The Calls+Rec column shows how many times a method was called recursively, which can help you track down performance issues.
        来源： https://developer.android.com/studio/profile/traceview-walkthru.html


Analyzing UI Performance with Systrace

  1. Overview
  2. Generating a Trace
  3. Analyzing a Trace
    1. Inspecting Frames
    2. Investigating Alerts
  4. Tracing Application Code

See also

  1. Systrace

While developing your application, you should check that user interactions are buttery smooth, running at a consistent 60 frames per second. If something goes wrong, and a frame gets dropped, the first step in fixing the problem is understanding what the system is doing.

The Systrace tool allows you to collect and inspect timing information across an entire Android device, which is called a trace. It shows where time and CPU cycles are being spent, displaying what each thread and process is doing at any given time. It also inpects the captured tracing information to highlight problems that it observes, from list item recycling to rendering content, and provide recommendations about how to fix them. This document explains how to navigate the trace files produced by the tool, and use them to analyze the performance of an application's user interface (UI).

Overview

Systrace helps you analyze how the execution of your application fits into the many running systems on an Android device. It puts together system and application thread execution on a common timeline. In order to analyze your app with Systrace, you first collect a trace log of your app, and the system activity. The generated trace allows you to view highly detailed, interactive reports showing everything happening in the system for the traced duration.

Figure 1. An example Systrace, showing 5 seconds of scrolling an app when it is not performing well.

Figure 1. shows a trace captured while scrolling an app that is not rendering smoothly. By default, a zoomed out view of the traced duration is shown. The horizontal axis is time, and trace events are grouped by process, and then by thread on the vertical axis.

The groupings are in the order Kernel, SurfaceFlinger (the android compositor process), followed by apps, each labeled by package name. Each app process contains all of the tracing signals from each thread it contains, including a hierarchy of high level tracing events based on the enabled tracing categories.

Generating a Trace

In order to create a trace of your application, you must perform a few setup steps. First, you must have a device running Android 4.1 (API 16) or higher. Set up the device for debugging, connect it to your development system, and install your application. Some types of trace information, specifically disk activity and kernel work queues, require that you have root access to the device. However, most Systrace log data only requires that the device be enabled for developer debugging.

Systrace traces can be run either from a command line or from a graphical user interface. This guide focuses on using the command line options.

Tracing on Android 4.3 and higher

To run a trace on Android 4.3 and higher devices:

  1. Make sure the device is connected through a USB cable and is enabled for debugging.
  2. Run the trace with the options you want, for example:
    $ cd android-sdk/platform-tools/systrace
    $ python systrace    .py --time=10 -o mynewtrace.html sched gfx view wm
  3. On the device, execute any user actions you want be included in the trace.

For more information on the available options for running Systrace, see the Systrace help page.

Tracing on Android 4.2 and lower

To use Systrace effectively with devices running Android 4.2 and lower, you must configure the types of processes you want to trace before running a trace. The tool can gather the following types of process information:

  • General system processes such as graphics, audio and input processes (selected using trace category tags).
  • Low level system information such as CPU, kernel and disk activity (selected using options).

To set trace tags for Systrace using the command-line:

  1. Use the --set-tags option:
    $ cd android-sdk/platform-tools/systrace
    $ python systrace    .py --set-tags=gfx,view,wm
  2. Stop and restart the adb shell to enable tracing of these processes.
    $ adb shell stop
    $ adb shell start

To set trace tags for Systrace using the device user interface:

  1. On the device connected for tracing, navigate to: Settings > Developer options > Monitoring > Enable traces.
  2. Select the categories of processes to be traced and click OK.

Note: The adb shell does not have to be stopped and restarted when selecting trace tags using this method.

After you have configured the category tags for your trace, you can start collecting information for analysis.

To run a trace using the current trace tag settings:

  1. Make sure the device is connected through a USB cable and is enabled for debugging.
  2. Run the trace with the low-level system trace options and limits you want, for example:
    $ python systrace.py --cpu-freq --cpu-load --time=10 -o mytracefile.html
  3. On the device, execute any user actions you want be included in the trace.

For more information on the available options for running Systrace, see the Systrace help page.

Analyzing a Trace

After you have generated a trace, open the output html file using a web browser. This section explains how to analyze and interpret the information that the tool produces to find and fix UI performance problems.

Inspecting Frames

Each app that is rendering frames shows a row of frame circles, which are typically colored green. Circles that are colored yellow or red, exceeding the 16.6 millisecond run time limit required to maintain a stable 60 frames per second. Zoom in using the 'w' key to see the frames of your application, and look for long-running frames getting in the way of smoothness.

Note: Hit the '?' key, or the button in the top right for help navigating the trace.

Figure 2. Systrace display after zooming in on a long-running frame.

Clicking on one such frame highlights it, focusing only on the work done by the system for that frame. On devices running Android 5.0 (API level 21) or higher, this work is split between the UI Thread and RenderThread. On prior versions, all work in creating a frame is done on the UI Thread.

Click on individual components of the frame to see how long they took to run. Some events, such as performTraversals, describe what the system is doing in that method when you select it. Selecting a frame displays any alerts present in that frame.

Investigating Alerts

Systrace does automatic analysis of the events in the trace, and highlights many performance problems as alerts, suggesting what to do next.

Figure 3. Selecting the problematic frame, an alert is shown identifying a problem.

After you select a slow frame such as the one shown in Figure 3, an alert may be displayed. In the case above, it calls out that the primary problem with the frame is too much work being done inside ListView recycling and rebinding. There are links to the relevant events in the trace, which can be followed to explain more about what the system is doing during this time.

If you see too much work being done on the UI thread, as in this case with this ListView work, you can use Traceview, the app code profiling tool, to investigate exactly what is taking so much time.

Note that you can also find about every alert in the trace by clicking the Alerts tab to the far right of the window. Doing so expands the Alerts panel, where you can see every alert that the tool discovered in your trace, along with an occurrence count.

Figure 4. Clicking the Alert button to the right reveals the alert tab.

The Alerts panel helps you see which problems occur in the trace, and how often they contribute to jank. Think of the alerts panel as a list of bugs to be fixed, often a tiny change or improvement in one area can eliminate an entire class of alerts from your application!

Tracing Application Code

The tracing signals defined by the framework do not have visibility into everything your application is doing, so you may want to add your own. In Android 4.3 (API level 18) and higher, you can use the methods of the Trace class to add signals to your code. This technique can help you see what work your application's threads are doing at any given time. Tracing begin and end events do add overhead while a trace is being captured, a few microseconds each, but sprinkling in a few per frame, or per worker thread task can go a long way to adding context to a trace of your app.

The following code example shows how to use the Trace class to track execution of an application method, including two nested code blocks within that method.

public void ProcessPeople() {
    Trace.beginSection("ProcessPeople");
    try {
        Trace.beginSection("Processing Jane");
        try {
            // code for Jane task...
        } finally {
            Trace.endSection(); // ends "Processing Jane"
        }

        Trace.beginSection("Processing John");
        try {
            // code for John task...
        } finally {
            Trace.endSection(); // ends "Processing John"
        }
    } finally {
        Trace.endSection(); // ends "ProcessPeople"
    }
}

Note: When you nest trace calls within each other, the endSection() method ends the most recently called beginSection(String) method. This means that a trace started within another trace cannot extend beyond the end of the enclosing trace, so make sure your beginning and ending method calls are properly matched to measure your applications processing.

Note: Traces must begin and end on the same thread. Do not call beginSection(String) on one thread of execution and then attempt to end the trace with a call to endSection() on another thread.

When using application-level tracing with Systrace, you must specify the package name of your application in the user interface or specify the -a or --app= options on the command line. For more information, see the Systrace usage guide.

You should enable app level tracing when profiling your app, even if you have not added signals yourself. Library code can include very useful tracing signals when you enable application-level tracing. The RecyclerView class is a great example of this, providing information about several important stages of work it executes.

来源： https://developer.android.com/studio/profile/systrace.html


Walk through Systrace

Systrace Walkthrough

  • Prerequisites
  • Working with Systrace

You should also read

  • Traceview Walkthrough
  • Allocation Tracker Walkthrough

This walkthrough shows the basic usage and workflow for the Systrace tool in the Android Device Monitor.

Systrace collects system and application process execution data and generates detailed, interactive reports from devices running Android 4.1 and higher.

What it's good for:

  • Evaluating container performance.
  • Finding performance bottlenecks in the execution of your code.

Prerequisites

  • Android SDK Tools 20.
  • Python installed and included in your development computer's execution path.
  • A mobile device running at least Android 4.1 with Developer Options and USB Debugging enabled in Developer Options.
  • Application code. Use your own code, or the Sunshine sample app from the Android Fundamentals Udacity course.

Working with Systrace

    • Figure 1. Starting Android Device Monitor.

    1. Connect your mobile device to your computer.
    2. Open your application in Android Studio, build the source, and run it on your device.
    3. From Android Studio, start the Android Device Monitor: Tools -> Android -> Android Device Monitor.

    • Figure 2. Steps for starting Systrace.

    4. Make sure your device and the package for your application are showing in the Devices (DDMS mode) or Windows (Hierarchy Viewer mode) tab.

      You can choose Window > Reset Perspective to get back to the default arrangement.

    5. Click the DDMS button, because Systrace is one of the DDMS tools.
    6. Click the Systrace button [image] .

    • Figure 3. Steps for creating a trace.

    7. In the Android System Trace popup, choose your settings for the trace.
      • Destination File: Where the trace is stored as an HTML file. Default is in your home directory as trace.html.
      • Trace Duration: Default is 5 seconds, and 30 seconds is a good time to choose.
      • Trace Buffer size: Default is unlimited.
      • Enable Application Traces from: Make sure your app is selected.
      • Select tags to enable: Choose at least one value to trace, for example Graphics and View System.
    8. Click OK to start tracing.
    9. Interact with your app.

    • Figure 4. Example systrace output in browser.

    10. When the trace is done, you are automatically returned to Android Device Monitor.
    11. Go to your home directory, or the directory you chose as the file destination.
    12. Open the trace.html file in your browser.

来源： https://developer.android.com/studio/profile/systrace-walkthru.html


Systrace Command Reference

Systrace

The Systrace tool helps analyze the performance of your application by capturing and displaying execution times of your applications processes and other Android system processes. The tool combines data from the Android kernel such as the CPU scheduler, disk activity, and application threads to generate an HTML report that shows an overall picture of an Android device’s system processes for a given period of time.

The Systrace tool is particularly useful in diagnosing display problems where an application is slow to draw or stutters while displaying motion or animation. For more information on how to use Systrace, see Analyzing UI Performance with Systrace.

Requirements

In order to run Systrace, you must have Android SDK Tools 20 or later installed. You must also have Python installed and included in your development computer's execution path. In order to generate a trace, you must connect a device running Android 4.1 (API Level 16) or higher to your development system using a USB debugging connection.

The Systrace tool can be run either from one of the Android SDK's graphical user interface tools, or from the command line. The following sections describe how to run the tool using either of these methods.

User Interface

The Systrace tool can be run from the Android Device Monitor.

To run the Systrace capture user interface:

Using Android Studio

Using Device Monitor

Command Line Usage

The Systrace tool has different command line options for devices running Android 4.3 (API level 18) and higher versus devices running Android 4.2 (API level 17) and lower. The following sections describe the different command line options for each version.

The general syntax for running Systrace from the command line is as follows.

$ python systrace.py [options] [category1] [category2] ... [categoryN]

See the sections below for example Systrace sessions.

Android 4.3 and higher options

When you use Systrace on devices running Android 4.3 and higher, you can omit trace category tags to get the defaults, or you may manually specify tags for inclusion. Here is an example execution run that sets trace tags and generates a trace from a connected device.

$ cd android-sdk/platform-tools/systrace
$ python systrace.py --time=10 -o mynewtrace.html sched gfx view wm

Tip: If you want to see the names of tasks in the trace output, you must include the sched category in your command parameters.

The table below lists the Systrace command line options for devices running Android 4.3 (API level 18) and higher.

Option | Description
-h, --help | Show the help message.
-o <FILE> | Write the HTML trace report to the specified file.
-t N, --time=N | Trace activity for N seconds. The default value is 5 seconds.
-b N, --buf-size=N | Use a trace buffer size of N kilobytes. This option lets you limit the total size of the data collected during a trace.
-k <KFUNCS>
--ktrace=<KFUNCS> 		Trace the activity of specific kernel functions, specified in a comma-separated list.
-l, --list-categories List the available tracing category tags. The available tags are:
  • gfx - Graphics
  • input - Input
  • view - View
  • webview - WebView
  • wm - Window Manager
  • am - Activity Manager
  • audio - Audio
  • video - Video
  • camera - Camera
  • hal - Hardware Modules
  • res - Resource Loading
  • dalvik - Dalvik VM
  • rs - RenderScript
  • sched - CPU Scheduling
  • freq - CPU Frequency
  • membus - Memory Bus Utilization
  • idle - CPU Idle
  • disk - Disk input and output
  • load - CPU Load
  • sync - Synchronization Manager
  • workq - Kernel Workqueues

Note: Some trace categories are not supported on all devices.

Tip: If you want to see the names of tasks in the trace output, you must include the sched category in your command parameters.

-a <APP_NAME>
--app=<APP_NAME> 		Enable tracing for applications, specified as a comma-separated list of package names. The apps must contain tracing instrumentation calls from the Trace class. For more information, see Analyzing UI Performance with Systrace.
--from-file=<FROM_FILE> | Create the interactive Systrace report from a file, instead of running a live trace.
-e <DEVICE_SERIAL>
--serial=<DEVICE_SERIAL> 		Conduct the trace on a specific connected device, identified by its device serial number.

Android 4.2 and lower options

Using Systrace on the command line with devices running Android 4.2 and lower is typically a two-step process. You must first set the trace tags you want to capture and then run the trace. Here is an example execution run that sets trace tags and generates a trace from a connected device.

$ cd android-sdk/platform-tools/systrace
$ python systrace.py --set-tags gfx,view,wm
$ adb shell stop
$ adb shell start
$ python systrace.py --disk --time=10 -o mynewtrace.html

The table below lists the Systrace command line options for devices running Android 4.2 (API level 17) and lower.

Option | Description
-h, --help | Show the help message.
-o <FILE> | Write the HTML trace report to the specified file.
-t N, --time=N | Trace activity for N seconds. The default value is 5 seconds.
-b N, --buf-size=N | Use a trace buffer size of N kilobytes. This option lets you limit the total size of the data collected during a trace.
-d, --disk | Trace disk input and output activity. This option requires root access on the device.
-f, --cpu-freq | Trace CPU frequency changes. Only changes to the CPU frequency are logged, so the initial frequency of the CPU when tracing starts is not shown.
-i, --cpu-idle | Trace CPU idle events.
-l, --cpu-load | Trace CPU load. This value is a percentage determined by the interactive CPU frequency governor.
-s, --no-cpu-sched | Prevent tracing of the CPU scheduler. This option allows for longer trace times by reducing the rate of data flowing into the trace buffer.
-u, --bus-utilization | Trace the bus utilization levels. This option requires root access on the device.
-w, --workqueue | Trace kernel work queues. This option requires root access on the device.
--set-tags=<TAGS> Set the enabled trace tags in a comma separated list. The available tags are:
  • gfx - Graphics
  • input - Input
  • view - View
  • webview - WebView
  • wm - Window Manager
  • am - Activity Manager
  • sync - Synchronization Manager
  • audio - Audio
  • video - Video
  • camera - Camera

Note: When setting trace tags from the command line, you must stop and restart the framework ($ adb shell stop; adb shell start) for the tag tracing changes to take effect.

You can set the trace tags for Systrace on your Android 4.2 and lower device by navigating to Settings > Developer options > Monitoring > Enable traces.

Trace Viewing Shortcuts

The table below lists the keyboard shortcuts that are available while viewing a Systrace trace HTML report.

Key | Description
w | Zoom into the trace timeline.
s | Zoom out of the trace timeline.
a | Pan left on the trace timeline.
d | Pan right on the trace timeline.
e | Center the trace timeline on the current mouse location.
g | Show grid at the start of the currently selected task.
Shift+g | Show grid at the end of the currently selected task.
Right Arrow | Select the next event on the currently selected timeline.
Left Arrow | Select the previous event on the currently selected timeline.

来源： https://developer.android.com/studio/profile/systrace-commandline.html


Hierarchy Viewer

The Hierarchy Viewer allows you to debug and optimize your user interface. It provides a visual representation of the layout's View hierarchy (the Layout View) and a magnified inspector of the display (the Pixel Perfect View).

To start the Hierarchy Viewer, do one of the following:

  • From Android Studio, choose Tools > Android > Android Device Monitor or click Android Device Monitor [image] in the toolbar. Click Open Perspectives [image] and select Hierarchy View.
  • From the SDK tools/ directory, enter:
    monitor

For more information on how to use the Hierarchy Viewer, see Optimizing Your UI.

Note: The command line version of Hierarchy Viewer has been deprecated.

来源： https://developer.android.com/studio/profile/hierarchy-viewer.html


Optimize Your UI

Optimizing Your UI

  1. Using Hierarchy Viewer
    1. Running Hierarchy Viewer and choosing a window
    2. About the View Hierarchy window
    3. Working with an individual View in Tree View
    4. Debugging with View Hierarchy
    5. Optimizing with View Hierarchy
  2. Using Pixel Perfect
    1. About the Pixel Perfect window
    2. Working with Pixel Perfect overlays
  3. Using lint to optimize your UI

Related videos

Sometimes your application's layout can slow down your application. To help debug issues in your layout, the Android SDK provides the Hierarchy Viewer and Lint tools.

The Hierarchy Viewer application allows you to debug and optimize your user interface. It provides a visual representation of the layout's View hierarchy (the View Hierarchy window) with performance information for each node in the layout, and a magnified view of the display (the Pixel Perfect window) to closely examine the pixels in your layout.

Android Lint is a static code scanning tool that helps you optimize the layouts and layout hierarchies of your applications, as well as detect other common coding problems. You can run it against your layout files or resource directories to quickly check for inefficiencies or other types of problems that could be affecting the performance of your application.

Using Hierarchy Viewer

Running Hierarchy Viewer and choosing a window

To run Hierarchy Viewer, follow these steps:

  1. Connect your device or launch an emulator.

    To preserve security, Hierarchy Viewer can only connect to devices running a developer version of the Android system.

  2. If you have not done so already, install the application you want to work with.
  3. Run the application, and ensure that its UI is visible.
  4. From a terminal, launch hierarchyviewer from the <sdk>/tools/ directory.
  5. The first window you see displays a list of devices and emulators. To expand the list of Activity objects for a device or emulator, click the arrow on the left. This displays a list of the Activity objects whose UI is currently visible on the device or emulator. The objects are listed by their Android component name. The list includes both your application Activity and system Activity objects. A screenshot of this window appears in figure 1.
  6. Select the name of your Activity from the list. You can now look at its view hierarchy using the View Hierarchy window, or look at a magnified image of the UI using the Pixel Perfect window.

To learn how to use the View Hierarchy window, go to About the View Hierarchy window. To learn how to use the Pixel Perfect window, go to About the Pixel Perfect window.

Figure 1. Hierarchy Viewer device window

About the View Hierarchy window

The View Hierarchy window displays the View objects that form the UI of the Activity that is running on your device or emulator. You use it to look at individual View objects within the context of the entire View tree. For each View object, the View Hierarchy window also displays rendering performance data.

To see the View Hierarchy window, run Hierarchy Viewer as described in the section Running Hierarchy Viewer and choosing a window. Next, click View Hierarchy at the top of the device window.

You should see four panes:

  • Tree View: The left-hand pane displays the Tree View, a diagram of the Activity object's hierarchy of views. Use Tree View to examine individual View objects and see the relationships between View objects in your UI.

    To zoom in on the pane, use the slider at the bottom of the pane, or use your mouse scroll wheel. To move around in the pane or reveal View objects that are not currently visible, click and drag the pane.

    To highlight the nodes in the tree whose class or ID match a search string, enter the string in the Filter by class or id: edit box at the bottom of the window. The background of nodes that match the search string will change from gray to bright blue.

    To save a screenshot of Tree View to a PNG file, click Save As PNG at the top of the View Hierarchy window. This displays a dialog in which you can choose a directory and file name.

    To save a layered screenshot of your device or emulator to an Adobe Photoshop (PSD) file, click Capture Layers at the top of the View Hierarchy window. This displays a dialog in which you can choose a directory or file name. Each View in the UI is saved as a separate Photoshop layer.

    In Photoshop (or similar program that accepts .psd files), you can hide, show or edit a layer independently of others. When you save a layered screenshot, you can examine and modify the image of an individual View object. This helps you experiment with design changes.

  • The upper right-hand pane displays the Tree Overview, a smaller map representation of the entire Tree View window. Use Tree Overview to identify the part of the view tree that is being displayed in Tree View.

    You can also use Tree Overview to move around in the Tree View pane. Click and drag the shaded rectangle over an area to reveal it in Tree View.

  • The middle right-hand pane displays the Properties View, a list of the properties for a selected View object. With Properties View, you can examine all the properties without having to look at your application source.

    The properties are organized by category. To find an individual property, expand a category name by clicking the arrow on its left. This reveals all the properties in that category.

  • The lower right-hand pane displays the Layout View, a block representation of the UI. Layout View is another way to navigate through your UI. When you click on a View object in Tree View, its position in the UI is highlighted. Conversely, when you click in an area of Layout View, the View object for that area is highlighted in Tree View.

    The outline colors of blocks in Layout View provide additional information:

    • Bold red: The block represents the the View that is currently selected in Tree View.
    • Light red: The block represents the parent of the block outlined in bold red.
    • White: The block represents a visible View that is not a parent or child of the View that is currently selected in Tree View.

When the UI of the current Activity changes, the View Hierarchy window is not automatically updated. To update it, click Load View Hierarchy at the top of the window.

Also, the window is not updated if you switch to a new Activity. To update it, start by clicking the window selection icon in the bottom left-hand corner of the window. This navigates back to the Window Selection window. From this window, click the Android component name of the new Activity and then click Load View Hierarchy at the top of the window.

A screenshot of the View Hierarchy window appears in figure 2.

Figure 2. The View Hierarchy window

Working with an individual View in Tree View

Each node in Tree View represents a single View. Some information is always visible. Starting at the top of the node, you see the following:

  1. View class: The View object's class.
  2. View object address: A pointer to View object.
  3. View object ID: The value of the android:id attribute.
  4. Performance indicators: A set of three colored dots that indicate the rendering speed of this View relative to other View objects in the tree. The three dots represent (from left to right) the measure, layout, and draw times of the rendering.

    The colors indicate the following relative performance:

    • Green: For this part of the render time, this View is in the faster 50% of all the View objects in the tree. For example, a green dot for the measure time means that this View has a faster measure time than 50% of the View objects in the tree.
    • Yellow: For this part of the render time, this View is in the slower 50% of all the View objects in the tree. For example, a yellow dot for the layout time means that this View has a slower layout time than 50% of the View objects in the tree.
    • Red: For this part of the render time, this View is the slowest one in the tree. For example, a red dot for the draw time means that this View takes the most time to draw of all the View objects in the tree.
  5. View index: The zero-based index of the View in its parent View. If it is the only child, this is 0.

When you select a node, additional information for the View appears in a small window above the node. When you click one of the nodes, you see the following:

  • Image: The actual image of the View, as it would appear in the emulator. If the View has children, these are also displayed.
  • View count: The number of View objects represented by this node. This includes the View itself and a count of its children. For example, this value is 4 for a View that has 3 children.
  • Render times: The actual measure, layout, and draw times for the View rendering, in milliseconds. These represent the same values as the performance indicators mentioned in the preceding section.

An annotated screenshot of an individual node in the Tree View window appears in figure 3.

Figure 3. An annotated node in Tree View

Debugging with View Hierarchy

The View Hierarchy window helps you debug an application by providing a static display of the UI. The display starts with your application's opening screen. As you step through your application, the display remains unchanged until you redraw it by invalidating and then requesting layout for a View.

To redraw a View in the display:

  • Select a View in Tree View. As you move up towards the root of the tree (to the left in the Tree View), you see the highest-level View objects. Redrawing a high-level object usually forces the lower-level objects to redraw as well.
  • Click Invalidate at the top of the window. This marks the View as invalid, and schedules it for a redraw at the next point that a layout is requested.
  • Click Request Layout to request a layout. The View and its children are redrawn, as well as any other View objects that need to be redrawn.

Manually redrawing a View allows you to watch the View object tree and examine the properties of individual View objects one step at a time as you go through breakpoints in your code.

Optimizing with View Hierarchy

View Hierarchy also helps you identify slow render performance. You start by looking at the View nodes with red or yellow performance indicators to identify the slower View objects. As you step through your application, you can judge if a View is consistently slow or slow only in certain circumstances.

Remember that slow performance is not necessarily evidence of a problem, especially for ViewGroup objects. View objects that have more children and more complex View objects render more slowly.

The View Hierarchy window also helps you find performance issues. Just by looking at the performance indicators (the dots) for each View node, you can see which View objects are the slowest to measure, layout, and draw. From that, you can quickly identify the problems you should look at first.

Using Pixel Perfect

Pixel Perfect is a tool for examining pixel properties and laying out UIs from a design drawing.

About the Pixel Perfect window

The Pixel Perfect window displays a magnified image of the screen that is currently visible on the emulator or device. In it, you can examine the properties of individual pixels in the screen image. You can also use the Pixel Perfect window to help you lay out your application UI based on a bitmap design.

To see the Pixel Perfect window, run Hierarchy Viewer, as described in the section Running Hierarchy Viewer and choosing a window. Next, click Inspect Screenshot at the top of the device window. The Pixel Perfect window appears.

In it, you see three panes:

  • View Object pane: This is a hierarchical list of the View objects that are currently visible on the device or emulator screen, including both the ones in your application and the ones generated by the system. The objects are listed by their View class. To see the class names of a View object's children, expand the View by clicking the arrow to its left. When you click a View, its position is highlighted in the Pixel Perfect pane on the right.
  • Pixel Perfect Loupe pane: This is the magnified screen image. It is overlaid by a grid in which each square represents one pixel. To look at the information for a pixel, click in its square. Its color and X,Y coordinates appear at the bottom of the pane.

    The magenta crosshair in the pane corresponds to the positioning crosshair in the next pane. It only moves when you move the crosshair in the next pane.

    To zoom in or out on the image, use the Zoom slider at the bottom of the pane, or use your mouse's scroll wheel.

    When you select a pixel in the Loupe pane, you see the following information at the bottom of the pane:

    • Pixel swatch: A rectangle filled with the same color as the pixel.
    • HTML color code: The hexadecimal RGB code corresponding to the pixel color
    • RGB color values: A list of the (R), green (G), and blue (B) color values of the pixel color. Each value is in the range 0-255.
    • X and Y coordinates: The pixel's coordinates, in device-specific pixel units. The values are 0-based, with X=0 at the left of the screen and Y=0 at the top.
  • Pixel Perfect pane: This displays the currently visible screen as it would appear in the emulator.

    You use the cyan crosshair to do coarse positioning. Drag the crosshair in the image, and the Loupe crosshair will move accordingly. You can also click on a point in the Pixel Perfect pane, and the crosshair will move to that point.

    The image corresponding to the View object selected in the View Object pane is outlined in a box that indicates the View object's position on the screen. For the selected object, the box is bold red. Sibling and parent View objects have a light red box. View objects that are neither parents nor siblings are in white.

    The layout box may have other rectangles either inside or outside it, each of which indicates part of the View. A purple or green rectangle indicates the View bounding box. A white or black box inside the layout box represents the padding, the defined distance between the View object's content and its bounding box. An outer white or black rectangle represents the margins, the distance between the View bounding box and adjacent View objects. The padding and margin boxes are white if the layout background is black, and vice versa.

    You can save the screen image being displayed in the Pixel Perfect pane as a PNG file. This produces a screenshot of the current screen. To do this, click Save as PNG at the top of the window. This displays a dialog, in which you can choose a directory and filename for the file.

The panes are not automatically refreshed when you change one of the View objects or go to another Activity. To refresh the Pixel Perfect pane and the Loupe pane, click Refresh Screenshot at the top of the window. This will change the panes to reflect the current screen image. You still may need to refresh the View Object pane; to do this, click Refresh Tree at the top of the window.

To automatically refresh the panes while you are debugging, set Auto Refresh at the top of the window, and then set a refresh rate with the Refresh Rate slider at the bottom of the Loupe pane.

Working with Pixel Perfect overlays

You often construct a UI based on a design done as a bitmap image. The Pixel Perfect window helps you match up your View layout to a bitmap image by allowing you to load the bitmap as an overlay on the screen image.

To use a bitmap image as an overlay:

  • Start your application in a device or emulator and navigate to the Activity whose UI you want to work with.
  • Start Hierarchy Viewer and navigate to the Pixel Perfect window.
  • At the top of the window, click Load Overlay. A dialog opens, prompting for the image file to load. Load the image file.
  • Pixel Perfect displays the overlay over the screen image in the Pixel Perfect pane. The lower left corner of the bitmap image (X=0, Y=max value) is anchored on the lower leftmost pixel (X=0, Y=max screen) of the screen.

    By default, the overlay has a 50% transparency, which allows you to see the screen image underneath. You can adjust this with the Overlay: slider at the bottom of the Loupe pane.

    Also by default, the overlay is not displayed in the Loupe pane. To display it, set Show in Loupe at the top of the window.

The overlay is not saved as part of the screenshot when you save the screen image as a PNG file.

A screenshot of the Pixel Perfect window appears in figure 4.

Figure 4. The Pixel Perfect window

Using lint to Optimize Your UI

The Android Lint tool lets you analyze the XML files that define your application's UI to find inefficiencies in the view hierarchy.

Note: The Android layoutopt tool has been replaced by the lint tool beginning in SDK Tools revision 16. The lint tool reports UI layout performance issues in a similar way as layoutopt, and detects additional problems.

For more information about using lint, see Improving Your Code with lint and the lint tools help.

来源： https://developer.android.com/studio/profile/optimize-ui.html


Walk through Hierarchy Viewer

Hierarchy Viewer Walkthrough

  • Prerequisites
  • Working with Hierarchy Viewer

You should also read

  • Device Setup for Hierarchy Viewer
  • Profiling with Hierarchy Viewer
  • Hierarchy Viewer
  • View Hierarchies
  • Importing Legacy Apps into Android Studio
  • Using Hardware Devices

This walkthrough shows the basic usage and workflow for the Hierarchy Viewer tool.

The Hierarchy Viewer tool visualizes your app's view hierarchy and profiles the relative rendering speed for each view.

What it's good for:

  • Simplifying your view hierarchy to reduce overdraw, and make it easier to manage.
  • Finding potential rendering performance bottlenecks related to the structure and shape of your view hierarchy.

Prerequisites

  • A mobile device set up to work with Hierarchy Viewer:
    1. You must have Developer Options enabled on your mobile device. You must use a physical device to get accurate measurements.
    2. Set an ANDROID_HVPROTO environment variable on the desktop machine that is connected to your device. For more information, see Device Setup for Hierarchy Viewer.
  • Debuggable app code with a view hierarchy. Use your own code, or the code for the Sunshine sample app from the Android Fundamentals Udacity course.

Working with Hierarchy Viewer

    • Figure 1. Starting Android Device Monitor.

    1. Connect your mobile device to your computer.
    2. Open your application in Android Studio, build the source, and run it on your device.
    3. From Android Studio, start the Android Device Monitor: Tools > Android > Android Device Monitor.
    4. Allow USB Debugging on your phone (if asked).

    • Figure 2. Android Device Monitor.

    6. Figure 2 illustrates what is initially shown in the Device Monitor tool. This varies depending on your setup.

      Make sure your device and the package for your application are showing in the Devices (DDMS mode) or Windows (Hierarchy Viewer mode) tab. You can choose Window > Reset Perspective to get back to the default arrangement.

      If the app does not appear, make sure you followed the device setup instructions, then start over at step 1.

    • Figure 3. Changing Perspective to Hierarchy Viewer.

    7. In Android Device Monitor (ADM), in the menu bar, choose Window > Open Perspective, and in the popup click Hierarchy View.

      OR

      Click the Hierarchy View button if it's already visible.

    • Figure 4. Hierarchy Viewer layout.

    9. If not already open, the Hierarchy View panes open.
      The example screen in Figure 4 shows an example of these panes.

    • Figure 5. Resetting the Perspective.

    10. If you see a different window arrangement, in Android Device Manager, use Window > Reset Perspective to return to the default layout for this tutorial.

    • Figure 6. Populated Hierarchy Viewer.

    11. Double-click your application in the Windows tab. This populates the panes with the view hierarchy of your application. This display is a static representation of the complete view hierarchy defined for the app.
    12. You can adjust the sizes of the panes and ADM will preserve your arrangement in future sessions.

    • Figure 7. Hierarchy Viewer panes.

    13. If necessary, click the Layout View tab to hide the Console and show a wireframe of your layout. The outline of the currently selected view is red. Click an outline to select it.
    14. The rest of the panes:
      • The Tree Overview in the upper right gives you a bird's-eye view of your app's complete View Hierarchy.
      • In the Tree Overview, move the gray viewport rectangle to change what section of your hierarchy shows in the Tree View pane (in the center).
      • In the Tree View, you can drag and zoom the tree using your mouse.

    • Figure 7. Parts of the View node display.

    15. Click on a View node to display details. Here is an annotated close-up of a node and its details.

    • Figure 8. Location of View Properties tab.

    16. Click the View Properties tab at the top right (next to the Windows tab) to see properties of the selected View node.

    • Figure 9. Rendering a view in a popup.

    17. Double-click a View node in the Tree View to render it in a popup window.

    • Figure 10. Node with its type and id.

    18. Nodes in the Tree View show a Type, which indicates the View class, and an id, which is the view identifier in your code.

来源： https://developer.android.com/studio/profile/hierarchy-viewer-walkthru.html


Set Up Devices for Hierarchy Viewer

Device Setup for Hierarchy Viewer

You should also read

  • Hierarchy Viewer Walkthrough
  • Profiling with Hierarchy Viewer

To run Hierarchy Viewer, you must enable Developer Options on your mobile device and perform some setup on your computer.

Configuring Devices

  1. Enable Developer Options on your mobile device.

  2. Depending on the type of device you have, do one of the following:
    • If you have a locked device running Android 4.0 or lower, follow the instructions for installing and configuring ViewServer.
    • If you have an unlocked device running Android 4.0 or lower, no further configuration is needed.
    • If you have a device running Android 4.1 or higher, you must set an environment variable on your development machine. For more information, seeSetting the ANDROID_HVPROTO variable

Setting the ANDROID_HVPROTO variable

Windows

  1. Click My Computer > Property > Advanced > Environment Variables.
  2. Click New.
  3. In variables name put: ANDROID_HVPROTO
  4. In variable value put: ddm
  5. Click OK<./li>

Mac

  1. Edit ~/.bash_profile
  2. Add:
    #Hierarchy Viewer Variable
    export ANDROID_HVPROTO=ddm
  3. source ~/.bash_profile

Linux

  1. Edit ~/.bash_profile
  2. Add:
    #Hierarchy Viewer Variable
    export ANDROID_HVPROTO=ddm
  3. source ~/.bash_profile

来源： https://developer.android.com/studio/profile/hierarchy-viewer-setup.html


Interpret Hierarchy Viewer Results

Profiling with Hierarchy Viewer

  • Prerequisites
  • Profiling with Hierarchy Viewer
  • Interpreting Profiling Results

This walkthrough shows you how to profile your app's view hiearchy with Hierarchy Viewer, and how to interpret the results.

Prerequisites

  • Device Setup for Hierarchy Viewer
  • Hierarchy Viewer Walkthrough

Profiling Steps

    • Figure 1. View hierarchy after profiling.

    1. Start Hierarchy Viewer for your app.
    2. In the Tree View or the Layout View, click on the View node whose children you want to profile.
    3. To start profiling, click the small button with three circles [image] at the top of the Tree View.
    4. For large view hierarchies, profiling may take a few seconds.
    5. Each view in your subtree gets three dots, which can be green, yellow, or red.
      • The left dot represents the Draw Process of the rendering pipeline.
      • The middle dot represents the Layout Phase.
      • The right dot represents the Execute Phase.

    • Figure 2. How the colored dots relate
      to the rendering pipeline.

    5. These dots roughly correspond to the Measure, Layout, and Draw phases of the processing pipeline.
    6. The color of the dots indicates the relative performance of this node in respect to all other profiled nodes.
      • Green means the view renders faster than at least half of the other views.
      • Yellow means the view renders faster than the bottom half of the other views.
      • Red means the view is among the slowest half of views.

Interpreting Hierarchy Viewer Profiling Results

Hierarchy Viewer measures the relative performance of a node, so there are always red nodes in a profile, and it doesn't necessarily mean that view is too slow for the users of your app.

Hierarchy Viewer software rasterizes your Activity to acquire the timing information. Rasterization is the process of taking a high-level primitive, such as a circle or a vector font, and turning it into pixels on the screen. Typically, rasterization is done by the GPU on your device, but in the case of software rasterization, rendering is done on the CPU with ordinary software. This means that the absolute reported timings are correct relative to each other, but are bloated and vary depending on the overall and changing CPU workload on your device and PC. Profile several times to get a feel for the average measurements.

The following are guidelines for interpreting Hierarchy Viewer profiling output.

A red node is a potential problem in any situation where your app has unexpectedly slow performance. In a relative setting, there is always a slowest node; make sure it is the node you expect. The following examples illustrate how to interpret red dots.

  • Look for red dots in leaf nodes or view groups with only a few children. This might point to a problem. Your app may not be slow, or it may not be slow on your device, but you need to be aware of why that dot is red. Systrace or Traceview can give you additional information.
  • If you have a view group with many children and a red measure phase, take a look at the children to see how they are performing.
  • A view with yellow or even red dots might not be performing slowly on the device. That's where the actual numbers are helpful. Systrace or Traceviewcan give you additional information.
  • If the root view of a hierarchy has a red measure phase, red layout phase, and yellow draw phase, this is somewhat typical, because it's the parent of all the other views.
  • If a leaf node in a tree with 20+ views has a red draw phase, this is a problem. Check your OnDraw method for code that shouldn't be there.

来源： https://developer.android.com/studio/profile/hierarchy-viewer-results-walkthru.html


Android Device Monitor

See also

  1. Investigating Your RAM Usage
  2. Android Monitor

Android Device Monitor is a standalone tool that provides a UI for several Android application debugging and analysis tools. Android Device Monitor doesn't require installation of an integrated development environment, such as Android Studio, and encapsulates the following tools:

  • DDMS
  • Tracer for OpenGL ES
  • Hierarchy Viewer
  • Systrace
  • Traceview
  • Pixel Perfect magnification viewer

Launching Android Device Monitor

To start Android Device Monitor:

  • From Android Studio, choose Tools > Android > Android Device Monitor or click the Android Device Monitor [image] in the toolbar.
  • From the command line, in the SDK tools/ directory, enter the following command:
    monitor

Next, start an Android Emulator or connect an Android device to your development computer through a USB cable. Connect Android Device Monitor to the device by selecting it in the Devices tab.

Note: Only one debugger can be connected to your device at a time.

来源： https://developer.android.com/studio/profile/monitor.html


Use DDMS

Using DDMS

  1. Running DDMS
  2. How DDMS Interacts with a Debugger
  3. Using DDMS
    1. Viewing heap usage for a process
    2. Tracking memory allocation of objects
    3. Working with an emulator or device's file system
    4. Examining thread information
    5. Starting method profiling
    6. Using the Network Traffic tool
    7. Using LogCat
    8. Emulating phone operations and location

See also

  1. Android Monitor
  2. Android Emulator

Android Studio includes a debugging tool called the Dalvik Debug Monitor Server (DDMS), which provides port-forwarding services, screen capture on the device, thread and heap information on the device, logcat, process, and radio state information, incoming call and SMS spoofing, location data spoofing, and more. This page provides a modest discussion of DDMS features; it is not an exhaustive exploration of all the features and capabilities.

Running DDMS

DDMS is integrated into Android Studio. To use it, launch the Android Device Monitor, and click the DDMSmenu button. DDMS works with both the emulator and a connected device. If both are connected and running simultaneously, DDMS defaults to the emulator.

How DDMS Interacts with a Debugger

On Android, every application runs in its own process, each of which runs in its own virtual machine (VM). Each VM exposes a unique port that a debugger can attach to.

When DDMS starts, it connects to adb. When a device is connected, a VM monitoring service is created between adb and DDMS, which notifies DDMS when a VM on the device is started or terminated. Once a VM is running, DDMS retrieves the VM's process ID (pid), via adb, and opens a connection to the VM's debugger, through the adb daemon (adbd) on the device. DDMS can now talk to the VM using a custom wire protocol.

DDMS assigns a debugging port to each VM on the device. Typically, DDMS assigns port 8600 for the first debuggable VM, the next on 8601, and so on. When a debugger connects to one of these ports, all traffic is forwarded to the debugger from the associated VM. You can only attach a single debugger to a single port, but DDMS can handle multiple, attached debuggers.

By default, DDMS also listens on another debugging port, the DDMS "base port" (8700, by default). The base port is a port forwarder, which can accept VM traffic from any debugging port and forward it to the debugger on port 8700. This allows you to attach one debugger to port 8700, and debug all the VMs on a device. The traffic that is forwarded is determined by the currently selected process in the DDMS Devices view.

The following screenshot shows a typical DDMS screen. If you are starting DDMS from the command line, the screen is slightly different, but much of the functionality is identical. Notice that the highlighted process, com.android.email, that is running in the emulator has the debugging port 8700 assigned to it as well as 8606. This signifies that DDMS is currently forwarding port 8606 to the static debugging port of 8700.

Figure 1. Screenshot of DDMS

If you are using the command line, read Configuring your IDE to attach to the debugging port, for more information on attaching your debugger.

Tip: You can set a number of DDMS preferences in File > Preferences. Preferences are saved to $HOME/.android/ddms.cfg.

Known debugging issues with Dalvik
Debugging an application in the Dalvik VM should work the same as it does in other VMs. However, when single-stepping out of synchronized code, the "current line" cursor may jump to the last line in the method for one step.

Using DDMS

The following sections describe how to use DDMS and the various tabs and panes that are part of the DDMS GUI. The Android Studio version and the command line version have minor UI differences, but the same functionality. For information on running DDMS, see the previous section in this document, Running DDMS .

Viewing heap usage for a process

DDMS allows you to view how much heap memory a process is using. This information is useful in tracking heap usage at a certain point of time during the execution of your application.

To view heap usage for a process:

  1. In the Devices tab, select the process that you want to see the heap information for.
  2. Click the Update Heap button to enable heap information for the process.
  3. In the Heap tab, click Cause GC to invoke garbage collection, which enables the collection of heap data. When the operation completes, you will see a group of object types and the memory that has been allocated for each type. You can click Cause GC again to refresh the data.
  4. Click on an object type in the list to see a bar graph that shows the number of objects allocated for a particular memory size in bytes.

Tracking memory allocation of objects

DDMS provides a feature to track objects that are being allocated to memory and to see which classes and threads are allocating the objects. This allows you to track, in real time, where objects are being allocated when you perform certain actions in your application. This information is valuable for assessing memory usage that can affect application performance.

To track memory allocation of objects:

  1. In the Devices tab, select the process that you want to enable allocation tracking for.
  2. In the Allocation Tracker tab, click the Start Tracking button to begin allocation tracking. At this point, anything you do in your application will be tracked.
  3. Click Get Allocations to see a list of objects that have been allocated since you clicked on the Start Tracking button. You can click on Get Allocationsagain to append to the list new objects that have been allocated.
  4. To stop tracking or to clear the data and start over, click the Stop Tracking button.
  5. Click on a specific row in the list to see more detailed information such as the method and line number of the code that allocated the object.

Working with an emulator or device's file system

DDMS provides a File Explorer tab that allows you to view, copy, and delete files on the device. This feature is useful in examining files that are created by your application or if you want to transfer files to and from the device.

To work with an emulator or device's file system:

  1. In the Devices tab, select the emulator that you want to view the file system for.
  2. To copy a file from the device, locate the file in the File Explorer and click the Pull file button.
  3. To copy a file to the device, click the Push file button on the File Explorer tab.

Examining thread information

The Threads tab in DDMS shows you the currently running threads for a selected process.

  1. In the Devices tab, select the process that you want to examine the threads for.
  2. Click the Update Threads button.
  3. In the Threads tab, you can view the thread information for the selected process.

Starting method profiling

Method profiling is a means to track certain metrics about a method, such as number of calls, execution time, and time spent executing the method. If you want more granular control over where profiling data is collected, use the startMethodTracing() and stopMethodTracing() methods. For more information about generating trace logs, see Profiling and Debugging UIs.

Before you start method profiling in DDMS, be aware of the following restrictions:

  • Android 2.1 and earlier devices must have an SD card present and your application must have permission to write to the SD card.
  • Android 2.2 and later devices do not need an SD card. The trace log files are streamed directly to your development machine.

To start method profiling:

  1. On the Devices tab, select the process that you want to enable method profiling for.
  2. Click the Start Method Profiling button.
  3. In Android 4.4 and later, choose either trace-based profiling or sample-based profiling with a specified sampling interval. For earlier versions of Android, only trace-based profiling is available.
  4. Interact with your application to start the methods that you want to profile.
  5. Click the Stop Method Profiling button. DDMS stops profiling your application and opens Traceview with the method profiling information that was collected between the time you clicked on Start Method Profiling and Stop Method Profiling.

Using the Network Traffic tool

In Android 4.0, the DDMS (Dalvik Debug Monitor Server) includes a Detailed Network Usage tab that makes it possible to track when your application is making network requests. Using this tool, you can monitor how and when your app transfers data and optimize the underlying code appropriately. You can also distinguish between different traffic types by applying a “tag” to network sockets before use.

These tags are shown in a stack area chart in DDMS, as shown in figure 2:

Figure 2. Network Usage tab.

By monitoring the frequency of your data transfers, and the amount of data transferred during each connection, you can identify areas of your application that can be made more battery-efficient. Generally, you should look for short spikes that can be delayed, or that should cause a later transfer to be pre-empted.

To better identify the cause of transfer spikes, the TrafficStats API allows you to tag the data transfers occurring within a thread usingsetThreadStatsTag(), followed by manually tagging (and untagging) individual sockets using tagSocket() and untagSocket(). For example:

TrafficStats.setThreadStatsTag(0xF00D);
TrafficStats.tagSocket(outputSocket);
// Transfer data using socket
TrafficStats.untagSocket(outputSocket);

Alternatively, the URLConnection APIs included in the platform automatically tag sockets internally based on the active tag (as identified bygetThreadStatsTag()). These APIs correctly tag/untag sockets when recycled through keep-alive pools. In the following example, setThreadStatsTag()sets the active tag to be 0xF00D. There can only be one active tag per thread. That is the value that will be returned by getThreadStatsTag() and thus used by the HTTP client to tag sockets. The finally statement invokes clearThreadStatsTag() to clear the tag.

TrafficStats.setThreadStatsTag(0xF00D);
    try {
        // Make network request using your http client.
    } finally {
        TrafficStats.clearThreadStatsTag();
}

Socket tagging is supported in Android 4.0, but real-time stats will only be displayed on devices running Android 4.0.3 or higher.

Using LogCat

LogCat is integrated into DDMS, and outputs the messages that you print out using the Log class along with other system messages such as stack traces when exceptions are thrown. View the Reading and Writing Log Messages. topic for more information on how to log messages to the LogCat.

When you have set up your logging, you can use the LogCat feature of DDMS to filter certain messages with the following buttons:

  • Verbose
  • Debug
  • Info
  • Warn
  • Error

You can also setup your own custom filter to specify more details such as filtering messages with the log tags or with the process id that generated the log message. The add filter, edit filter, and delete filter buttons let you manage your custom filters.

Emulating phone operations and location

The Emulator Control tab, shown in Figure 1, is no longer supported. Use the Android Emulator for these features.

来源： https://developer.android.com/studio/profile/ddms.html


Inspect the Memory Heap with Heap Viewer

Heap Viewer Walkthrough

  • Prerequisites
  • Working with Heap Viewer

You should also read

  • Memory Monitor Walkthrough
  • Allocation Tracker Walkthrough
  • Comparison: Memory Monitor, Heap Viewer, Allocation Tracker
  • Traceview Walkthrough

This walkthrough shows the basic usage and workflow for the Heap Viewer tool. Heap Viewer reports in real-time what types of objects your application has allocated, how many, and their sizes on the heap.

What it's good for:

  • Getting a sense of how your app allocates and frees memory.
  • Identifying memory leaks.

Prerequisites

  • A mobile device running Android 5.0 or higher with Developer Options enabled.
  • Application code. Use your own code, or the Sunshine sample app from the Android Fundamentals Udacity course.

Working with Heap Viewer

    • Figure 1. Starting Memory Monitor.

    1. Connect your mobile device to your computer.
    2. Open your application in Android Studio, build the source, and run it on your device or emulator.
    3. Start the Android Device Monitor from Android Studio: Tools -> Android -> Android Device Monitor.

      Alternatively, you could start the Memory Monitor in Android Monitor.

    • Figure 2. Steps for Using Heap Viewer.

    4. In the device and application drop-downs, select the app you want to monitor.

    • Figure 3. Update Heap button.

    8. To save a heap dump, click the Dump Java Heap icon. The heap snapshot file with the filename Snapshot-yyyy.mm.dd-hh.mm.ss.hprof appears in the Captures tab.

    • Figure 4. Triggering GC (Garbage Collection).

    9. Note the Heap updates will happen after every GC for this client. message.
    10. Click the Initiate GC icon to trigger a garbage collection event.

    • Figure 5. Example Heap Viewer output.

    11. Double-click the heap snapshot file to open the heap viewer and see detailed information about the current allocations on the heap.

来源： https://developer.android.com/studio/profile/heap-viewer-walkthru.html


Track Memory Allocation with Allocation Tracker

Allocation Tracker Walkthrough

  • Prerequisites
  • Working with Allocation Tracker

You should also read

  • Heap Viewer Walkthrough
  • Memory Monitor Walkthrough
  • Comparison: Memory Monitor, Heap Viewer, Allocation Tracker
  • Traceview Walkthrough

This walkthrough shows the basic usage and workflow for the Allocation Tracker tool in Android Studio. Allocation Tracker records an app's memory allocations and lists all allocated objects for the profiling cycle with their call stack, size, and allocating code.

What it's good for:

  • Identifying where many similar object types, from roughly the same call stack, are allocated and deallocated over a very short period of time.
  • Finding the places in your code that may contribute to inefficient memory use.

Before using Allocation Tracker, profile your code with the Memory Monitor Tool. If you see many garbage collection events in a short amount of time, use Heap Viewer to identify candidate object types, and Allocation Tracker to determine where this is happening in your code.

Prerequisites

  • A mobile device with Developer Options enabled.
  • Application code. Use your own code, or the Sunshine sample app from the Android Fundamentals Udacity course.

Working with Allocation Tracker

Allocation Tracker records each memory allocation that your app performs during the profiling cycle. You tell Allocation Tracker to start recording and it logs allocations until you tell it to stop.

    • Figure 1. Steps for starting Allocation Tracker in Android DDMS.

    1. Connect your mobile device to your computer.
    2. Open your application in Android Studio, build the source, and run it on your device or emulator.
    3. Click the Android button at the bottom of your Android Studio window.
    4. If you are using the Android Device Monitor, click the RECORD button [image] (Start Allocation Tracking tooltip) in the Android DDMS tool bar. If you are using Android Monitor, click the [image] icon in the a href="/tools/help/am-memory.html">Memory Monitor toolbar.
    5. Interact with your application.
    6. Click the (same) STOP button (Stop Allocation Tracking tooltip).

    • Figure 2. Example of Allocation Tracker output in Android DDMS.

    7. After a few seconds, a pane with your recorded data opens.

      Note that allocations are logged on the device, and the data file is transferred to the host computer, parsed for information, and displayed.

    8. The pane populates with a table.
      • Each row represents a memory allocation event.
      • Each column represents information about the allocation, such as the object type, the thread, and its size.
      • The columns are movable, resizable, and sortable.

      Use the Filter to show only allocations from your app.

    9. Click on an object to see its full stack trace.

来源： https://developer.android.com/studio/profile/allocation-tracker-walkthru.html


Trace OpenGL Code

Tracer for OpenGL ES

  1. Running Tracer
  2. Generating a Trace
  3. Analyzing a Trace

Tracer is a tool for analyzing OpenGL for Embedded Systems (ES) code in your Android application. The tool allows you to capture OpenGL ES commands and frame by frame images to help you understand how your graphics commands are being executed.

Note: The Tracer tool requires a device running Android 4.1 (API Level 16) or higher.

Running Tracer

To run Tracer in Device Monitor:

  1. Start the Android Device Monitor tool.
  2. Activate the perspective for Tracer by choosing Window > Open Perspective...
  3. Select Tracer for OpenGL ES and click OK.

Generating a Trace

Tracer captures OpenGL ES command execution logs and can also capture progressive images of the frames generated by those commands to enable you to perform logical and visual analysis of your OpenGL ES code. The Tracer tool operates by connecting to a device running Android 4.1 (API Level 16) or higher that is running the application you want to analyze. The Tracer tool captures trace information while the application is running and saves it to a.gltrace file for analysis.

Figure 1. Trace capture dialog box.

To capture an OpenGL ES trace for an Android application:

  1. Connect the Android device using a USB cable and make sure it is enabled for debugging. For more information, see Using Hardware Devices.
  2. In the Device Monitor, activate the Tracer for OpenGL ES perspective.
  3. On the toolbar, click the trace capture button ( [image] ).
  4. In the dialog box, select the Device to use for the trace.
  5. In the Application Package field, enter the full application package name containing the activity you want to trace, for example:com.example.android.opengl
  6. In the Activity to launch field, enter the class name of the activity you want to trace, for example: OpenGLES20Complete

    Note: If you are tracing the default activity for the application, you can leave this field blank.

  7. Select the desired Data Collection Options.

    Note: If you want to capture progressive frame images for each drawing call, enable the Read back currently bound framebuffer on glDraw*()option. Be aware that using this option can result in large trace files.

  8. Enter a Destination File for the trace output.
  9. Click Trace to start the trace capture.
  10. On the connected device, exercise the functions of your application you want to trace.
  11. In the dialog box, Stop Tracing to complete the tracing run.

Analyzing a Trace

After you have generated a trace, you can load it for review and analysis.

To review a captured trace:

  1. In Device Monitor, activate the Tracer for OpenGL ES perspective.
  2. On the toolbar, click the trace load button ( [image] ).
  3. After loading a trace, select a frame and review the OpenGL ES calls. Drawing commands are highlighted in blue.
    来源： https://developer.android.com/studio/profile/gltracer.html


Performance Profiling Tools

Putting pixels on the screen involves four primary pieces of hardware. To greatly simplify, the CPU computes display lists, the GPU renders images to the display, the memory stores images and data, and the battery provides electrical power. Each of these pieces of hardware has constraints; pushing or exceeding those constraints causes your app to be slow, have bad display performance, or exhaust the battery.

To discover what causes your specific performance problems, you need to take a look under the hood, use tools to collect data about your app execution behavior, surface that data as lists and graphics, understand and analyze what you see, and improve your code.

Android Studio and your device provide profiling tools to record and visualize the rendering, compute, memory, and battery performance of your app.

Note: While profiling an app, you should disable Instant Run. There is a small performance impact when using Instant Run and a slightly larger impact when updating methods. This performance impact could interfere with information provided by performance profiling tools. Additionally, the stub methods generated while using the feature can complicate stack traces.

来源： https://developer.android.com/studio/profile/index.html


Optimize Memory Use with the Memory Monitor

Memory Monitor

  1. Memory Monitor Workflow
    1. Garbage collection roots and dominator trees
    2. Memory leak and use analysis
    3. Memory management for different virtual machines
  2. Displaying a Running App in the Memory Monitor
  3. Forcing a Garbage Collection Event
  4. Taking a Snapshot of the Java Heap and Memory Allocation

See also

  1. Managing Your App's Memory
  2. Addressing Garbage Collection Issues
  3. Investigating Your RAM Usage

Android Monitor provides a Memory Monitor so you can more easily monitor app performance and memory usage to find deallocated objects, locate memory leaks, and track the amount of memory the connected device is using. The Memory Monitor reports how your app allocates memory and helps you to visualize the memory your app uses. It lets you:

  • Show a graph of available and allocated Java memory over time.
  • Show garbage collection (GC) events over time.
  • Initiate garbage collection events.
  • Quickly test whether app slowness might be related to excessive garbage collection events.
  • Quickly test whether app crashes may be related to running out of memory.

Memory Monitor Workflow

To profile and optimize memory use, the typical workflow is to run your app and do the following:

  1. Profile the app using the Memory Monitor to find out whether undesirable garbage collection event patterns might be causing performance problems.
  2. If you see many garbage collection events in a short amount of time, dump the Java heap to identify candidate object types that get or stay allocated unexpectedly or unnecessarily.
  3. Start allocation tracking to determine where any problems are happening in your code.

The Java heap data shows in real-time what types of objects your application has allocated, how many, and their sizes on the heap. Viewing the heap helps you to:

  • Get a sense of how your app allocates and frees memory.
  • Identify memory leaks.

Allocation tracking records app memory allocations and lists all allocations for the profiling cycle, including the call stack, size, and allocating code. It helps you to:

  • Identify where many similar object types, from roughly the same call stack, are allocated and deallocated over a very short period of time.
  • Find the places in your code that may contribute to inefficient memory use.

Garbage collection roots and dominator trees

When you dump the Java heap, the Memory Monitor creates an Android-specific Heap/CPU Profiling (HPROF) file that you can view in the HPROF Viewer. The HPROF Viewer indicates a garbage collection root with the [image] icon (and a depth of zero) and a dominator with the [image] icon.

There are several kinds of garbage collection roots in Java:

  • references on the stack
  • Java Native Interface (JNI) native objects and memory
  • static variables and functions
  • threads and objects that can be referenced
  • classes loaded by the bootstrap loader
  • finalizers and unfinalized objects
  • busy monitor objects

The HPROF file provides the list of roots to the HPROF Viewer.

A dominator tree traces paths to objects created by the app. An object dominates another object if the only way to reach the other object is, directly or indirectly, through the dominator object. When you examine objects and paths created by an app in an effort to optimize memory use, try to remove objects that are no longer needed. You can release a dominator object to release all subordinate objects. For example, in the following figure, if you were to remove object B, that would also release the memory used by the objects it dominates, which are objects C, D, E, and F. In fact, if objects C, D, E, and F were marked for removal, but object B was still referring to them, that could be the reason that they weren’t released.

Memory leak and use analysis

An app performs better if it uses memory efficiently and releases the memory when it’s no longer needed. Memory leaks that are large or that grow over time are the most important to correct.

One way to optimize memory usage is to analyze large arrays. For example, can you reduce the size of individual elements in the array to save memory?

Another area that deserves attention is objects that the app no longer needs but continues to reference. You can gather heap dumps over different periods of time and compare them to determine if you have a growing memory leak, such as an object type that your code creates multiple times but doesn’t destroy. These objects could be part of a growing array or an object tree, for example. To track down this problem, compare the heap dumps and see if you have a particular object type that continues to have more and more instances over time.

Continually growing object trees that contain root or dominator objects can prevent subordinate objects from being garbage-collected. This issue is a common cause of memory leaks, out-of-memory errors, and crashes. Your app could have a small number of objects that are preventing a large number of subordinate objects from being destroyed, so it runs out of memory quickly. To find these issues, get a heap dump and examine the amount of memory held by root and dominator objects. If the memory is substantial, you’ve likely found a good place to start optimizing your memory use.

As you start narrowing down memory issues, you should also use the Allocation Tracker to get a better understanding of where your memory-hogging objects are allocated. The Allocation Tracker can be valuable not only for looking at specific uses of memory, but also for analyzing critical code paths, such as loading and scrolling. For example, tracking allocations when flinging a list in your app allows you to see all of the allocations that need to be done for that behavior, what thread they are on, and where they came from. This information is extremely valuable for tightening up these paths to reduce the work they need and improve the overall smoothness of the UI.

It’s useful to examine your algorithms for allocations that are unnecessary or that create the same object many times instead of reusing them. For example, do you create temporary objects and variables within recursive loops? If so, try creating an object or variable before the loop for use within the loop. Otherwise, your app might needlessly allocate many objects and variables, depending on the number of recursions.

It’s important to perform allocation tests on portions of your code that create the most and largest objects, as those areas offer the most optimization opportunities. In addition to unit tests, you should test your app with production-realistic data loads, especially those algorithms that are data-driven. Also, make sure to account for the app caching and startup phase, which can sometimes be slow; allocation analysis is best done after that phase to produce accurate results.

After you optimize code, be sure to test that it worked. You need to test under different load conditions and also without running the Memory Monitor tools. Compare results before and after optimization to make sure that performance has actually improved.

Memory management for different virtual machines

Android Monitor uses the Virtual Machine (VM) that the device or emulator uses:

  • Android 4.3 (API level 18) and lower uses the Dalvik VM.
  • In Android 4.4 (API level 19), the Android RunTime (ART) VM is an option, while the Dalvik VM is the default.
  • Android 5.0 (API level 21) and higher uses the ART VM.

The VM handles garbage collection. The Dalvik VM uses a mark-and-sweep scheme for garbage collection. The ART VM uses a generational scheme, combined with mark-and-sweep when memory needs a more thorough garbage collection, such as when memory becomes excessively fragmented. The logcat Monitor displays some messages that indicate the type of garbage collection that occurred and why.

Memory Monitor results can vary between the different VMs. As a result, if you’re supporting both VMs, you might want to test with both. In addition, the VMs available for different API levels can have different behavior. For example, the Dalvik VM in Android 2.3 (API level 10) and lower uses externally allocated memory while higher versions allocate in the Dalvik heap only.

You can’t reconfigure the Dalvik and ART VMs to tune performance. Instead, you should examine your app code to determine how to improve its operation, for example, reducing the size of very large arrays.

There are programmatic ways to manipulate when the VM performs garbage collection, although it’s not a best practice. These techniques can be specific to the VM. For more information, see Addressing Garbage Collection (GC) Issues and Investigating Your RAM Usage.

The ART VM adds a number of performance, development, and debugging improvements over the Dalvik VM. For more information, see ART and Dalvik.

Displaying a Running App in the Memory Monitor

To display an app running on a particular device or emulator in the Memory Monitor:

  1. Meet the prerequisites and dependencies.
  2. Open an app project.
  3. Run the app on a hardware device or emulator.
  4. Display Android Monitor.
  5. Click the Monitors tab and display the Memory Monitor.
  6. Enable the Memory Monitor by clicking Pause [image] to deselect it.

    7. In the graph, the y-axis displays the free and allocated RAM in megabytes. The x-axis shows the time elapsed; it starts with seconds, and then minutes and seconds, and so on. The amount of free memory, measured in megabytes, is shown in a light color, and allocated memory is a darker color. When there’s a sharp drop in allocated memory, that indicates a garbage collection event.

    To force a garbage collection event, click Initiate GC [image] .

    In the following figure, the VM initiated the first garbage collection event, while the developer forced the second.

  7. Interact with your app and watch how it affects memory usage in the Memory Monitor. You can identify garbage collection patterns for your app and determine whether they're healthy and what you expect.

    8. The graph can show you potential issues:

    • Excessive garbage collection events slow down the app.
    • The app runs out of memory, which causes it to crash.
    • Potential memory leaks.

    For example, you might see the following signs of problems:

    • Your app is static, but you see memory being allocated in the monitor.
    • You see spikes of memory allocations in the monitor, but you don’t think there’s any app logic to cause this behavior.
  8. To stop the Memory Monitor, click Pause [image] again to select it.

Forcing a Garbage Collection Event

Normally, VMs perform garbage collection only when absolutely needed, since it’s expensive. However, it can be useful to force garbage collection in certain circumstances. For example, when locating memory leaks, if you want to determine whether a large object was successfully released already, you can initiate garbage collection much more aggressively than usual.

To force a garbage collection event:

  • While the Memory Monitor is running, click Initiate GC [image] .

Taking a Snapshot of the Java Heap and Memory Allocation

You can take snapshots while the Memory Monitor is running or paused:

  • To take and display a snapshot of the Java heap, see HPROF Viewer and Analyzer.
  • To take and display a snapshot of memory allocation, see Allocation Tracker.
    来源： https://developer.android.com/studio/profile/am-memory.html


Investigating Your RAM Usage

  1. Interpreting Log Messages
  2. Viewing Heap Updates
  3. Tracking Allocations
  4. Viewing Overall Memory Allocations
  5. Capturing a Heap Dump
  6. Triggering Memory Leaks

See Also

  • Managing Your App's Memory

Because Android is designed for mobile devices, you should always be careful about how much random-access memory (RAM) your app uses. Although Dalvik and ART perform routine garbage collection (GC), this doesn’t mean you can ignore when and where your app allocates and releases memory. In order to provide a stable user experience that allows the system to quickly switch between apps, it is important that your app does not needlessly consume memory when the user is not interacting with it.

Even if you follow all the best practices for Managing Your App Memory during development (which you should), you still might leak objects or introduce other memory bugs. The only way to be certain your app is using as little memory as possible is to analyze your app’s memory usage with tools. This guide shows you how to do that.

Interpreting Log Messages

The simplest place to begin investigating your app’s memory usage is the runtime log messages. Sometimes when a GC occurs, a message is printed to logcat. The logcat output is also available in the Device Monitor or directly in an IDE such as Android Studio.

Dalvik Log Messages

In Dalvik (but not ART), every GC prints the following information to logcat:

D/dalvikvm: <GC_Reason> <Amount_freed>, <Heap_stats>, <External_memory_stats>, <Pause_time>

Example:

D/dalvikvm( 9050): GC_CONCURRENT freed 2049K, 65% free 3571K/9991K, external 4703K/5261K, paused 2ms+2ms
GC Reason
What triggered the GC and what kind of collection it is. Reasons that may appear include:
GC_CONCURRENT
A concurrent GC that frees up memory as your heap begins to fill up.
GC_FOR_MALLOC
A GC caused because your app attempted to allocate memory when your heap was already full, so the system had to stop your app and reclaim memory.
GC_HPROF_DUMP_HEAP
A GC that occurs when you request to create an HPROF file to analyze your heap.
GC_EXPLICIT
An explicit GC, such as when you call gc() (which you should avoid calling and instead trust the GC to run when needed).
GC_EXTERNAL_ALLOC
This happens only on API level 10 and lower (newer versions allocate everything in the Dalvik heap). A GC for externally allocated memory (such as the pixel data stored in native memory or NIO byte buffers).
Amount freed
The amount of memory reclaimed from this GC.
Heap stats
Percentage free of the heap and (number of live objects)/(total heap size).
External memory stats
Externally allocated memory on API level 10 and lower (amount of allocated memory) / (limit at which collection will occur).
Pause time
Larger heaps will have larger pause times. Concurrent pause times show two pauses: one at the beginning of the collection and another near the end.

As these log messages accumulate, look out for increases in the heap stats (the 3571K/9991K value in the above example). If this value continues to increase, you may have a memory leak.

ART Log Messages

Unlike Dalvik, ART doesn't log messages for GCs that were not explicitly requested. GCs are only printed when they are they are deemed slow. More precisely, if the GC pause exceeds than 5ms or the GC duration exceeds 100ms. If the app is not in a pause perceptible process state, then none of its GCs are deemed slow. Explicit GCs are always logged.

ART includes the following information in its garbage collection log messages:

I/art: <GC_Reason> <GC_Name> <Objects_freed>(<Size_freed>) AllocSpace Objects, <Large_objects_freed>(<Large_object_size_freed>) <Heap_stats> LOS objects, <Pause_time(s)>

Example:

I/art : Explicit concurrent mark sweep GC freed 104710(7MB) AllocSpace objects, 21(416KB) LOS objects, 33% free, 25MB/38MB, paused 1.230ms total 67.216ms
GC Reason
What triggered the GC and what kind of collection it is. Reasons that may appear include:
Concurrent
A concurrent GC which does not suspend app threads. This GC runs in a background thread and does not prevent allocations.
Alloc
The GC was initiated because your app attempted to allocate memory when your heap was already full. In this case, the garbage collection occurred in the allocating thread.
Explicit
The garbage collection was explicitly requested by an app, for instance, by calling gc() or gc(). As with Dalvik, in ART it is recommended that you trust the GC and avoid requesting explicit GCs if possible. Explicit GCs are discouraged since they block the allocating thread and unnecessarily was CPU cycles. Explicit GCs could also cause jank if they cause other threads to get preempted.
NativeAlloc
The collection was caused by native memory pressure from native allocations such as Bitmaps or RenderScript allocation objects.
CollectorTransition
The collection was caused by a heap transition; this is caused by switching the GC at run time. Collector transitions consist of copying all the objects from a free-list backed space to a bump pointer space (or visa versa). Currently collector transitions only occur when an app changes process states from a pause perceptible state to a non pause perceptible state (or visa versa) on low RAM devices.
HomogeneousSpaceCompact
Homogeneous space compaction is free-list space to free-list space compaction which usually occurs when an app is moved to a pause imperceptible process state. The main reasons for doing this are reducing RAM usage and defragmenting the heap.
DisableMovingGc
This is not a real GC reason, but a note that collection was blocked due to use of GetPrimitiveArrayCritical. while concurrent heap compaction is occuring. In general, the use of GetPrimitiveArrayCritical is strongly discouraged due to its restrictions on moving collectors.
HeapTrim
This is not a GC reason, but a note that collection was blocked until a heap trim finished.
GC Name
ART has various different GCs which can get run.
Concurrent mark sweep (CMS)
A whole heap collector which frees collects all spaces other than the image space.
Concurrent partial mark sweep
A mostly whole heap collector which collects all spaces other than the image and zygote spaces.
Concurrent sticky mark sweep
A generational collector which can only free objects allocated since the last GC. This garbage collection is run more often than a full or partial mark sweep since it is faster and has lower pauses.
Marksweep + semispace
A non concurrent, copying GC used for heap transitions as well as homogeneous space compaction (to defragement the heap).
Objects freed
The number of objects which were reclaimed from this GC from the non large object space.
Size freed
The number of bytes which were reclaimed from this GC from the non large object space.
Large objects freed
The number of object in the large object space which were reclaimed from this garbage collection.
Large object size freed
The number of bytes in the large object space which were reclaimed from this garbage collection.
Heap stats
Percentage free and (number of live objects)/(total heap size).
Pause times
In general pause times are proportional to the number of object references which were modified while the GC was running. Currently, the ART CMS GCs only has one pause, near the end of the GC. The moving GCs have a long pause which lasts for the majority of the GC duration.

If you are seeing a large amount of GCs in logcat, look for increases in the heap stats (the 25MB/38MB value in the above example). If this value continues to increase and doesn't ever seem to get smaller, you could have a memory leak. Alternatively, if you are seeing GC which are for the reason "Alloc", then you are already operating near your heap capacity and can expect OOM exceptions in the near future.

Viewing Heap Updates

To get a little information about what kind of memory your app is using and when, you can view real-time updates to your app's heap in Android Studio'sHPROF viewer or in the Device Monitor:

Memory Monitor in Android Studio

Use Android Studio to view your app's memory use:

  1. Start your app on a connected device or emulator.
  2. Open the Android run-time window, and view the free and allocated memory in the Memory Monitor.
  3. Click the Dump Java Heap icon ( [image] ) in the Memory Monitor toolbar.

    Android Studio creates the heap snapshot file with the filename Snapshot-yyyy.mm.dd-hh.mm.ss.hprof in the Captures tab.

  4. Double-click the heap snapshot file to open the HPROF viewer.

    Note: To convert a heap dump to standard HPROF format in Android Studio, right-click a heap snapshot in the Captures view and select Export to standard .hprof.

  5. Interact with your app and click the ( [image] ) icon to cause heap allocation.
  6. Identify which actions in your app are likely causing too much allocation and determine where in your app you should try to reduce allocations and release resources.

Device Monitor

  1. Open the Device Monitor.

    From your <sdk>/tools/ directory, launch the monitor tool.

  2. In the Debug Monitor window, select your app's process from the list on the left.
  3. Click Update Heap above the process list.
  4. In the right-side panel, select the Heap tab.

The Heap view shows some basic stats about your heap memory usage, updated after every GC. To see the first update, click the Cause GC button.

Figure 1. The Device Monitor tool, showing the [1] Update Heap and [2] Cause GC buttons. The Heap tab on the right shows the heap results.

Continue interacting with your app to watch your heap allocation update with each garbage collection. This can help you identify which actions in your app are likely causing too much allocation and where you should try to reduce allocations and release resources.

Tracking Allocations

As you start narrowing down memory issues, you should also use the Allocation Tracker to get a better understanding of where your memory-hogging objects are allocated. The Allocation Tracker can be useful not only for looking at specific uses of memory, but also to analyze critical code paths in an app such as scrolling.

For example, tracking allocations when flinging a list in your app allows you to see all the allocations that need to be done for that behavior, what thread they are on, and where they came from. This is extremely valuable for tightening up these paths to reduce the work they need and improve the overall smoothness of the UI.

To use the Allocation Tracker, open the Memory Monitor in Android Studio and click the Allocation Tracker icon. You can also track allocations in the Android Device Monitor:

Android Studio

To use the Allocation Tracker in Android Studio:

  1. Start your app on a connected device or emulator
  2. Open the Android run-tme window, and view the free and allocated memory in the Memory Monitor.
  3. Click the Allocation Tracker icon ( [image] ) in the Memory Monitor tool bar to start and stop memory allocations.

    Android Studio creates the allocation file with the filename Allocations-yyyy.mm.dd-hh.mm.ss.alloc in the Captures tab.

  4. Double-click the allocation file to open the Allocation viewer.
  5. Identify which actions in your app are likely causing too much allocation and determine where in your app you should try to reduce allocations and release resources.

Device Monitor

  1. Open the Device Monitor.

    From your <sdk>/tools/ directory, launch the monitor tool.

  2. In the DDMS window, select your app's process in the left-side panel.
  3. In the right-side panel, select the Allocation Tracker tab.
  4. Click Start Tracking.
  5. Interact with your app to execute the code paths you want to analyze.
  6. Click Get Allocations every time you want to update the list of allocations.

The list shows all recent allocations, currently limited by a 512-entry ring buffer. Click on a line to see the stack trace that led to the allocation. The trace shows you not only what type of object was allocated, but also in which thread, in which class, in which file and at which line.

Figure 2. The Device Monitor tool, showing recent app allocations and stack traces in the Allocation Tracker.

Note: You will always see some allocations from DdmVmInternal and elsewhere that come from the allocation tracker itself.

Although it's not necessary (nor possible) to remove all allocations from your performance critical code paths, the allocation tracker can help you identify important issues in your code. For instance, some apps might create a new Paint object on every draw. Moving that object into a global member is a simple fix that helps improve performance.

Viewing Overall Memory Allocations

For further analysis, you may want to observe how your app's memory is divided between different types of RAM allocation with the following adbcommand:

adb shell dumpsys meminfo <package_name|pid> [-d]

The -d flag prints more info related to Dalvik and ART memory usage.

The output lists all of your app's current allocations, measured in kilobytes.

When inspecting this information, you should be familiar with the following types of allocation:

Private (Clean and Dirty) RAM
This is memory that is being used by only your process. This is the bulk of the RAM that the system can reclaim when your app’s process is destroyed. Generally, the most important portion of this is “private dirty” RAM, which is the most expensive because it is used by only your process and its contents exist only in RAM so can’t be paged to storage (because Android does not use swap). All Dalvik and native heap allocations you make will be private dirty RAM; Dalvik and native allocations you share with the Zygote process are shared dirty RAM.
Proportional Set Size (PSS)
This is a measurement of your app’s RAM use that takes into account sharing pages across processes. Any RAM pages that are unique to your process directly contribute to its PSS value, while pages that are shared with other processes contribute to the PSS value only in proportion to the amount of sharing. For example, a page that is shared between two processes will contribute half of its size to the PSS of each process.

A nice characteristic of the PSS measurement is that you can add up the PSS across all processes to determine the actual memory being used by all processes. This means PSS is a good measure for the actual RAM weight of a process and for comparison against the RAM use of other processes and the total available RAM.

For example, below is the the output for Map’s process on a Nexus 5 device. There is a lot of information here, but key points for discussion are listed below.

adb shell dumpsys meminfo com.google.android.apps.maps -d

Note: The information you see may vary slightly from what is shown here, as some details of the output differ across platform versions.

** MEMINFO in pid 18227 [com.google.android.apps.maps] **
                   Pss  Private  Private  Swapped     Heap     Heap     Heap
                 Total    Dirty    Clean    Dirty     Size    Alloc     Free
                ------   ------   ------   ------   ------   ------   ------
  Native Heap    10468    10408        0        0    20480    14462     6017
  Dalvik Heap    34340    33816        0        0    62436    53883     8553
 Dalvik Other      972      972        0        0
        Stack     1144     1144        0        0
      Gfx dev    35300    35300        0        0
    Other dev        5        0        4        0
     .so mmap     1943      504      188        0
    .apk mmap      598        0      136        0
    .ttf mmap      134        0       68        0
    .dex mmap     3908        0     3904        0
    .oat mmap     1344        0       56        0
    .art mmap     2037     1784       28        0
   Other mmap       30        4        0        0
   EGL mtrack    73072    73072        0        0
    GL mtrack    51044    51044        0        0
      Unknown      185      184        0        0
        TOTAL   216524   208232     4384        0    82916    68345    14570

 Dalvik Details
        .Heap     6568     6568        0        0
         .LOS    24771    24404        0        0
          .GC      500      500        0        0
    .JITCache      428      428        0        0
      .Zygote     1093      936        0        0
   .NonMoving     1908     1908        0        0
 .IndirectRef       44       44        0        0

 Objects
               Views:       90         ViewRootImpl:        1
         AppContexts:        4           Activities:        1
              Assets:        2        AssetManagers:        2
       Local Binders:       21        Proxy Binders:       28
       Parcel memory:       18         Parcel count:       74
    Death Recipients:        2      OpenSSL Sockets:        2

Here is an older dumpsys on Dalvik of the gmail app:

** MEMINFO in pid 9953 [com.google.android.gm] **
                 Pss     Pss  Shared Private  Shared Private    Heap    Heap    Heap
               Total   Clean   Dirty   Dirty   Clean   Clean    Size   Alloc    Free
              ------  ------  ------  ------  ------  ------  ------  ------  ------
  Native Heap      0       0       0       0       0       0    7800    7637(6)  126
  Dalvik Heap   5110(3)    0    4136    4988(3)    0       0    9168    8958(6)  210
 Dalvik Other   2850       0    2684    2772       0       0
        Stack     36       0       8      36       0       0
       Cursor    136       0       0     136       0       0
       Ashmem     12       0      28       0       0       0
    Other dev    380       0      24     376       0       4
     .so mmap   5443(5) 1996    2584    2664(5) 5788    1996(5)
    .apk mmap    235      32       0       0    1252      32
    .ttf mmap     36      12       0       0      88      12
    .dex mmap   3019(5) 2148       0       0    8936    2148(5)
   Other mmap    107       0       8       8     324      68
      Unknown   6994(4)    0     252    6992(4)    0       0
        TOTAL  24358(1) 4188    9724   17972(2)16388    4260(2)16968   16595     336

 Objects
               Views:    426         ViewRootImpl:        3(8)
         AppContexts:      6(7)        Activities:        2(7)
              Assets:      2        AssetManagers:        2
       Local Binders:     64        Proxy Binders:       34
    Death Recipients:      0
     OpenSSL Sockets:      1

 SQL
         MEMORY_USED:   1739
  PAGECACHE_OVERFLOW:   1164          MALLOC_SIZE:       62

Generally, you should be concerned with only the Pss Total and Private Dirty columns. In some cases, the Private Clean and Heap Alloc columns also offer interesting data. Here is some more information about the different memory allocations (the rows) you should observe:

Dalvik Heap
The RAM used by Dalvik allocations in your app. The Pss Total includes all Zygote allocations (weighted by their sharing across processes, as described in the PSS definition above). The Private Dirty number is the actual RAM committed to only your app’s heap, composed of your own allocations and any Zygote allocation pages that have been modified since forking your app’s process from Zygote.

Note: On newer platform versions that have the Dalvik Other section, the Pss Total and Private Dirty numbers for Dalvik Heap do not include Dalvik overhead such as the just-in-time compilation (JIT) and GC bookkeeping, whereas older versions list it all combined underDalvik.

The Heap Alloc is the amount of memory that the Dalvik and native heap allocators keep track of for your app. This value is larger than Pss Totaland Private Dirty because your process was forked from Zygote and it includes allocations that your process shares with all the others.

.so mmap and .dex mmap
The RAM being used for mapped .so (native) and .dex (Dalvik or ART) code. The Pss Total number includes platform code shared across apps; the Private Clean is your app’s own code. Generally, the actual mapped size will be much larger—the RAM here is only what currently needs to be in RAM for code that has been executed by the app. However, the .so mmap has a large private dirty, which is due to fix-ups to the native code when it was loaded into its final address.
.oat mmap
This is the amount of RAM used by the code image which is based off of the preloaded classes which are commonly used by multiple apps. This image is shared across all apps and is unaffected by particular apps.
.art mmap
This is the amount of RAM used by the heap image which is based off of the preloaded classes which are commonly used by multiple apps. This image is shared across all apps and is unaffected by particular apps. Even though the ART image contains Object instances, it does not count towards your heap size.
.Heap (only with -d flag)
This is the amount of heap memory for your app. This excludes objects in the image and large object spaces, but includes the zygote space and non-moving space.
.LOS (only with -d flag)
This is the amount of RAM used by the ART large object space. This includes zygote large objects. Large objects are all primitive array allocations larger than 12KB.
.GC (only with -d flag)
This is the amount of internal GC accounting overhead for your app. There is not really any way to reduce this overhead.
.JITCache (only with -d flag)
This is the amount of memory used by the JIT data and code caches. Typically, this is zero since all of the apps will be compiled at installed time.
.Zygote (only with -d flag)
This is the amount of memory used by the zygote space. The zygote space is created during device startup and is never allocated into.
.NonMoving (only with -d flag)
This is the amount of RAM used by the ART non-moving space. The non-moving space contains special non-movable objects such as fields and methods. You can reduce this section by using fewer fields and methods in your app.
.IndirectRef (only with -d flag)
This is the amount of RAM used by the ART indirect reference tables. Usually this amount is small, but if it is too high, it may be possible to reduce it by reducing the number of local and global JNI references used.
Unknown
Any RAM pages that the system could not classify into one of the other more specific items. Currently, this contains mostly native allocations, which cannot be identified by the tool when collecting this data due to Address Space Layout Randomization (ASLR). As with the Dalvik heap, thePss Total for Unknown takes into account sharing with Zygote, and Private Dirty is unknown RAM dedicated to only your app.
TOTAL
The total Proportional Set Size (PSS) RAM used by your process. This is the sum of all PSS fields above it. It indicates the overall memory weight of your process, which can be directly compared with other processes and the total available RAM.

The Private Dirty and Private Clean are the total allocations within your process, which are not shared with other processes. Together (especially Private Dirty), this is the amount of RAM that will be released back to the system when your process is destroyed. Dirty RAM is pages that have been modified and so must stay committed to RAM (because there is no swap); clean RAM is pages that have been mapped from a persistent file (such as code being executed) and so can be paged out if not used for a while.

ViewRootImpl
The number of root views that are active in your process. Each root view is associated with a window, so this can help you identify memory leaks involving dialogs or other windows.
AppContexts and Activities
The number of app Context and Activity objects that currently live in your process. This can be useful to quickly identify leaked Activity objects that can’t be garbage collected due to static references on them, which is common. These objects often have a lot of other allocations associated with them and so are a good way to track large memory leaks.

Note: A View or Drawable object also holds a reference to the Activity that it's from, so holding a View or Drawable object can also lead to your app leaking an Activity.

Capturing a Heap Dump

A heap dump is a snapshot of all the objects in your app's heap, stored in a binary format called HPROF. Your app's heap dump provides information about the overall state of your app's heap so you can track down problems you might have identified while viewing heap updates.

To retrieve your heap dump from within Android Studio, use the Memory Monitor and HPROF viewer.

You can also still perform these procedures in the Android monitor:

  1. Open the Device Monitor.

    From your <sdk>/tools/ directory, launch the monitor tool.

  2. In the DDMS window, select your app's process in the left-side panel.
  3. Click Dump HPROF file, shown in figure 3.
  4. In the window that appears, name your HPROF file, select the save location, then click Save.

Figure 3. The Device Monitor tool, showing the [1] Dump HPROF file button.

If you need to be more precise about when the dump is created, you can also create a heap dump at the critical point in your app code by callingdumpHprofData().

The heap dump is provided in a format that's similar to, but not identical to one from the Java HPROF tool. The major difference in an Android heap dump is due to the fact that there are a large number of allocations in the Zygote process. But because the Zygote allocations are shared across all app processes, they don’t matter very much to your own heap analysis.

To analyze your heap dump, you can use Memory Monitor in Android Studio. You can also use a standard tool like jhat. However, first you'll need to convert the HPROF file from Android's format to the J2SE HPROF format. You can do this using the hprof-conv tool provided in the <sdk>/platform-tools/ directory. Simply run the hprof-conv command with two arguments: the original HPROF file and the location to write the converted HPROF file. For example:

hprof-conv heap-original.hprof heap-converted.hprof

You can now load the converted file into a heap analysis tool that understands the J2SE HPROF format.

When analyzing your heap, you should look for memory leaks caused by:

  • Long-lived references to an Activity, Context, View, Drawable, and other objects that may hold a reference to the container Activity or Context.
  • Non-static inner classes (such as a Runnable, which can hold the Activity instance).
  • Caches that hold objects longer than necessary.

Triggering Memory Leaks

While using the tools described above, you should aggressively stress your app code and try forcing memory leaks. One way to provoke memory leaks in your app is to let it run for a while before inspecting the heap. Leaks will trickle up to the top of the allocations in the heap. However, the smaller the leak, the longer you need to run the app in order to see it.

You can also trigger a memory leak in one of the following ways:

  1. Rotate the device from portrait to landscape and back again multiple times while in different activity states. Rotating the device can often cause an app to leak an Activity, Context, or View object because the system recreates the Activity and if your app holds a reference to one of those objects somewhere else, the system can't garbage collect it.
  2. Switch between your app and another app while in different activity states (navigate to the Home screen, then return to your app).

Tip: You can also perform the above steps by using the "monkey" test framework. For more information on running the monkey test framework, read the monkeyrunner documentation.

来源： https://developer.android.com/studio/profile/investigate-ram.html


CPU Monitor

  1. Displaying a Running App in the CPU Monitor
  2. Recording Call Stack Changes

Android Monitor includes a CPU Monitor lets you easily monitor the central processing unit (CPU) usage of your app. It displays CPU usage in real time and displays the percentage of total CPU time (including all cores) used in user and kernel mode. In user mode, the code must use system APIs to access hardware or memory, has access to virtual memory addresses only, and crashes are usually recoverable. In kernel mode, the code can directly access hardware, including physical memory addresses; crashes halt the device.

Displaying a Running App in the CPU Monitor

To display an app running on a particular device or emulator in the CPU Monitor:

  1. Meet the prerequisites and dependencies.
  2. Open an app project.
  3. Run the app on a hardware device or emulator.
  4. Display Android Monitor.
  5. Click the Monitors tab and display the CPU Monitor.
  6. Enable the CPU Monitor by clicking Pause [image] to deselect it.

    7. The CPU Monitor starts to display any CPU usage. In the graph, the y-axis displays the percentage of CPU used. The x-axis records the time elapsed and starts with seconds, and then minutes and seconds, and so on.

  7. To stop the CPU Monitor, click Pause [image] again to select it.

Recording Call Stack Changes

You can capture a record of the changes on the call stack during a particular time period while the CPU Monitor is running. For more information, seeMethod Trace.

来源： https://developer.android.com/studio/profile/am-cpu.html


Track Network Use with the Network Monitor

Network Monitor

  1. Displaying a Running App in the Network Monitor

Video

  1. Battery Drain and Networking

Android Monitor includes a Network Monitor that makes it possible to track when your application is making network requests. Using this tool, you can monitor how and when your app transfers data, and optimize the underlying code appropriately.

By monitoring the frequency of data transfers, and the amount of data transferred during each connection, you can identify areas of your app that can be made more efficient and use less battery power. Generally, you should look for short spikes that can be delayed, or that could cause a later transfer to be preempted.

Displaying a Running App in the Network Monitor

To display an app running on a particular device in the Network Monitor:

  1. Meet the prerequisites and dependencies.

    2. Connect a hardware device; the Network Monitor doesn't monitor an emulator.

  2. Open an app project.
  3. Run the app on the hardware device.
  4. Display Android Monitor.
  5. Click the Monitors tab and display the Network Monitor.
  6. Enable the Network Monitor by clicking Pause [image] to deselect it.

    7. Any network traffic begins to appear in the Network Monitor:

    The Network Monitor adds up the amount of time it takes for the device to transmit and receive kilobytes of data. The y-axis is in kilobytes per second. The x-axis starts with seconds, and then minutes and seconds, and so on.

  7. To stop the Network Monitor, click Pause [image] again to select it.

    来源： https://developer.android.com/studio/profile/am-network.html


Analyze the Java Heap with the HPROF Viewer and Analyzer

HPROF Viewer and Analyzer

  1. Why Look at the Java Heap?
  2. Understanding the HPROF Viewer Display
  3. Taking a Snapshot of the Java Heap
  4. Viewing a Saved HPROF File
  5. Diving into Heap Dump Data in the HPROF Viewer
  6. Analyzing Heap Dump Data in the HPROF Analyzer
  7. Sorting Heap Dump Data
  8. Displaying Java Source
  9. Working with HPROF Files

See also

  1. Managing Your App's Memory
  2. Addressing Garbage Collection Issues
  3. Investigating Your RAM Usage

When you're monitoring memory usage in the Memory Monitor included in Android Monitor you can, at the same time, dump a snapshot of the Java heap to an Android-specific Heap/CPU Profiling (HPROF) file. The HPROF Viewer displays classes, instances of each class, and a reference tree to help you track memory usage and find memory leaks. HPROF is a binary heap dump format originally supported by J2SE.

Why Look at the Java Heap?

The Java heap display does the following:

  • Shows snapshots of a number of objects allocated by type.
  • Samples data every time a garbage collection event occurs naturally or is triggered by you.
  • Helps identify which object types might be involved in memory leaks.

However, you have to look for changes over time yourself by tracking what's happening in the graph.

The HPROF Analyzer finds the following potential issues:

  • All destroyed activity instances that are reachable from garbage collection roots.
  • Where the target program has strings that repeat values.

A dominator is at the top of a tree. If you remove it, you also remove the branches of the tree it dominates, so it’s a potential way to free memory.

Understanding the HPROF Viewer Display

The HPROF Viewer looks similar to the following figure:

The tool displays the following information:

Column | Description
Class Name | The Java class responsible for the memory.
Total Count | Total number of instances outstanding.
Heap Count | Number of instances in the selected heap.
Sizeof | Size of the instances (currently, 0 if the size is variable).
Shallow Size | Total size of all instances in this heap.
Retained Size | Size of memory that all instances of this class is dominating.
Instance | A specific instance of the class.
Reference Tree | References that point to the selected instance, as well as references pointing to the references.
Depth | The shortest number of hops from any GC root to the selected instance.
Shallow Size | Size of this instance.
Dominating Size | Size of memory that this instance is dominating.

If you click Analyzer Tasks, the HPROF Analyzer appears:

You can detect leaked activities and find duplicate strings with the HPROF Analyzer.

Taking and Displaying a Snapshot of the Java Heap

To examine a snapshot of the Java heap:

  1. Display a running app in the Memory Monitor.
  2. Click Dump Java Heap [image] .

    3. When the icon on the Memory Monitor display changes from [image] to [image] , the file is ready. Android Studio creates the heap snapshot file with the filename package_yyyy.mm.dd_hh.mm.ss.hprof using the activity package (or project) name, year, month, day, hour, minute, and second of the capture, for example, com.android.calc_2015.11.17_14.58.48.hprof.

    The HPROF Viewer appears.

Viewing a Saved HPROF File

After you do a heap dump, Android Studio automatically stores it so you can view it again.

To view an HPROF file in the HPROF Viewer:

  1. Click [image] in the main window.

    2. Or select View > Tools Windows > Captures.

    The Captures window appears.

  2. Open the Heap Snapshot folder.
  3. Double-click the file to view it in the HPROF Viewer.

    4. The HPROF Viewer appears.

  4. Select the Heap menu option you want to display:
    • App heap - The heap used by the current app.
    • Image heap - The memory mapped copy of the current app on disk.
    • Zygote heap - The common set of libraries and runtime classes and data that all apps are forked from. The zygote space is created during device startup and is never allocated into.
  5. Select the View menu option you want to display:
    • Class List View
    • Package Tree View

Diving into Heap Dump Data in the HPROF Viewer

The following steps outline the typical workflow:

  1. In the HPROF Viewer, select a class name.
  2. Select an instance of that class.
  3. Examine the reference tree.
  4. Right-click an item to Jump to source or Go to instance, as needed.

Analyzing Heap Dump Data in the HPROF Analyzer

You can detect leaked activities and find duplicate strings with the HPROF Analyzer.

To use the HPROF Analyzer:

  1. In the Captures window, double-click an .hprof file to display it in the HPROF Viewer.
  2. Click Analyzer Tasks on the right side of the main Android Studio window.

    3. The HPROF Analyzer appears to the right of the HPROF Analyzer, by default.

  3. In the Analyzer Tasks list, select the items you want to find.
  4. Click Perform Analysis [image] .
  5. Examine the items in Analysis Results. Click an item to display it in the HPROF Viewer.

Sorting Heap Dump Data

To sort heap dump data:

  • In the HPROF Viewer, click a column heading to sort the table by ascending or descending order.

Displaying Java Source

For some items displayed in the HPROF Viewer, you can go straight to its source code.

To display Java source:

  • In the HPROF Viewer, right-click a class, instance, or item in the reference tree, and then select Jump to Source.

    • The source code appears in the Code Editor.

Working with HPROF Files

You can rename, locate, and delete an HPROF file from within Android Studio. You can also convert it to standard HPROF format to use with other analysis tools.

Renaming an HPROF file

If you rename a file from within Android Studio, it continues to appear in the Captures window.

To rename an HPROF file:

  1. In the Captures window, right-click the file and select Rename.
  2. In the dialog, specify the name of the file and click OK.

Locating a heap dump file on disk

You can quickly discover where Android Studio stored HPROF files on disk.

To locate an HPROF file on disk:

  • In the Captures window, right-click a heap snapshot file and select Show or Reveal.

    • Android Studio opens an operating system file browser displaying the location where the file resides.

Note: If you move an HPROF file, Android Studio no longer displays it in the Captures window. To display it, use File > Open. Also, if you want to rename the file, do it from the Captures window and not in the operating system file browser.

Deleting a heap dump file

To delete a heap dump file:

  • In the Captures window, right-click a heap snapshot file and select Delete.

    • Android Studio deletes the file from the Captures dialog and from disk.

Converting a heap dump file to standard HPROF format

You can convert an HPROF file to standard format so you can use it outside of Android Studio with other analysis tools.

To convert an HPROF file:

  1. In the Captures window, right-click a heap snapshot file and select Export to standard .hprof.
  2. In the Convert Android Java Heap Dump dialog, specify a filename and click OK.

    3. Android Studio creates a binary HPROF file in the location you specified.

    来源： https://developer.android.com/studio/profile/am-hprof.html


Improve Memory Allocation with the Allocation Tracker

Allocation Tracker

  1. Understanding the Allocation Tracker Display
  2. Taking and Displaying a Snapshot of Allocation Data
  3. Viewing a Saved Allocation Tracking File
  4. Sorting Allocation Data
  5. Displaying Java Source
  6. Working with Allocation Tracking Files

See also

  1. Managing Your App's Memory
  2. Addressing Garbage Collection Issues
  3. Investigating Your RAM Usage

Android Monitor allows you to track memory allocation as it monitors memory use. Tracking memory allocation allows you to monitor where objects are being allocated when you perform certain actions. Knowing these allocations enables you to adjust the method calls related to those actions to optimize app performance and memory use.

The Allocation Tracker does the following:

  • Shows when and where your code allocates object types, their size, allocating thread, and stack traces.
  • Helps recognize memory churn through recurring allocation/deallocation patterns.
  • Helps you track down memory leaks when used in combination with the HPROF Viewer. For example, if you see a bitmap object resident on the heap, you can find its allocation location with Allocation Tracker.

However, it takes time and experience to learn to interpret the output from this tool.

Understanding the Allocation Tracker Display

The Allocation Tracker looks similar to the following figure:

The tool displays the following information:

Column | Description
Method | The Java method responsible for the allocation.
Count | Total number of instances allocated.
Size | The total amount of allocated memory in bytes.

Taking and Displaying a Snapshot of Allocation Data

To examine allocation data:

  1. Display a running app in the Memory Monitor.
  2. Click Start Allocation Tracking [image] .
  3. Click Start Allocation Tracking [image] again to deselect it and end the snapshot.

    4. The Memory Monitor displays the period when it took the snapshot. In the following figure, you can see the snapshot period, as shown on the left. By comparison, when you dump the Java heap, the Memory Monitor displays just the point where the heap snapshot was taken, as shown on the right.

    Android Studio creates the heap snapshot file with the filename package_yyyy.mm.dd_hh.mm.ss.alloc using the activity package (or project) name, year, month, day, hour, minute, and second of the capture, for example, com.android.calc_2015.11.17_14.58.48.alloc.

    The Allocation Tracker appears.

  4. Optionally click the graphic icon [image] to display a visual representation of the data.
  5. Select the Group By menu option you want to display:
    • Group by Allocator
    • Group by Method

Viewing a Saved Allocation Tracking File

After you capture allocation data, Android Studio automatically stores it so you can view it again.

To view an allocation tracking file in the Allocation Tracker:

  1. Click [image] in the main window.

    2. Or select View > Tools Windows > Captures.

    The Captures window appears.

  2. Open the Allocation Tracking folder.
  3. Double-click the file to view it.

Sorting Allocation Data

To sort allocation data:

  • In the Allocation Tracker, click a column heading to sort the table by ascending or descending order.

Displaying Java Source

For some items displayed in the Allocation Tracker, you can view the Java source.

To display Java source:

  • In the Allocation Tracker, right-click a method and then select Jump to Source.
  • In the Allocation Tracker, select a method and then click Jump to Source [image] .

The source code appears in the Code Editor.

Working with Allocation Tracking Files

You can rename, locate, and delete an allocation tracking file from within Android Studio.

Renaming an allocation tracking file

If you rename a file from within Android Studio, it continues to appear in the Captures window.

To rename an allocation tracking file:

  1. In the Captures window, right-click the file and select Rename.
  2. In the Rename dialog, specify the name of the file and click OK.

Locating an allocation tracking file

You can quickly discover where Android Studio stored allocation tracking files on disk.

To locate an allocation tracking file from Android Studio:

  • In the Captures window, right-click allocation file and select Show or Reveal.

    • Android Studio opens an operating system file browser displaying the location where the file resides.

Note: If you move an allocation tracking file, Android Studio no longer displays it in the Captures window. To display the file, use File > Open. Also, rename the file from the Captures window and not in the operating system file browser.

Deleting an allocation tracking file

To delete an allocation tracking file:

  • In the Captures window, right-click an allocation tracking file and select Delete.

    • Android Studio deletes the file from the Captures dialog and from disk.

    来源： https://developer.android.com/studio/profile/am-allocation.html


Study the Call Stack with the Method Tracer

Method Tracer

  1. Understanding the Method Trace Display
  2. Performing a Method Trace in the CPU Monitor
  3. Viewing a Saved Method Trace
  4. Sorting Method Trace Data
  5. Working with Method Trace Files

You can start a method trace from the CPU Monitor included with Android Monitor. It lets you view the call stack and timing information for your app. This information can help you optimize and debug your app.

Understanding the Method Trace Display

The method trace looks similar to the following figure:

The display shows the following information:

Field | Description
Name | The name of the method.
Invocation Count | How many times the method was called.
Inclusive Time (microseconds) | Time spent in the method and all of its children, either wall clock or thread time, depending on your selection in the x-axis menu.
Exclusive Time (microseconds) | Time spent just in the method (excluding time spent in its children), either wall clock or thread time, depending on your selection in the x-axis menu.

Note: Running the method trace significantly affects CPU timings. Use the method trace to understand the flow of the program, but not for performance timings.

Performing a Method Trace in the CPU Monitor

To perform a method trace:

  1. Display a running app in the CPU Monitor.
  2. Start a trace by clicking Start Method Tracing [image] to select it.
  3. To stop the trace, click Stop Method Tracing [image] to deselect it.

    4. The method trace appears in the Code Editor area.

    Android Studio creates the method trace file with the filename package_yyyy.mm.dd_hh.mm.ss.trace using the activity package (or project) name, year, month, day, hour, minute, and second of the capture, for example, com.android.calc_2015.11.17_14.58.48.trace.

  4. Specify display options:
    • Select a Thread.
    • Select an x-axis time for the graphic and the method list:
      • Wall Clock Time - Total CPU time elapsed between the method call and return.
      • Thread Time - Total time during which the JRE scheduled the thread during call processing. It’s less than or equal to the Wall Clock Time: less if the JRE interrupted the thread, and equal if it didn’t. The thread might not run continuously; when it’s not executing, that time is excluded. If threads are interrupted often and it’s not by design, the interruptions affect app performance. However, an example of a by-design use is synchronous operations that take a long time, such as file transfers and reads from disk, where the method could be the asynchronous wrapper for the synchronous reader.
    • Optionally select Color by inclusive time.

    The graphic represents the wall clock or thread time for each method. Hover the cursor over the display to receive information about the method. This information also appears in the table.

Viewing a Saved Method Trace

After you do a method trace, Android Studio automatically stores it so you can view it again.

To examine a saved method trace:

  1. Click [image] in the main window.

    2. Or select View > Tools Windows > Captures.

    The Captures window appears.

  2. Open the Methods Tracing folder.
  3. Double-click the file to view it.

Sorting Method Trace Data

You can sort the data by method name, count, inclusive time, and exclusive time.

To sort method trace data:

  • Click a column heading to sort the table by ascending or descending order.

Working with Method Trace Files

You can rename, locate, and delete a method trace file from within Android Studio.

Renaming a method trace file

Rename a method trace file from within Android Studio so it continues to appear in the Captures window.

To rename a method trace file:

  1. In the Captures window, right-click the file and select Rename.
  2. In the dialog, specify the name of the file and click OK.

Locating a method trace file on disk

You can quickly discover where Android Studio stored method trace files on disk.

To locate a method trace file on disk:

  • In the Captures window, right-click a method trace file and select Show or Reveal.

    • Android Studio opens an operating system file browser displaying the location where the file resides.

Note: If you move a method trace file, Android Studio no longer displays the file in the Captures window. To display it, use File > Open. Also, rename a file from the Captures window and not in the operating system file browser.

Deleting a method trace file

To delete a method trace file:

  • In the Captures window, right-click a method trace file and select Delete.

Android Studio deletes the file from the Captures dialog and from disk.

来源： https://developer.android.com/studio/profile/am-methodtrace.html


Evaluate dumpsys System Information

System Information

  1. Examining System Information for a Running App
  2. Viewing Saved System Information
  3. Working with System Information Files

You can capture dumpsys output from within Android Monitor and display the file in the Code Editor. TheCaptures window lists the system information files so you can retrieve the information later for analysis.

Examining System Information for a Running App

To capture and view a snapshot of system information:

  1. Meet the prerequisites and dependencies.
  2. Open an app project.
  3. Run the app on a hardware device or emulator.
  4. Display Android Monitor.
  5. In the toolbar of the Android Monitor main window, click System Information [image] and then select a menu item.

    6. The menu items display different types of dumpsys output:

    • Activity Manager State - dumpsys activity
    • Package Information - dumpsys package
    • Memory Usage - dumpsys meminfo
    • Memory Use Over Time - dumpsys procstats
    • Graphics State - dumpsys gfxinfo

    The information appears in an editable text file in the Code Editor.

    Android Studio creates the system information file with the filename package_yyyy.mm.dd_hh.mm.ss.txt using the activity package (or project) name, year, month, day, hour, minute, and second of the capture, for example, com.android.calc_2015.11.17_14.58.48.txt.

Viewing Saved System Information

After you take a snapshot of system information, Android Studio automatically stores it so you can view it again.

To examine a saved system information file:

  1. Click [image] in the main window.

    2. Or select View > Tools Windows > Captures.

    The Captures window appears.

  2. Open the System Information folder.
  3. Double-click the file to view it.

Working with System Information Files

You can rename, locate, and delete a system information file from within Android Studio.

Renaming a system information file

Rename a system information file from within Android Studio so it continues to appear in the Captures window.

To rename a system information file:

  1. In the Captures window, right-click the file and select Rename.
  2. In the dialog, specify the name of the file and click OK.

Locating a system information file on disk

You can quickly discover where Android Studio stored system information files on disk.

To locate a system information file on disk:

  • In the Captures window, right-click a system information file and select Show or Reveal.

    • Android Studio opens an operating system file browser displaying the location where the file resides.

Note: If you move a system information file, Android Studio no longer displays the file in the Captures window. To display it, use File > Open. Also, rename a file from the Captures window and not in the operating system file browser.

Deleting a system information file

To delete a system information file:

  • In the Captures window, right-click a system information file and select Delete.

Android Studio deletes the file from the Captures dialog and from disk.

来源： https://developer.android.com/studio/profile/am-sysinfo.html


Publish Your App

Quickview

  • Learn how to publish Android apps.
  • Find out how to prepare apps for release.
  • Learn how to release apps to users.

In this document

  1. Preparing Your Application for Release
  2. Releasing Your Application to Users

See also

  1. Publishing on Google Play

Publishing is the general process that makes your Android applications available to users. When you publish an Android application you perform two main tasks:

  • You prepare the application for release.

    During the preparation step you build a release version of your application, which users can download and install on their Android-powered devices.

  • You release the application to users.

    During the release step you publicize, sell, and distribute the release version of your application to users.

Usually, you release your application through an application marketplace, such as Google Play. However, you can also release applications by sending them directly to users or by letting users download them from your own website.

The publishing process is typically performed after you finish testing your application in a debug environment. Also, as a best practice, your application should meet all of your release criteria for functionality, performance, and stability before you begin the publishing process.

Preparing Your Application for Release

Preparing your application for release is a multi-step process that involves the following tasks:

  • Configuring your application for release.

    At a minimum you need to remove Log calls and remove the android:debuggable attribute from your manifest file. You should also provide values for the android:versionCode and android:versionName attributes, which are located in the <manifest> element. You may also have to configure several other settings to meet Google Play requirements or accomodate whatever method you're using to release your application.

    If you are using Gradle build files, you can use the release build type to set your build settings for the published version of your app.

  • Building and signing a release version of your application.

    You can use the Gradle build files with the release build type to build and sign a release version of your application. See Building and Running from Android Studio.

  • Testing the release version of your application.

    Before you distribute your application, you should thoroughly test the release version on at least one target handset device and one target tablet device.

  • Updating application resources for release.

    You need to be sure that all application resources such as multimedia files and graphics are updated and included with your application or staged on the proper production servers.

  • Preparing remote servers and services that your application depends on.

    If your application depends on external servers or services, you need to be sure they are secure and production ready.

You may have to perform several other tasks as part of the preparation process. For example, you will need to get a private key for signing your application. You will also need to create an icon for your application, and you may want to prepare an End User License Agreement (EULA) to protect your person, organization, and intellectual property.

When you are finished preparing your application for release you will have a signed .apk file that you can distribute to users.

To learn how to prepare your application for release, see Preparing for Release in the Dev Guide. This topic provides step-by-step instructions for configuring and building a release version of your application.

Releasing Your Application to Users

You can release your Android applications several ways. Usually, you release applications through an application marketplace such as Google Play, but you can also release applications on your own website or by sending an application directly to a user.

Releasing through an App Marketplace

If you want to distribute your apps to the broadest possible audience, releasing through an app marketplace such as Google Play is ideal.

Google Play is the premier marketplace for Android apps and is particularly useful if you want to distribute your applications to a large global audience. However, you can distribute your apps through any app marketplace you want or you can use multiple marketplaces.

Releasing Your Applications on Google Play

Google Play is a robust publishing platform that helps you publicize, sell, and distribute your Android applications to users around the world. When you release your applications through Google Play you have access to a suite of developer tools that let you analyze your sales, identify market trends, and control who your applications are being distributed to. You also have access to several revenue-enhancing features such as in-app billing and application licensing. The rich array of tools and features, coupled with numerous end-user community features, makes Google Play the premier marketplace for selling and buying Android applications.

Releasing your application on Google Play is a simple process that involves three basic steps:

  • Preparing promotional materials.

    To fully leverage the marketing and publicity capabilities of Google Play, you need to create promotional materials for your application, such as screenshots, videos, graphics, and promotional text.

  • Configuring options and uploading assets.

    Google Play lets you target your application to a worldwide pool of users and devices. By configuring various Google Play settings, you can choose the countries you want to reach, the listing languages you want to use, and the price you want to charge in each country. You can also configure listing details such as the application type, category, and content rating. When you are done configuring options you can upload your promotional materials and your application as a draft (unpublished) application.

  • Publishing the release version of your application.

    If you are satisfied that your publishing settings are correctly configured and your uploaded application is ready to be released to the public, you can simply click Publish in the developer console and within minutes your application will be live and available for download around the world.

For information complete information, see Google Play.

Releasing your application through email

Figure 1. Users can simply click Installwhen you send them an application via email.

The easiest and quickest way to release your application is to send it to a user through email. To do this, you prepare your application for release and then attach it to an email and send it to a user. When the user opens your email message on their Android-powered device the Android system will recognize the APK and display an Install Now button in the email message (see figure 1). Users can install your application by touching the button.

Note: The Install Now button shown in Figure 1 appears only if a user has configured their device to allow installation from unknown sources and has opened your email with the native Gmail application.

Distributing applications through email is convenient if you are sending your application to only a few trusted users, but it provides few protections from piracy and unauthorized distribution; that is, anyone you send your application to can simply forward it to someone else.

Releasing through a web site

If you do not want to release your app on a marketplace like Google Play, you can make the app available for download on your own website or server, including on a private or enterprise server. To do this, you must first prepare your application for release in the normal way. Then all you need to do is host the release-ready APK file on your website and provide a download link to users.

When users browse to the download link from their Android-powered devices, the file is downloaded and Android system automatically starts installing it on the device. However, the installation process will start automatically only if the user has configured their Settings to allow the installation of apps from unknown sources.

Although it is relatively easy to release your application on your own website, it can be inefficient. For example, if you want to monetize your application you will have to process and track all financial transactions yourself and you will not be able to use Google Play's In-app Billing service to sell in-app products. In addition, you will not be able to use the Licensing service to help prevent unauthorized installation and use of your application.

User Opt-In for Apps from Unknown Sources

Figure 2. Users must enable the Unknown sources setting before they can install apps not downloaded from Google Play.

Android protects users from inadvertent download and install of apps from locations other than Google Play (which is trusted). It blocks such installs until the user opts-in Unknown sources in Settings > Security, shown in Figure 2. To allow the installation of applications from other sources, users need to enable the Unknown sources setting on their devices, and they need to make this configuration change before they download your application to their devices.

Note that some network providers do not allow users to install applications from unknown sources.

来源： https://developer.android.com/studio/publish/index.html


Prepare for Release

Quickview

  • Learn which resources you'll need to release your app.
  • Find out how to configure and build your app for release.
  • Learn best practices for releasing your app.

In this document

  1. Introduction
  2. Gathering Materials and Resources
  3. Configuring Your Application
  4. Building Your Application
  5. Preparing External Servers and Resources
  6. Testing Your Application for Release

See also

  1. Publishing Overview
  2. Signing Your Applications
  3. Launch Checklist for Google Play

Before you distribute your Android application to users you need to prepare it for release. The preparation process is a required development task for all Android applications and is the first step in the publishing process (see figure 1).

When you prepare your application for release, you configure, build, and test a release version of your application. The configuration tasks are straightforward, involving basic code cleanup and code modification tasks that help optimize your application. The build process is similar to the debug build process and can be done using JDK and Android SDK tools. The testing tasks serve as a final check, ensuring that your application performs as expected under real-world conditions. When you are finished preparing your application for release you have a signed APK file, which you can distribute directly to users or distribute through an application marketplace such as Google Play.

This document summarizes the main tasks you need to perform to prepare your application for release. The tasks that are described in this document apply to all Android applications regardless how they are released or distributed to users. If you are releasing your application through Google Play, you should also readPublishing Checklist for Google Play to be sure your release-ready application satisfies all Google Play requirements.

Note: As a best practice, your application should meet all of your release criteria for functionality, performance, and stability before you perform the tasks outlined in this document.

Figure 1. Preparing for release is a required development task and is the first step in the publishing process.

Introduction

To release your application to users you need to create a release-ready package that users can install and run on their Android-powered devices. The release-ready package contains the same components as the debug APK file — compiled source code, resources, manifest file, and so on — and it is built using the same build tools. However, unlike the debug APK file, the release-ready APK file is signed with your own certificate and it is optimized with the zipalign tool.

Figure 2. You perform five main tasks to prepare your application for release.

The signing and optimization tasks are usually seamless if you are building your application with Android Studio. For example, you can use Android Studio with the Gradle build files to compile, sign, and optimize your application all at once. You can also configure the Gradle build files to do the same when you build from the command line. For more details about using the Gradle build files, see the Build System guide.

To prepare your application for release you typically perform five main tasks (see figure 2). Each main task may include one or more smaller tasks depending on how you are releasing your application. For example, if you are releasing your application through Google Play you may want to add special filtering rules to your manifest while you are configuring your application for release. Similarly, to meet Google Play publishing guidelines you may have to prepare screenshots and create promotional text while you are gathering materials for release.

You usually perform the tasks listed in figure 2 after you have throroughly debugged and tested your application. The Android SDK contains several tools to help you test and debug your Android applications. For more information, see the Debugging and Testing sections in the Dev Guide.

Gathering Materials and Resources

To begin preparing your application for release you need to gather several supporting items. At a minimum this includes cryptographic keys for signing your application and an application icon. You might also want to include an end-user license agreement.

Cryptographic keys

The Android system requires that each installed application be digitally signed with a certificate that is owned by the application's developer (that is, a certificate for which the developer holds the private key). The Android system uses the certificate as a means of identifying the author of an application and establishing trust relationships between applications. The certificate that you use for signing does not need to be signed by a certificate authority; the Android system allows you to sign your applications with a self-signed certificate. To learn about certificate requirements, see Signing Your Applications.

Important: Your application must be signed with a cryptographic key whose validity period ends after 22 October 2033.

You may also have to obtain other release keys if your application accesses a service or uses a third-party library that requires you to use a key that is based on your private key.

Application Icon

Be sure you have an application icon and that it meets the recommended icon guidelines. Your application's icon helps users identify your application on a device's Home screen and in the Launcher window. It also appears in Manage Applications, My Downloads, and elsewhere. In addition, publishing services such as Google Play display your icon to users.

Note: If you are releasing your application on Google Play, you need to create a high resolution version of your icon. See Graphic Assets for your Application for more information.

End-user License Agreement

Consider preparing an End User License Agreement (EULA) for your application. A EULA can help protect your person, organization, and intellectual property, and we recommend that you provide one with your application.

Miscellaneous Materials

You might also have to prepare promotional and marketing materials to publicize your application. For example, if you are releasing your application on Google Play you will need to prepare some promotional text and you will need to create screenshots of your application. For more information, seeGraphic Assets for your Application

Configuring Your Application for Release

After you gather all of your supporting materials you can start configuring your application for release. This section provides a summary of the configuration changes we recommend that you make to your source code, resource files, and application manifest prior to releasing your application. Although most of the configuration changes listed in this section are optional, they are considered good coding practices and we encourage you to implement them. In some cases, you may have already made these configuration changes as part of your development process.

Choose a good package name

Make sure you choose a package name that is suitable over the life of your application. You cannot change the package name after you distribute your application to users. You can set the package name in application's manifest file. For more information, see the package attribute documentation.

Turn off logging and debugging

Make sure you deactivate logging and disable the debugging option before you build your application for release. You can deactivate logging by removing calls to Log methods in your source files. You can disable debugging by removing the android:debuggable attribute from the <application> tag in your manifest file, or by setting the android:debuggable attribute to false in your manifest file. Also, remove any log files or static test files that were created in your project.

Also, you should remove all Debug tracing calls that you added to your code, such as startMethodTracing() and stopMethodTracing() method calls.

Important: Ensure that you disable debugging for your app if using WebView to display paid for content or if using JavaScript interfaces, since debugging allows users to inject scripts and extract content using Chrome DevTools. To disable debugging, use theWebView.setWebContentsDebuggingEnabled() method.

Clean up your project directories

Clean up your project and make sure it conforms to the directory structure described in Android Projects. Leaving stray or orphaned files in your project can prevent your application from compiling and cause your application to behave unpredictably. At a minimum you should do the following cleanup tasks:

  • Review the contents of your jni/, lib/, and src/ directories. The jni/ directory should contain only source files associated with the Android NDK, such as .c, .cpp, .h, and .mk files. The lib/ directory should contain only third-party library files or private library files, including prebuilt shared and static libraries (for example, .so files). The src/ directory should contain only the source files for your application (.java and .aidl files). The src/directory should not contain any .jar files.
  • Check your project for private or proprietary data files that your application does not use and remove them. For example, look in your project's res/directory for old drawable files, layout files, and values files that you are no longer using and delete them.
  • Check your lib/ directory for test libraries and remove them if they are no longer being used by your application.
  • Review the contents of your assets/ directory and your res/raw/ directory for raw asset files and static files that you need to update or remove prior to release.

Review and update your manifest and Gradle build settings

Verify that the following manifest and build files items are set correctly:

  • <uses-permission> element

    You should specify only those permissions that are relevant and required for your application.

  • android:icon and android:label attributes

    You must specify values for these attributes, which are located in the <application> element.

  • android:versionCode and android:versionName attributes.

    We recommend that you specify values for these attributes, which are located in the <manifest> element. For more information see Versioning your Application.

There are several additional manifest or build file elements that you can set if you are releasing your application on Google Play. For example, theandroid:minSdkVersion and android:targetSdkVersion attributes, which are located in the <uses-sdk> element. For more information about these and other Google Play settings, see Filters on Google Play.

Address compatibility issues

Android provides several tools and techniques to make your application compatible with a wide range of devices. To make your application available to the largest number of users, consider doing the following:

  • Add support for multiple screen configurations

    Make sure you meet the best practices for supporting multiple screens. By supporting multiple screen configurations you can create an application that functions properly and looks good on any of the screen sizes supported by Android.

  • Optimize your application for Android tablet devices.

    If your application is designed for devices older than Android 3.0, make it compatible with Android 3.0 devices by following the guidelines and best practices described in Optimizing Apps for Android 3.0 .

  • Consider using the Support Library

    If your application is designed for devices running Android 3.x, make your application compatible with older versions of Android by adding theSupport Library to your application project. The Support Library provides static support libraries that you can add to your Android application, which enables you to use APIs that are either not available on older platform versions or use utility APIs that are not part of the framework APIs.

Update URLs for servers and services

If your application accesses remote servers or services, make sure you are using the production URL or path for the server or service and not a test URL or path.

Implement Licensing (if you are releasing on Google Play)

If you are releasing a paid application through Google Play, consider adding support for Google Play Licensing. Licensing lets you control access to your application based on whether the current user has purchased it. Using Google Play Licensing is optional even if you are releasing your app through Google Play.

For more information about Google Play Licensing Service and how to use it in your application, see Application Licensing.

Building Your Application for Release

After you finish configuring your application you can build it into a release-ready APK file that is signed and optimized. The JDK includes the tools for signing the APK file (Keytool and Jarsigner); the Android SDK includes the tools for compiling and optimizing the APK file. If you are using Android Studio or you are using the Gradle build system from the command line, you can automate the entire build process. For more information about configuring Gradle builds, see Configuring Gradle Builds.

Building with Android Studio

You can use the Gradle build system, integrated with Android Studio to build a release-ready APK file that is signed with your private key and optimized. To learn how to setup and run builds from Android Studio, see Building and Running from Android Studio.

The build process assumes that you have a certificate and private key suitable for signing your application. If you do not have a suitable certificate and private key, Android Studio can help you generate one. For more information about the signing process, see Signing Your Applications.

Preparing External Servers and Resources

If your application relies on a remote server, make sure the server is secure and that it is configured for production use. This is particularly important if you are implementing in-app billing in your application and you are performing the signature verification step on a remote server.

Also, if your application fetches content from a remote server or a real-time service (such as a content feed), be sure the content you are providing is up to date and production-ready.

Testing Your Application for Release

Testing the release version of your application helps ensure that your application runs properly under realistic device and network conditions. Ideally, you should test your application on at least one handset-sized device and one tablet-sized device to verify that your user interface elements are sized correctly and that your application's performance and battery efficiency are acceptable.

As a starting point for testing, see What to Test. This article provides a summary of common Android situations that you should consider when you are testing. When you are done testing and you are satisfied that the release version of your application behaves correctly, you can release your application to users. For more information, see Releasing Your Application to Users. If you are publishing your application on Google Play, see Launch Checklist for Google Play.

来源： https://developer.android.com/studio/publish/preparing.html


Version Your App

Quickview

  • Your app must be versioned
  • Set the version in the app's Gradle build files
  • How you version your apps affects how users upgrade
  • Determine your versioning strategy early in the development process, including considerations for future releases.

In this document

  1. Set Application Version Information
  2. Specify API Level Requirements

See also

  1. Prepare for Release
  2. Launch Checklist for Google Play
  3. Configure Build Variants

Versioning is a critical component of your app upgrade and maintenance strategy. Versioning is important because:

  • Users need to have specific information about the app version that is installed on their devices and the upgrade versions available for installation.
  • Other apps — including other apps that you publish as a suite — need to query the system for your app's version, to determine compatibility and identify dependencies.
  • Services through which you will publish your app(s) may also need to query your app for its version, so that they can display the version to users. A publishing service may also need to check the app version to determine compatibility and establish upgrade/downgrade relationships.

The Android system does not use app version information to enforce restrictions on upgrades, downgrades, or compatibility of third-party apps. Instead, you are responsible for enforcing version restrictions within your app or by informing users of the version restrictions and limitations. The Android system does, however, enforce system version compatibility as expressed by the minSdkVersion setting in the build files. This setting allows an app to specify the minimum system API with which it is compatible. For more information seeSpecifying Minimum System API Version.

Set Application Version Information

To define the version information for your app, set values for the version settings in the Gradle build files. These values are then merged into your app's manifest file during the build process.

Note: If your app defines the app version directly in the <manifest> element, the version values in the Gradle build file will override the settings in the manifest. Additionally, defining these settings in the Gradle build files allows you to specify different values for different versions of your app. For greater flexibility and to avoid potential overwriting when the manifest is merged, you should remove these attributes from the <manifest> element and define your version settings in the Gradle build files instead.

Two settings are available, and you should always define values for both of them:

  • versionCode — An integer used as an internal version number. This number is used only to determine whether one version is more recent than another, with higher numbers indicating more recent versions. This is not the version number shown to users; that number is set by the versionNamesetting, below.

    The value is an integer so that other apps can programmatically evaluate it, for example to check an upgrade or downgrade relationship. You can set the value to any integer you want, however you should make sure that each successive release of your app uses a greater value. The system does not enforce this behavior, but increasing the value with successive releases is normative.

    Typically, you would release the first version of your app with versionCode set to 1, then monotonically increase the value with each release, regardless whether the release constitutes a major or minor release. This means that the versionCode value does not necessarily have a strong resemblance to the app release version that is visible to the user (see versionName, below). Apps and publishing services should not display this version value to users.

    Warning: The greatest value Google Play allows for versionCode is 2100000000.

  • versionName — A string used as the version number shown to users. This setting can be specified as a raw string or as a reference to a string resource.

    The value is a string so that you can describe the app version as a <major>.<minor>.<point> string, or as any other type of absolute or relative version identifier. The versionName has no purpose other than to be displayed to users.

You can define default values for these settings by including them in the defaultConfig {} block, nested inside the android {} block of your module'sbuild.gradle file. You can then override these default values for different versions of your app by defining separate values for individual build types or product flavors. The following build.gradle file shows the versionCode and versionName settings in the defaultConfig {} block, as well as theproductFlavors {} block.

android {
  ...
  defaultConfig {
    ...
    versionCode 2
    versionName "1.1"
  }
  productFlavors {
    demo {
      ...
      versionName "1.1-demo"
    }
    full {
      ...
    }
  }
}

In the defaultConfig {} block of this example, the versionCode value indicates that the current APK contains the second release of the app, and theversionName string specifies that it will appear to users as version 1.1. This build.gradle file also defines two product flavors, "demo" and "full." Since the "demo" product flavor defines versionName as "1.1-demo", the "demo" build uses this versionName instead of the default value. The "full" product flavor block does not define versionName, so it uses the default value of "1.1".

The Android framework provides an API to let you query the system for version information about your app. To obtain version information, use thegetPackageInfo(java.lang.String, int) method of PackageManager.

Note: When you use Instant Run, Android Studio automatically sets the versionCode to MAXINT and the versionName to "INSTANTRUN".

Specify API Level Requirements

If your app requires a specific minimum version of the Android platform, you can specify that version requirement as API level settings in the app'sbuild.gradle file. During the build process, these settings are merged into your app's manifest file. Specifying API level requirements ensures that your app can only be installed on devices that are running a compatible version of the Android platform.

Note: If you specify API level requirements directly in your app's manifest file, the corresponding settings in the build files will override the settings in the manifest file. Additionally, defining these settings in the Gradle build files allows you to specify different values for different versions of your app. For greater flexibility and to avoid potential overwriting when the manifest is merged, you should remove these attributes from the <uses-sdk>element and define your API level settings in the Gradle build files instead.

There are two API level settings available:

  • minSdkVersion — The minimum version of the Android platform on which the app will run, specified by the platform's API level identifier.
  • targetSdkVersion — Specifies the API level on which the app is designed to run. In some cases, this allows the app to use manifest elements or behaviors defined in the target API level, rather than being restricted to using only those defined for the minimum API level.

To specify default API level requirements in a build.gradle file, add one or more of the settings above to the defaultConfig {} block, nested inside theandroid {} block. You can also override these default values for different versions of your app by adding the settings to build types or product flavors. The following build.gradle file specifies default minSdkVersion and targetSdkVersion settings in the defaultConfig {} block and overridesminSdkVersion for one product flavor.

android {
  ...
  defaultConfig {
    ...
    minSdkVersion 14
    targetSdkVersion 24
  }
  productFlavors {
    main {
      ...
    }
    afterLollipop {
      ...
      minSdkVersion 21
    }
  }
}

When preparing to install your app, the system checks the value of these settings and compares them to the system version. If the minSdkVersion value is greater than the system version, the system prevents the installation of the app.

If you do not specify these settings, the system assumes that your app is compatible with all platform versions.

For more information, see the <uses-sdk> manifest element documentation and the API Levels document. For Gradle build settings, see Configure Build Variants.

来源： https://developer.android.com/studio/publish/versioning.html


Sign Your App

  1. Certificates and Keystores
  2. Sign Your Debug Build
    1. Expiry of the Debug Certificate
  3. Sign Your Release Build
    1. Configure the Build Process to Automatically Sign Your APK
    2. Sign Each Product Flavor Differently
    3. Sign Android Wear Apps
  4. Signing Considerations
  5. Secure Your Private Key
    1. Remove Signing Information from Your Build Files
  6. Sign Your App Manually

Android requires that all APKs be digitally signed with a certificate before they can be installed. This document describes how to sign your APKs using Android Studio, including creating and storing your certificate, signing different build configurations using different certificates, and configuring the build process to sign your APKs automatically.

Certificates and Keystores

A public-key certificate, also known as a digital certificate or an identity certificate, contains the public key of a public/private key pair, as well as some other metadata identifying the owner of the key (for example, name and location). The owner of the certificate holds the corresponding private key.

When you sign an APK, the signing tool attaches the public-key certificate to the APK. The public-key certificate serves as as a "fingerprint" that uniquely associates the APK to you and your corresponding private key. This helps Android ensure that any future updates to your APK are authentic and come from the original author.

A keystore is a binary file that contains one or more private keys. When you sign an APK for release using Android Studio, you can choose to generate a new keystore and private key or use a keystore and private key you already have. You should choose a strong password for your keystore, and a separate strong password for each private key stored in the keystore. You must keep your keystore in a safe and secure place. SeeSecuring Your Private Key, below.

You must use the same certificate throughout the lifespan of your app in order for users to be able to install new versions as updates to the app. For more about the benefits of using the same certificate for all your apps throughout their lifespans, see Signing Considerations below.

Sign Your Debug Build

When running or debugging your project from the IDE, Android Studio automatically signs your APK with a debug certificate generated by the Android SDK tools. The first time you run or debug your project in Android Studio, the IDE automatically creates the debug keystore and certificate in$HOME/.android/debug.keystore, and sets the keystore and key passwords.

Because the debug certificate is created by the build tools and is insecure by design, most app stores (including the Google Play Store) will not accept an APK signed with a debug certificate for publishing.

Android Studio automatically stores your debug signing information in a signing configuration so you do not have to enter it every time you debug. A signing configuration is an object consisting of all of the necessary information to sign an APK, including the keystore location, keystore password, key name, and key password. You cannot directly edit the debug signing configuration, but you can configure how you sign your release build.

For more information about how to build and run apps for debugging, see Build and Run Your App.

Expiry of the Debug Certificate

The self-signed certificate used to sign your APK for debugging has an expiration date of 365 days from its creation date. When the certificate expires, you will get a build error.

To fix this problem, simply delete the debug.keystore file. The file is stored in the following locations:

  • ~/.android/ on OS X and Linux
  • C:\Documents and Settings\<user>\.android\ on Windows XP
  • C:\Users\<user>\.android\ on Windows Vista and Windows 7, 8, and 10

The next time you build and run the debug build type, the build tools will regenerate a new keystore and debug key. Note that you must run your app, building alone does not regenerate the keystore and debug key.

Sign Your Release Build

You can use Android Studio to manually generate signed APKs, either one at a time, or for multiple build variants at once. Instead of manually signing APKs, you can also configure your Gradle build settings to handle signing automatically during the build process. This section describes the manual signing process. For more about signing apps as part of the build process, see Configure the Build Process to Automatically Sign Your APK.

To manually sign your APK for release in Android Studio, follow these steps:

  1. In the menu bar, click Build > Generate Signed APK.
  2. Select the module you would like to release from the drop down, and click Next.

  3. If you already have a keystore, go to step 5. If you want to create a new keystore, click Create new.

  4. On the New Key Store window, provide the following information for your keystore and key, as shown in figure 1.

    Figure 1. Create a new keystore in Android Studio.

    Keystore

    • Key store path: Select the location where your keystore should be created.
    • Password: Create and confirm a secure password for your keystore.

    Key

    • Alias: Enter an identifying name for your key.
    • Password: Create and confirm a secure password for your key. This should be different from the password you chose for your keystore
    • Validity (years): Set the length of time in years that your key will be valid. Your key should be valid for at least 25 years, so you can sign app updates with the same key through the lifespan of your app.
    • Certificate: Enter some information about yourself for your certificate. This information is not displayed in your app, but is included in your certificate as part of the APK.

    Once you complete the form, click OK.

  5. On the Generate Signed APK Wizard window, select a keystore, a private key, and enter the passwords for both. (If you created your keystore in the last step, these fields are already populated for you.) Then click Next.

    Figure 2. Select a private key in Android Studio.

  6. On the next window, select a destination for the signed APK(s), select the build type, (if applicable) choose the product flavor(s), and click Finish.

    Figure 3. Generate signed APKs for the selected product flavors.

    Note: If your project uses product flavors, you can select multiple product flavors while holding down the Ctrl key on Windown/Linux, or theCommand key on Mac OSX. Android Studio will generate a separate APK for each selected product flavor.

When the process completes, you will find your signed APK in the destination folder you selected above. You may now distribute your signed APK through an app marketplace like the Google Play Store, or using the mechanism of your choice. For more about how to publish your signed APK to the Google Play Store, see Get Started with Publishing. To learn more about other distribution options, read Alternative Distribution Options.

In order for users to succesfully install updates to your app, you will need to sign your APKs with the same certificate throughout the lifespan of your app. For more about this and other benefits of signing all your apps with the same key, see Signing Considerations below. For more information about securing your private key and keystore, see Securing Your Private Key.

Configure the Build Process to Automatically Sign Your APK

In Android Studio, you can configure your project to sign your release APK automatically during the build process by creating a signing configuration and assigning it to your release build type. A signing configuration consists of a keystore location, keystore password, key alias, and key password. To create a signing configuration and assign it to your release build type using Android Studio, use the following steps:

  1. In the Project window, right click on your app and click Open Module Settings.
  2. On the Project Structure window, under Modules in the left panel, click the module you would like to sign.
  3. Click the Signing tab, then click Add [image] .

  4. Select your keystore file, enter a name for this signing configuration (as you may create more than one), and enter the required information.

    Figure 4. The window for creating a new signing configuration.

  5. Click the Build Types tab.
  6. Click the release build.

  7. Under Signing Config, select the signing configuration you just created.

    Figure 5. Select a signing configuration in Android Studio.

  8. Click OK.

Now every time you build your release build type using Android Studio, the IDE will sign the APK automatically, using the signing configuration you specified. You can find your signed APKs in the build/outputs/apk/ folder inside the project directory for the module you are building.

When you create a signing configuration, your signing information is included in plain text in your Gradle build files. If you are working in a team or sharing your code publicly, you should keep your signing information secure by removing it from the build files and storing it separately. You can read more about how to remove your signing information from your build files in Remove Signing Information from Your Build Files. For more about keeping your signing information secure, read Secure Your Private Key.

Sign Each Product Flavor Differently

If your app uses product flavors and you would like to sign each flavor differently, you can create additional signing configurations and assign them by flavor:

  1. In the Project window, right click on your app and click Open Module Settings.
  2. On the Project Structure window, under Modules in the left panel, click the module you would like to sign.
  3. Click the Signing tab, then click Add [image] .

  4. Select your keystore file, enter a name for this signing configuration (as you may create more than one), and enter the required information.

    Figure 6. The window for creating a new signing configuration.

  5. Repeat steps 3 and 4 as necessary until you have created all your signing configurations.
  6. Click the Flavors tab.
  7. Click the flavor you would like to configure, then select the appropriate signing configuration from the Signing Config dropdown menu.

    Figure 7. Configure signing settings by product flavor.

    Repeat to configure any additional product flavors.

  8. Click OK.

You can also specify your signing settings in Gradle configuration files. For more information, see Configuring Signing Settings.

Sign Android Wear Apps

When publishing Android Wear APKs, you package the wearable APK inside of a handheld APK, because users cannot browse and install apps directly on the wearable. Both APKs must be signed. For more information on packaging and signing Android Wear APKs, see Packaging Wearable Apps.

Signing Considerations

You should sign all of your APKs with the same certificate throughout the expected lifespan of your apps. There are several reasons why you should do so:

  • App upgrade: When the system is installing an update to an app, it compares the certificate(s) in the new version with those in the existing version. The system allows the update if the certificates match. If you sign the new version with a different certificate, you must assign a different package name to the app—in this case, the user installs the new version as a completely new app.
  • App modularity: Android allows APKs signed by the same certificate to run in the same process, if the apps so request, so that the system treats them as a single app. In this way you can deploy your app in modules, and users can update each of the modules independently.
  • Code/data sharing through permissions: Android provides signature-based permissions enforcement, so that an app can expose functionality to another app that is signed with a specified certificate. By signing multiple APKs with the same certificate and using signature-based permissions checks, your apps can share code and data in a secure manner.

If you plan to support upgrades for an app, ensure that your key has a validity period that exceeds the expected lifespan of that app. A validity period of 25 years or more is recommended. When your key's validity period expires, users will no longer be able to seamlessly upgrade to new versions of your app.

If you plan to publish your apps on Google Play, the key you use to sign those APKs must have a validity period ending after 22 October 2033. Google Play enforces this requirement to ensure that users can seamlessly upgrade apps when new versions are available.

Secure Your Private Key

Maintaining the security of your private key is of critical importance, both to you and to the user. If you allow someone to use your key, or if you leave your keystore and passwords in an unsecured location such that a third-party could find and use them, your authoring identity and the trust of the user are compromised.

If a third party should manage to take your key without your knowledge or permission, that person could sign and distribute apps that maliciously replace your authentic apps or corrupt them. Such a person could also sign and distribute apps under your identity that attack other apps or the system itself, or corrupt or steal user data.

Your private key is required for signing all future versions of your app. If you lose or misplace your key, you will not be able to publish updates to your existing app. You cannot regenerate a previously generated key.

Your reputation as a developer entity depends on your securing your private key properly, at all times, until the key is expired. Here are some tips for keeping your key secure:

  • Select strong passwords for the keystore and key.
  • Do not give or lend anyone your private key, and do not let unauthorized persons know your keystore and key passwords.
  • Keep the keystore file containing your private key in a safe, secure place.

In general, if you follow common-sense precautions when generating, using, and storing your key, it will remain secure.

Remove Signing Information from Your Build Files

When you create a signing configuration, Android Studio adds your signing information in plain text to the module's build.gradle files. If you are working with a team or open-sourcing your code, you should move this sensitive information out of the build files so it is not easily accessible to others. To do this, you should create a separate properties file to store secure information and refer to that file in your build files as follows:

  1. Create a signing configuration, and assign it to one or more build types. These instructions assume you have configured a single signing configuration for your release build type, as described in Configure the Build Process to Automatically Sign Your APK, above.
  2. Create a file named keystore.properties in the root directory of your project. This file should contain your signing information, as follows:
    storePassword=myStorePassword
    keyPassword    =mykeyPassword
    keyAlias    =myKeyAlias
    storeFile    =myStoreFileLocation
  3. In your module's build.gradle file, add code to load your keystore.properties file before the android {} block.
    ...

    // Create a variable called keystorePropertiesFile, and initialize it to your
    // keystore.properties file, in the rootProject folder.
    def keystorePropertiesFile = rootProject.file("keystore.properties")

    // Initialize a new Properties() object called keystoreProperties.
    def keystoreProperties = new Properties()

    // Load your keystore.properties file into the keystoreProperties object.
    keystoreProperties    .load(new FileInputStream(keystorePropertiesFile))

    android     {
            ...
    }

    Note: You could choose to store your keystore.properties file in another location (for example, in the module folder rather than the root folder for the project, or on your build server if you are using a continuous integration tool). In that case, you should modify the code above to correctly initialize keystorePropertiesFile using your actual keystore.properties file's location.

  4. You can refer to properties stored in keystoreProperties using the syntax keystoreProperties['propertyName']. Modify the signingConfigs block of your module's build.gradle file to reference the signing information stored in keystoreProperties using this syntax.
    android {
        signingConfigs     {
            config     {
                keyAlias keystoreProperties    ['keyAlias']
                keyPassword keystoreProperties    ['keyPassword']
                storeFile file    (keystoreProperties['storeFile'])
                storePassword keystoreProperties    ['storePassword']
                }
            }
            ...
          }
  5. Open the Build Variants tool window and ensure that the release build type is selected.
  6. Click Build > Build APK to build your release build, and confirm that Android Studio has created a signed APK in the build/outputs/apk/ directory for your module.

Because your build files no longer contain sensitive information, you can now include them in source control or upload them to a shared codebase. Be sure to keep the keystore.properties file secure. This may include removing it from your source control system.

Sign Your App Manually

You do not need Android Studio to sign your app. You can sign your app from the command line using standard tools from the Android SDK and the JDK. To sign an app in release mode from the command line:

  1. Generate a private key using keytool. For example:

    $ keytool -genkey -v -keystore my-release-key.keystore
-alias alias_name -keyalg RSA -keysize 2048 -validity 10000

    This example prompts you for passwords for the keystore and key, and to provide the Distinguished Name fields for your key. It then generates the keystore as a file called my-release-key.keystore. The keystore contains a single key, valid for 10000 days. The alias is a name that you will use later when signing your app.

  2. Compile your app in release mode to obtain an unsigned APK.

  3. Sign your app with your private key using jarsigner:

    $ jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1
-keystore my-release-key.keystore my_application.apk alias_name

    This example prompts you for passwords for the keystore and key. It then modifies the APK in-place to sign it. Note that you can sign an APK multiple times with different keys.

  4. Verify that your APK is signed. For example:

    $ jarsigner -verify -verbose -certs my_application.apk

  5. Align the final APK package using zipalign.

    $ zipalign -v 4 your_project_name-unaligned.apk your_project_name.apk

    zipalign ensures that all uncompressed data starts with a particular byte alignment relative to the start of the file, which reduces the amount of RAM consumed by an app.

来源： https://developer.android.com/studio/publish/app-signing.html


Command Line Tools

The Android SDK tools available from the SDK Manager provide additional command-line tools to help you during your Android development. The tools are classified into two groups: SDK tools and platform tools. SDK tools are platform independent and are required no matter which Android platform you are developing on. Platform tools are customized to support the features of the latest Android platform.

SDK Tools

The SDK tools are installed with the SDK starter package and are periodically updated. The SDK tools are required if you are developing Android applications. The most important SDK tools include the Android SDK Manager (android sdk), the AVD Manager (android avd) the emulator (emulator), and the Dalvik Debug Monitor Server (ddms). A short summary of some frequently-used SDK tools is provided below.

Virtual Device Tools

Android Virtual Device Manager
The AVD Manager provides a graphical user interface in which you can create and manage Android Virtual Devices (AVDs) that run in the Android Emulator.
Android Emulator (emulator)
A QEMU-based device-emulation tool that you can use to debug and test your applications in an actual Android run-time environment.
mksdcard
Helps you create a disk image that you can use with the emulator, to simulate the presence of an external storage card (such as an SD card).

Development Tools

Hierarchy Viewer (hierarchyviewer)
Provides a visual representation of the layout's View hierarchy with performance information for each node in the layout, and a magnified view of the display to closely examine the pixels in your layout.
SDK Manager
Lets you manage SDK packages, such as installed platforms and system images.
sqlite3
Lets you access the SQLite data files created and used by Android applications.

Debugging Tools

Android Monitor
Android Monitor is integrated into Android Studio and provides logcat, memory, CPU, GPU, and network monitors for app debugging and analysis.
adb
Android Debug Bridge (adb) is a versatile command line tool that lets you communicate with an emulator instance or connected Android-powered device. It also provides access to the device shell.
ADB Shell Commands
Learn the commands available for advanced command-line operations.
Dalvik Debug Monitor Server (ddms)
Lets you debug Android apps.
Device Monitor
Android Device Monitor is a stand-alone tool that provides a graphical user interface for several Android application debugging and analysis tools.
Systrace
Lets you analyze the execution of your application in the context of system processes, to help diagnose display and performance issues.
traceview
Provides a graphical viewer for execution logs saved by your application.
Tracer for OpenGL ES
Allows you to capture OpenGL ES commands and frame-by-frame images to help you understand how your app is executing graphics commands.

Build Tools

JOBB
Allows you to build encrypted and unencrypted APK expansion files in Opaque Binary Blob (OBB) format.
ProGuard
Shrinks, optimizes, and obfuscates your code by removing unused code and renaming classes, fields, and methods with semantically obscure names.
zipalign
Optimizes .apk files by ensuring that all uncompressed data starts with a particular alignment relative to the start of the file. This should always be used to align .apk files after they have been signed.

Image Tools

Draw 9-patch
Allows you to easily create a NinePatch graphic using a WYSIWYG editor. It also previews stretched versions of the image, and highlights the area in which content is allowed.
etc1tool
A command line utility that lets you encode PNG images to the ETC1 compression standard and decode ETC1 compressed images back to PNG.

Platform Tools

The platform tools are typically updated every time you install a new SDK platform. Each update of the platform tools is backward compatible with older platforms. Usually, you directly use only one of the platform tools—the Android Debug Bridge (adb). Android Debug Bridge is a versatile tool that lets you manage the state of an emulator instance or Android-powered device. You can also use it to install an Android application (.apk) file on a device.

The other platform tools, such as aidl, aapt, dexdump, and dx, are typically called by the Android build tools, so you rarely need to invoke these tools directly. As a general rule, you should rely on the build tools to call them as needed.

Note: The Android SDK provides additional shell tools that can be accessed through adb, such as bmgr and logcat.

bmgr
A shell tool you can use to interact with the Backup Manager on Android devices supporting API Level 8 or greater.
logcat
Provides a mechanism for collecting and viewing system debug output.

来源： https://developer.android.com/studio/command-line/index.html


Android Debug Bridge

  1. How adb Works
  2. Enabling adb Debugging
  3. Syntax
  4. Commands
  5. Querying for Emulator/Device Instances
  6. Directing Commands to a Specific Emulator/Device Instance
  7. Installing an Application
  8. Forwarding Ports
  9. Copying Files to or from an Emulator/Device Instance
  10. Stopping the adb Server
  11. Wireless usage

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 sends commands. The client runs on your development machine. You can invoke a client from a shell by issuing an adb command. Other Android tools such as DDMS also create adb clients.
  • 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.

You can find the adb tool in <sdk>/platform-tools/.

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

Enabling adb Debugging

In order 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.

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.

For more information about connecting to a device over USB, read Using Hardware Devices.

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

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

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

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

Wireless usage

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

  1. Connect your Android device and adb host computer to a common Wi-Fi network accessible to both. We have found 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 a Wear device, force it to connect to Wi-Fi by shutting off Bluetooth on the phone connected to it.

  2. Connect the device to the host computer with a USB cable.
  3. Set the target device to listen for a TCP/IP connection on port 5555.
    $ adb tcpip 5555
  4. Disconnect the USB cable from the target device.
  5. 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.
  6. Connect to the device, identifying it by IP address.
    $ adb connect <device-ip-address>
  7. Confirm that your host computer is connected to the target device:
    $ adb devices
List of devices attached
<device-ip-address>: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
    and then start over from the beginning.

来源： https://developer.android.com/studio/command-line/adb.html


bmgr

  1. Forcing a Backup Operation
  2. Forcing a Restore Operation
  3. Other Commands

See also

  1. Data Backup

bmgr is a shell tool you can use to interact with the Backup Manager on Android devices supporting API Level 8 or greater. It provides commands to induce backup and restore operations so that you don't need to repeatedly wipe data or take similar intrusive steps in order to test your application's backup agent. These commands are accessed via the adb shell.

For information about adding support for backup in your application, read Data Backup, which includes a guide to testing your application using bmgr.

Forcing a Backup Operation

Normally, your application must notify the Backup Manager when its data has changed, via dataChanged(). The Backup Manager will then invoke your backup agent's onBackup() implementation at some time in the future. However, instead of callingdataChanged(), you can invoke a backup request from the command line by running the bmgr backup command:

adb shell bmgr backup <package>

<package> is the formal package name of the application you wish to schedule for backup. When you execute this backup command, your application's backup agent will be invoked to perform a backup operation at some time in the future (via your onBackup() method), though there is no guarantee when it will occur. However, you can force all pending backup operations to run immediately by using the bmgr run command:

adb shell bmgr run

This causes a backup pass to execute immediately, invoking the backup agents of all applications that had previously called dataChanged() since the last backup operation, plus any applications which had been manually scheduled for backup via bmgr backup.

Forcing a Restore Operation

Unlike backup operations, which are batched together and run on an occasional basis, restore operations execute immediately. The Backup Manager currently provides two kinds of restore operations. The first kind restores an entire device with the data that has been backed up. This is typically performed only when a device is first provisioned (to replicate settings and other saved state from the user's previous device) and is an operation that only the system can perform. The second kind of restore operation restores a single application to its "active" data set; that is, the application will abandon its current data and revert to the last-known-good data that is held in the current backup image. You can invoke this second restore operation with the requestRestore() method. The Backup Manager will then invoke your backup agent's onRestore() implementation.

While testing your application, you can immediately invoke the restore operation (bypassing the requestRestore() method) for your application by using the bmgr restore command:

adb shell bmgr restore <package>

<package> is the formal Java-style package name of the application participating in the backup/restore mechanism, which you would like to restore. The Backup Manager will immediately instantiate the application's backup agent and invoke it for restore. This will happen even if your application is not currently running.

Other Commands

Wiping data

The data for a single application can be erased from the active data set on demand. This is very useful while you're developing a backup agent, in case bugs lead you to write corrupt data or saved state information. You can wipe an application's data with the bmgr wipe command:

adb shell bmgr wipe <package>

<package> is the formal package name of the application whose data you wish to erase. The next backup operation that the application's agent processes will look as though the application had never backed anything up before.

Enabling and disabling backup

You can see whether the Backup Manager is operational at all with the bmgr enabled command:

adb shell bmgr enabled

This might be useful if your application's backup agent is never being invoked for backup, to verify whether the operating system thinks it should be performing such operations at all.

You can also directly disable or enable the Backup Manager with this command:

adb shell bmgr enable <boolean>

<boolean> is either true or false. This is equivalent to disabling or enabling backup in the device's main Settings UI.

Warning! When backup is disabled, the current backup transport will explicitly wipe the entire active data set from its backend storage. This is so that when a user says they do not want their data backed up, the Backup Manager respects that wish. No further data will be saved from the device, and no restore operations will be possible, unless the Backup Manager is re-enabled (either through Settings or through the above bmgr command).

来源： https://developer.android.com/studio/command-line/bmgr.html


etc1tool

etc1tool is a command line utility that lets you encode PNG images to the ETC1 compression standard and decode ETC1 compressed images back to PNG.

The usage for etc1tool is:

etc1tool infile [--help | --encode | --encodeNoHeader | --decode] [--showDifference
diff-file] [-o outfile]
Option | Description
infile | The input file to compress
--help | Print usage information
--encode | Create an ETC1 file from a PNG file. This is the default mode for the tool if nothing is specified.
--encodeNoHeader | Create a raw ETC1 data file (without a header) from a PNG file.
--decode | Create a PNG file from an ETC1 file
--showDifferencediff-file | Write the difference between the original and encoded image to diff-file (only valid when encoding).
-o outfile | Specify the name of the output file. If outfile is not specified, the output file is constructed from the input filename with the appropriate suffix (.pkm or .png).

来源： https://developer.android.com/studio/command-line/etc1tool.html


JOBB

The jobb tool allows you to build encrypted and unencrypted APK expansion files in Opaque Binary Blob (OBB) format. You can download and mount these expansion files in your application using StorageManager on devices with Android 2.3 (API Level 9) or higher. OBB files are used to provide additional file assets for Android applications (such as graphics, sounds and video), separate from an application's APK file. For more information on using expansion files, see APK Expansion Files.

Usage

The syntax for running jobb is as follows:

jobb [-d <directory>][-o <filename>][-pn <package>][-pv <version>] \
     [-k <key>][-ov][-dump <filename>][-v][-about]

You can use the jobb tool to create an OBB file or extract the contents of an existing OBB. The following example command creates an OBB file from source files.

$ jobb -d /temp/assets/ -o my-app-assets.obb -k secret-key -pn com.my.app.package -pv 11

This example shows how to dump (extract) the contents of an existing OBB file:

$ jobb -d /temp/obb-output/ -o my-app-assets.obb -k secret-key

Options

The table below lists the command line options for the jobb tool.

Option | Description
-d <directory> | Set the input directory for creating an OBB file, or the output directory when extracting (-dump) an existing file. When creating an OBB file, the contents of the specified directory and all its sub-directories are included in the OBB file system.
-o <filename> | Specify the filename for the OBB file. This parameter is required when creating an OBB and extracting (dumping) its contents.
-pn <package> | Specify the package name for the application that mounts the OBB file, which corresponds to the package value specified in your application's manifest. This parameter is required when creating an OBB file.
-pv <version> | Set the minimum version for the application that can mount the OBB file, which corresponds to the android:versionCode value in your application's manifest. This parameter is required when creating an OBB file.
-k <key> | Specify a password for encrypting a new OBB file or decrypting an existing, encypted OBB file.
-ov | Create OBB file that is an overlay of an existing OBB file structure. This option allows the new package contents to be mounted into the same location as a previous package and is intended for creating patch versions of previously generated OBB files. Files within an overlay OBB file replace files that have the same path.
-dump <filename>

Extract the contents of the specified OBB file. When using this option, you must also specify the output directory for the contents using the -d <directory> parameter.

Note: When dumping an existing OBB file, you can omit the -d <directory> parameter to get a listing of the directories inside the file, without extracting the contents.

-v | Set verbose output for the tool.
-about | Display version and help information for the jobb tool.

来源： https://developer.android.com/studio/command-line/jobb.html


logcat Command-line Tool

  1. Command-line Syntax
  2. Starting LogCat
  3. Filtering Log Output
  4. Controlling Log Output Format
  5. Viewing Alternative Log Output Buffers
  6. Viewing stdout and stderr
  7. Logging from Code

Logcat is a command-line tool that dumps a log of system messages, including stack traces when the device throws an error and messages that you have written from your app with the Log class.

This page is about the command-line logcat tool, but you can also view log messages from the Logcatwindow in Android Studio. For information about viewing and filtering logs from Android Studio, see Write and View Logs with Logcat.

Command-line Syntax

[adb] logcat [<option>] ... [<filter-spec>] ...

You can run logcat as an adb command or directly in a shell prompt of your emulator or connected device. To view log output using adb, navigate to your SDK platform-tools/ directory and execute:

$ adb logcat

You can create a shell connection to a device and execute:

$ adb shell
# logcat

Options

The following table describes the command line options of logcat.

Option | Description
-b <buffer> | Loads an alternate log buffer for viewing, such as events or radio. The main buffer is used by default. See Viewing Alternative Log Buffers.
-c | Clears (flushes) the entire log and exits.
-d | Dumps the log to the screen and exits.
-f <filename> | Writes log message output to <filename>. The default is stdout.
-g | Prints the size of the specified log buffer and exits.
-n <count> | Sets the maximum number of rotated logs to <count>. The default value is 4. Requires the -r option.
-r <kbytes> | Rotates the log file every <kbytes> of output. The default value is 16. Requires the -f option.
-s | Sets the default filter spec to silent.
-v <format> | Sets the output format for log messages. The default is brief format. For a list of supported formats, see Controlling Log Output Format.

Starting logcat

To run logcat, through the ADB shell, 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

The following table describes the logcat command line options:

-c | Clears (flushes) the entire log and exits.
-d | Dumps the log to the screen and exits.
-f <filename> | Writes log message output to <filename>. The default is stdout.
-g | Prints the size of the specified log buffer and exits.
-n <count> | Sets the maximum number of rotated logs to <count>. The default value is 4. Requires the -r option.
-r <kbytes> | Rotates the log file every <kbytes> of output. The default value is 16. Requires the -f option.
-s | Sets the default filter spec to silent.
-v <format> | Sets the output format for log messages. The default is brief format. For a list of supported formats, see Controlling Log Output Format.

Filtering Log Output

Every Android log message has a tag and a priority associated with it.

  • The tag of a log message is a short string indicating the system component from which the message originates (for example, "View" for the view system).
  • The priority is one of the following character values, ordered from lowest to highest priority:
    • V — Verbose (lowest priority)
    • D — Debug
    • I — Info
    • W — Warning
    • E — Error
    • F — Fatal
    • S — Silent (highest priority, on which nothing is ever printed)

You can obtain a list of tags used in the system, together with priorities, by running logcat and observing the first two columns of each message, given as<priority>/<tag>.

Here's an example of logcat output that shows that the message relates to priority level "I" and tag "ActivityManager":

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

To reduce the log output to a manageable level, you can restrict log output using filter expressions. Filter expressions let you indicate to the system the tags-priority combinations that you are interested in — the system suppresses other messages for the specified tags.

A filter expression follows this format tag:priority ..., where tag indicates the tag of interest and priority indicates the minimum level of priority to report for that tag. Messages for that tag at or above the specified priority are written to the log. You can supply any number of tag:priorityspecifications in a single filter expression. The series of specifications is whitespace-delimited.

Here's an example of a filter expression that suppresses all log messages except those with the tag "ActivityManager", at priority "Info" or above, and all log messages with tag "MyApp", with priority "Debug" or above:

adb logcat ActivityManager:I MyApp:D *:S

The final element in the above expression, *:S, sets the priority level for all tags to "silent", thus ensuring only log messages with "ActivityManager" and "MyApp" are displayed. Using *:S is an excellent way to ensure that log output is restricted to the filters that you have explicitly specified — it lets your filters serve as a "whitelist" for log output.

The following filter expression displays all log messages with priority level "warning" and higher, on all tags:

adb logcat *:W

If you're running logcat from your development computer (versus running it on a remote adb shell), you can also set a default filter expression by exporting a value for the environment variable ANDROID_LOG_TAGS:

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

Note that ANDROID_LOG_TAGS filter is not exported to the emulator/device instance, if you are running logcat from a remote shell or using adb shell logcat.

Controlling Log Output Format

Log messages contain a number of metadata fields, in addition to the tag and priority. You can modify the output format for messages so that they display a specific metadata field. To do so, you use the -v option and specify one of the supported output formats listed below.

  • brief — Display priority/tag and PID of the process issuing the message (the default format).
  • process — Display PID only.
  • tag — Display the priority/tag only.
  • raw — Display the raw log message, with no other metadata fields.
  • time — Display the date, invocation time, priority/tag, and PID of the process issuing the message.
  • threadtime — Display the date, invocation time, priority, tag, and the PID and TID of the thread issuing the message.
  • long — Display all metadata fields and separate messages with blank lines.

When starting logcat, you can specify the output format you want by using the -v option:

[adb] logcat [-v <format>]

Here's an example that shows how to generate messages in thread output format:

adb logcat -v thread

Note that you can only specify one output format with the -v option.

Viewing Alternative Log Buffers

The Android logging system keeps multiple circular buffers for log messages, and not all of the log messages are sent to the default circular buffer. To see additional log messages, you can run the logcat command with the -b option, to request viewing of an alternate circular buffer. You can view any of these alternate buffers:

  • radio — View the buffer that contains radio/telephony related messages.
  • events — View the buffer containing events-related messages.
  • main — View the main log buffer (default)

The usage of the -b option is:

[adb] logcat [-b <buffer>]

Here's an example of how to view a log buffer containing radio and telephony messages:

adb logcat -b radio

Viewing stdout and stderr

By default, the Android system sends stdout and stderr (System.out and System.err) output to /dev/null. In processes that run the Dalvik VM, you can have the system write a copy of the output to the log file. In this case, the system writes the messages to the log using the log tags stdout and stderr, both with priority I.

To route the output in this way, you stop a running emulator/device instance and then use the shell command setprop to enable the redirection of output. Here's how you do it:

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

The system retains this setting until you terminate the emulator/device instance. To use the setting as a default on the emulator/device instance, you can add an entry to /data/local.prop on the device.

Logging from Code

The Log class allows you to create log entries in your code that display in the logcat tool. Common logging methods include:

  • Log.v(String, String) (verbose)
  • Log.d(String, String) (debug)
  • Log.i(String, String) (information)
  • Log.w(String, String) (warning)
  • Log.e(String, String) (error)

For example, using the following call:

Log.i("MyActivity", "MyClass.getView() — get item number " + position);

The logcat outputs something like:

I/MyActivity( 1557): MyClass.getView() — get item number 1

来源： https://developer.android.com/studio/command-line/logcat.html


mksdcard

The mksdcard tool lets you quickly create a FAT32 disk image that you can load in the emulator, to simulate the presence of an SD card in the device. Because you can specify an SD card while creating an AVD in the AVD Manager, you usually use that feature to create an SD card. This tool creates an SD card that is not bundled with an AVD, so it is useful for situations where you need to share a virtual SD card between multiple emulators.

Usage

mksdcard -l <label> <size> <file>

Options

The following table describes the command-line options of mksdcard

Option | Description
-l | A volume label for the disk image to create.
size | An integer that specifies the size (in bytes) of disk image to create. You can also specify size in kilobytes or megabytes, by appending a "K" or "M" to <size>. For example, 1048576K, 1024M.
file | The path/filename of the disk image to create.

Once you have created the disk image file, you can load it in the emulator at startup using the emulator's -sdcard option. For more information, seeAndroid Emulator.

The usage for the -sdcard option is as follows:

emulator -sdcard <file>

Example

mksdcard -l mySdCard 1024M mySdCardFile.img

来源： https://developer.android.com/studio/command-line/mksdcard.html


zipalign

zipalign is an archive alignment tool that provides important optimization to Android application (.apk) files. The purpose is to ensure that all uncompressed data starts with a particular alignment relative to the start of the file. Specifically, it causes all uncompressed data within the .apk, such as images or raw files, to be aligned on 4-byte boundaries. This allows all portions to be accessed directly with mmap() even if they contain binary data with alignment restrictions. The benefit is a reduction in the amount of RAM consumed when running the application.

This tool should always be used to align your .apk file before distributing it to end-users. The Android build tools can handle this for you. Android Studio automatically aligns your .apk after it signs it with your private key. The build scripts used when compiling your application with Gradle also align your .apk, as long as you have provided the path to your keystore and the key alias in your project gradle.properties file, so that the build tools can sign the package first.

Caution: zipalign must only be performed after the .apk file has been signed with your private key. If you perform zipalign before signing, then the signing procedure will undo the alignment. Also, do not make alterations to the aligned package. Alterations to the archive, such as renaming or deleting entries, will potentially disrupt the alignment of the modified entry and all later entries. And any files added to an "aligned" archive will not be aligned.

The adjustment is made by altering the size of the "extra" field in the zip Local File Header sections. Existing data in the "extra" fields may be altered by this process.

For more information about how to use zipalign when building your application, please read Signing Your Application.

Usage

To align infile.apk and save it as outfile.apk:

zipalign [-f] [-v] <alignment> infile.apk outfile.apk

To confirm the alignment of existing.apk:

zipalign -c -v <alignment> existing.apk

The <alignment> is an integer that defines the byte-alignment boundaries. This must always be 4 (which provides 32-bit alignment) or else it effectively does nothing.

Flags:

  • -f : overwrite existing outfile.zip
  • -v : verbose output
  • -c : confirm the alignment of the given file

来源： https://developer.android.com/studio/command-line/zipalign.html


Android Studio Release Notes

See also

  1. Download Android Studio

Android Studio is the official IDE for Android development, and with a single download includes everything you need to begin developing Android apps:

  • IntelliJ IDE + Android Studio plugin
  • Android SDK Tools
  • Android Platform-tools
  • A version of the Android platform
  • Android Emulator with an Android system image including Google Play Services

For an introduction to Android Studio, read Meet Android Studio.

Periodic updates are pushed to Android Studio without requiring you to update your Android project. To manually check for updates, select Help > Check for update (on Mac, select Android Studio > Check for updates).

Revisions

The sections below provide notes about successive releases of Android Studio, as denoted by revision number.

Android Studio v2.1.3 (August 2016)

This update adds compatibility with Gradle 2.14.1, which includes performance improvements, new features, and an important security fix. For more details, see the Gradle release notes.

By default, new projects in Android Studio 2.1.3 use Gradle 2.14.1. For existing projects, the IDE prompts you to upgrade to Gradle 2.14.1 and Android Plugin for Gradle 2.1.3, which is required when using Gradle 2.14.1 and higher.

Android Studio v2.1.2 (June 2016)

Android Studio v2.1.1 (May 2016)

Android Studio v2.1.0 (April 2016)

Android Studio v2.0.0 (April 2016)

Android Studio v1.5.1 (December 2015)

Android Studio v1.5.0 (November 2015)

Android Studio v1.4.1 (October 2015)

Android Studio v1.4.0 (September 2015)

Android Studio v1.3.2 (August 2015)

Android Studio v1.3.1 (August 2015)

Android Studio v1.3.0 (July 2015)

Android Studio v1.2.2 (June 2015)

Android Studio v1.2.1 (May 2015)

Android Studio v1.2.0 (April 2015)

Android Studio v1.1.0 (February 2015)

Android Studio v1.0.1 (December 2014)

Android Studio v1.0 (December 2014)

Android Studio v0.8.14 (October 2014)

Android Studio v0.8.6 (August 2014)

Android Studio v0.8.0 (June 2014)

Android Studio v0.5.2 (May 2014)

Android Studio v0.4.6 (March 2014)

Android Studio v0.4.2 (Jan 2014)

Android Studio v0.3.2 (Oct 2013)

Android Studio v0.2.x (July 2013)

Android Studio v0.1.x (May 2013)

Troubleshooting

If you encounter problems in Android Studio, look at the following page for possible resolutions to known issues: http://tools.android.com/knownissues.

来源： https://developer.android.com/studio/releases/index.html


SDK Tools Release Notes

SDK Tools is a downloadable component for the Android SDK. It includes the complete set of development and debugging tools for the Android SDK. It is included with Android Studio.

If you are already using the SDK and you want to update to the latest version of the SDK Tools, use the SDK Manager to get the update.

Revisions

The sections below provide notes about successive releases of the SDK Tools, as denoted by revision number. To determine what revision of the SDK Tools you are using, refer to the "Installed Packages" listing in the Android SDK Manager.

For a summary of all known issues in SDK Tools, visit the Android Tools Project Site.

SDK Tools, Revision 25.1.6 (May 2016)

Dependencies:
  • Android SDK Platform-tools revision 23 or later.
General Notes:
  • To improve the security of the Android Emulator and to address a reported security vulnerability, the Android Emulator Console now requiresauthentication before you can enter commands. Enter the auth auth_token command after you telnet to an emulator instance. auth_tokenmust match the contents of the .emulator_console_auth_token file in your home directory.

SDK Tools, Revision 25.0.0 (April 2016)

SDK Platform-tools, Revision 23.1.0 (December 2015)

SDK Tools, Revision 24.4.1 (October 2015)

SDK Tools, Revision 24.4.0 (October 2015)

SDK Tools, Revision 24.3.4 (August 2015)

SDK Tools, Revision 24.3.3 (June 2015)

SDK Tools, Revision 24.3.2 (June 2015)

SDK Tools, Revision 24.3.1 (June 2015)

SDK Tools, Revision 24.3.0 (June 2015)

SDK Tools, Revision 24.2.0 (May 2015)

SDK Tools, Revision 24.1.2 (February 2015)

SDK Tools, Revision 24.0.2 (December 2014)

SDK Tools, Revision 24.0.1 (December 2014)

SDK Tools, Revision 24.0.0 (December 2014)

SDK Tools, Revision 23.0.5 (October 2014)

SDK Tools, Revision 23.0.4 (October 2014)

SDK Tools, Revision 23.0.2 (July 2014)

SDK Tools, Revision 23.0.0 (June 2014)

SDK Tools, Revision 22.6.4 (June 2014)

SDK Tools, Revision 22.6.3 (April 2014)

SDK Tools, Revision 22.6.2 (March 2014)

SDK Tools, Revision 22.6.1 (March 2014)

SDK Tools, Revision 22.6 (March 2014)

SDK Tools, Revision 22.3 (October 2013)

SDK Tools, Revision 22.2.1 (September 2013)

SDK Tools, Revision 22.2 (September 2013)

SDK Tools, Revision 22.0.5 (July 2013)

SDK Tools, Revision 22.0.4 (July 2013)

SDK Tools, Revision 22.0.1 (May 2013)

SDK Tools, Revision 22 (May 2013)

SDK Tools, Revision 21.1 (February 2013)

SDK Tools, Revision 21.0.1 (December 2012)

SDK Tools, Revision 21 (November 2012)

SDK Tools, Revision 20.0.3 (August 2012)

SDK Tools, Revision 20.0.1 (July 2012)

SDK Tools, Revision 20 (June 2012)

SDK Tools, Revision 19 (April 2012)

SDK Tools, Revision 18 (April 2012)

SDK Tools, Revision 17 (March 2012)

SDK Tools, Revision 16 (December 2011)

SDK Tools, Revision 15 (October 2011)

SDK Tools, Revision 14 (October 2011)

SDK Tools, Revision 13 (September 2011)

SDK Tools, Revision 12 (July 2011)

SDK Tools, Revision 11 (May 2011)

SDK Tools, Revision 10 (February 2011)

SDK Tools, Revision 9 (January 2011)

SDK Tools, Revision 8 (December 2010)

SDK Tools, Revision 7 (September 2010)

SDK Tools, Revision 6 (May 2010)

SDK Tools, Revision 5 (March 2010)

SDK Tools, Revision 4 (December 2009)

SDK Tools, Revision 3 (October 2009)

来源： https://developer.android.com/studio/releases/sdk-tools.html


SDK Build Tools Release Notes

See Also

  1. Building and Running

Build Tools is a component of the Android SDK required for building Android application code and is installed in the <sdk>/build-tools/ directory.

You should always keep your Build Tools component updated by downloading the latest version using theAndroid SDK Manager. By default, the Android SDK uses the most recent downloaded version of the Build Tools. If your projects depend on older versions of the Build Tools, the SDK Manager allows you to download and maintain separate versions of the tools for use with those projects.

To use a specific version of the Build Tools in your application project:

  1. In the root folder of your application project, find the build.gradle file.
  2. Open the file and specify the Build Tools version by adding a buildToolsVersion property to the android section:
    android {
            ...
        buildToolsVersion     "17.0.0"
            ...
    }

Revisions

The sections below provide notes about releases of the Build Tools. To determine which revisions of the Build Tools are available in your SDK, refer to theInstalled Packages listing in the Android SDK Manager.

Build Tools, Revision 23.0.3 (March 2016)

  • Fix issues in the RenderScript Support Library on arm64 devices.
  • Fix issues in the RenderScript Support Library on certain Jelly Bean devices.
  • Support renderscriptTargetAPI 21+ when using Android Plugin for Gradle, Revision 2.1.0 and above .

Build Tools, Revision 23.0.2 (November 2015)

  • Improved the merging performance of the dx tool.
  • Fixed issues in the RenderScript compiler for Windows.

Build Tools, Revision 23.0.1 (October 2015)

Build Tools, Revision 23.0.0 (August 2015)

Build Tools, Revision 22.0.1 (March 2015)

Build Tools, Revision 22.0.0 (March 2015)

Build Tools, Revision 21.1.2 (February 2015)

Build Tools, Revision 21.1.1 (November 2014)

Build Tools, Revision 21.1 (October 2014)

Build Tools, Revision 21.0.2 (October 2014)

Build Tools, Revision 21.0.1 (October 2014)

Build Tools, Revision 21.0.0 (October 2014)

Build Tools, Revision 20.0.0 (June 2014)

Build Tools, Revision 19.1.0 (May 2014)

Build Tools, Revision 19.0.3 (March 2014)

Build Tools, Revision 19.0.2 (February 2014)

Build Tools, Revision 19.0.1 (December 2013)

Build Tools, Revision 19 (October 2013)

Build Tools, Revision 18.1.1 (September 2013)

Build Tools, Revision 18.1.0 (September 2013)

Build Tools, Revision 18.0.1 (July 2013)

Build Tools, Revision 17 (May 2013)

来源： https://developer.android.com/studio/releases/build-tools.html


Android Plugin for Gradle Release Notes

  1. Update the Android Plugin for Gradle Version
  2. Update the Gradle Version
  3. Revisions

See also

  1. Android Plugin DSL Reference
  2. Configure Your Build

The Android build system uses the Android Plugin for Gradle to support building Android applications with the Gradle build toolkit. The plugin runs independent of Android Studio so the plugin and the Gradle build system can be updated independently of Android Studio.

Update the Android Plugin for Gradle

When you update Android Studio, you may receive a prompt to automatically update the Android Plugin for Gradle to the latest available version. You can choose to accept the update or manually specify a version based on your project's build requirements.

You can specify the Android Plugin for Gradle version in either the File > Project Structure > Project menu in Android Studio, or the top-level build.gradle file. The plugin version applies to all modules built in that Android Studio project. The following example sets the Android Plugin for Gradle to version 2.1.0 from thebuild.gradle file:

buildscript {
  ...
  dependencies {
    classpath 'com.android.tools.build:gradle:2.1.0'
  }
}

Caution: You should not use dynamic dependencies in version numbers, such as 'com.android.tools.build:gradle:2.+'. Using this feature can cause unexpected version updates and difficulty resolving version differences.

If the specified plugin version has not been downloaded, Gradle downloads it the next time you build your project or click Tools > Android > Sync Project with Gradle Files from the Android Studio main menu.

Update Gradle

When you update Android Studio, you may receive a prompt to automatically update Gradle to the latest available version. You can choose to accept the update or manually specify a version based on your project's build requirements.

You can specify the Gradle version in either the File > Project Structure > Project menu in Android Studio, or by editing the Gradle distribution reference in the gradle/wrapper/gradle-wrapper.properties file. The following example sets the Gradle version to 2.10 in the gradle-wrapper.properties file.

...
distributionUrl = https\://services.gradle.org/distributions/gradle-2.10-all.zip
...

Revisions

For a summary of known issues in Android Plugin for Gradle, visit the Android Tools Project Site.

Android Plugin for Gradle, Revision 2.1.3 (August 2016)

Dependencies:
  • Gradle 2.14.1 or higher.
  • Build Tools 23.0.2 or higher.
This update adds compatibility with Gradle 2.14.1, which includes performance improvements, new features, and an important security fix. For more details, see the Gradle release notes.

Android Plugin for Gradle, Revision 2.1.0 (April 2016)

Android Plugin for Gradle, Revision 2.0.0 (April 2016)

Android Plugin for Gradle, Revision 1.5.0 (November 2015)

Android Plugin for Gradle, Revision 1.3.1 (August 2015)

Android Plugin for Gradle, Revision 1.3.0 (July 2015)

Android Plugin for Gradle, Revision 1.2.0 (April 2015)

Android Plugin for Gradle, Revision 1.1.3 (March 2015)

Android Plugin for Gradle, Revision 1.1.2 (February 2015)

Android Plugin for Gradle, Revision 1.1.1 (February 2015)

Android Plugin for Gradle, Revision 1.1.0 (February 2015)

Android Plugin for Gradle, Revision 1.0.1 (January 2015)

Android Plugin for Gradle, Revision 1.0.0 (December 2014)

来源： https://developer.android.com/studio/releases/gradle-plugin.html


SDK Platform Release Notes

This page provides release information about the SDK Platform packages required for app development. If you want details about the features and APIs added in each Android version, instead read the highlights in the About Android section.

To compile your application against a particular version of Android, you must use the SDK Manager to download and install the SDK Platform for that release. If you want to test your application on an emulator, you must also download at least one System Image for that Android version.

Each platform release includes system images that support a specific processor architecture, such as ARM EABI, Intel x86 or MIPS. Platform releases also include a system image that contains Google APIs. The SDK Manager lists available platform system images under each platform version header, for example:

  • ARM EABI v7a System Image
  • Intel x86 Atom System Image
  • MIPS System Image
  • Google APIs

To determine what revisions of an Android platform you have installed, refer to the Packages listing in the Android SDK Manager.

Important: To download the most recent Android system components from the Android SDK Manager, you must first update the SDK Tools to the most recent release and restart the SDK Manager. If you do not, the latest Android system packages may not be available for download.

Android 6.0

Revision 2 (November 2015)

Fixed bugs in the layout rendering library used by Android Studio.

Dependencies:

  • Android SDK Platform-tools r23 or higher is required.
  • Android SDK Tools 24.3.4 or higher is required.

Revision 1 (August 2015)

Android 5.1

Revision 1 (March 2015)

Android 5.0

Revision 2 (December 2014)

Revision 1 (October 2014)

Device Definitions

The platform includes the following new device definitions for use in creating Android Virtual Devices in the AVD Manager:

  • Nexus 6 (5.96", 1440 x 2560, Normal 560dpi screen)
  • Nexus 9 (8.9", 2048 x 1536, X-Large xhdpi screen)

Android 4.4W

Revision 2 (October 2014)

Revision 1 (June 2014)

Device Definitions

The platform includes the following device definitions for use in creating Android Virtual Devices in the AVD Manager:

  • Android Wear Round (320 x 320, hdpi)
  • Android Wear Square (320 x 320, hdpi)

Android 4.4

Revision 2 (December 2013)

Revision 1 (October 2013)

Google APIs System Image

Revision 4 (March 2014)

Revision 3 (February 2014)

Revision 2 (December 2013)

Revision 1 (October 2013)

Android 4.3

Revision 2 (August 2013)

Revision 1 (July 2013)

Google APIs System Image

Revision 3 (September 2013)

Revision 2 (August 2013)

Revision 1 (July 2013)

Android 4.2

Revision 2 (February 2013)

Revision 1 (November 2012)

Device Definitions

The platform includes the following device definitions for use in creating Android Virtual Devices in the AVD Manager:

  • Nexus 7 (7.3", 800 x 1280, Large tvdpi screen)
  • Galaxy Nexus (4.7", 720 x 1280, Normal xhdpi screen)
  • Nexus S (4.0", 480 x 800, Normal hdpi screen)
  • Nexus One (3.7", 480 x 720, Normal hdpi screen)
  • 10.1" WXGA Tablet (1280 x 800, X-Large mdpi screen)
  • 7.0" WSVGA Tablet (1024 x 600, Large mdpi screen)
  • 5.4" FWVGA (480 x 854, Large mdpi screen)
  • 5.1" WVGA (480 x 800, Large mdpi screen)
  • 4.7" WXGA (1280 x 720, Normal xhdpi screen)
  • 4.65" 720p (720 x 1280, Normal xhdpi screen)
  • 4.0" WVGA (480 x 800, Normal hdpi screen)
  • 3.7" WVGA (480 x 800, Normal hdpi screen)
  • 3.7" FWVGA slider (480 x 854, Normal hdpi screen)
  • 3.4" WQVGA (240 x 432, Normal ldpi screen)
  • 3.3" WQVGA (240 x 400, Normal ldpi screen)
  • 3.2" QVGA ADP2 (320 x 480, Normal mdpi screen)
  • 3.2" HVGA slider ADP1 (320 x 480, Normal mdpi screen)
  • 2.7" QVGA slider (240 x 320, Small ldpi screen)
  • 2.7" QVGA (240 x 320, Small ldpi screen)

Android 4.1

Revision 3 (October 2012)

Revision 2 (July 2012)

Revision 1 (June 2012)

Emulator Skins

The downloadable platform includes the following emulator skins:

  • QVGA (240x320, low density, small screen)
  • WQVGA400 (240x400, low density, normal screen)
  • WQVGA432 (240x432, low density, normal screen)
  • HVGA (320x480, medium density, normal screen)
  • WVGA800 (480x800, high density, normal screen)
  • WVGA854 (480x854 high density, normal screen)
  • WXGA720 (1280x720, extra-high density, normal screen)
  • WSVGA (1024x600, medium density, large screen)
  • WXGA800-7in (1280x800, high density, large screen) new
  • WXGA800 (1280x800, medium density, xlarge screen)

To test your application on an emulator that represents the Nexus 7 tablet device, you can create an AVD with the new WXGA800-7in skin. For best performance, make sure to enable graphics acceleration in the emulator configuration.

Android 4.0.3

Revision 3 (March 2012)

Revision 2 (January 2012)

Revision 1 (December 2011)

Emulator Skins

The downloadable platform includes the following emulator skins:

  • QVGA (240x320, low density, small screen)
  • WQVGA400 (240x400, low density, normal screen)
  • WQVGA432 (240x432, low density, normal screen)
  • HVGA (320x480, medium density, normal screen)
  • WVGA800 (480x800, high density, normal screen)
  • WVGA854 (480x854 high density, normal screen)
  • WXGA720 (1280x720, extra-high density, normal screen)
  • WSVGA (1024x600, medium density, large screen)
  • WXGA (1280x800, medium density, xlarge screen)

Android 4.0

Android 4.0, Revision 2 (December 2011)

Android 4.0, Revision 1 (October 2011)

Emulator Skins

The downloadable platform includes the following emulator skins:

  • QVGA (240x320, low density, small screen)
  • WQVGA400 (240x400, low density, normal screen)
  • WQVGA432 (240x432, low density, normal screen)
  • HVGA (320x480, medium density, normal screen)
  • WVGA800 (480x800, high density, normal screen)
  • WVGA854 (480x854 high density, normal screen)
  • WXGA720 (1280x720, extra-high density, normal screen) new
  • WSVGA (1024x600, medium density, large screen) new
  • WXGA (1280x800, medium density, xlarge screen)

To test your application on an emulator that represents the latest Android device, you can create an AVD with the new WXGA720 skin (it's an xhdpi, normal screen device). Note that the emulator currently doesn't support the new on-screen navigation bar for devices without hardware navigation buttons, so when using this skin, you must use keyboard keys Home for the Home button, ESC for the Back button, and F2 or Page-up for the Menu button.

However, due to performance issues in the emulator when running high-resolution screens such as the one for the WXGA720 skin, we recommend that you primarily use the traditional WVGA800 skin (hdpi, normal screen) to test your application.

Android 3.2

Android 3.2, Revision 1 (July 2011)

Emulator Skins

The downloadable platform includes the following emulator skin:

  • WXGA (1280x800, medium density, xlarge screen)

For more information about how to develop an application that displays and functions properly on all Android-powered devices, see Supporting Multiple Screens.

Android 3.1

Android 3.1, Revision 3 (July 2011)

Android 3.1, Revision 2 (May 2011)

Android 3.1, Revision 1 (May 2011)

Emulator Skins

The downloadable platform includes the following emulator skin:

  • WXGA (1280x800, medium density, xlarge screen)

For more information about how to develop an application that displays and functions properly on all Android-powered devices, see Supporting Multiple Screens.

Android 3.0

Android 3.0, Revision 2 (July 2011)

Android 3.0, Revision 1 (February 2011)

Emulator Skins

The downloadable platform includes the following emulator skin:

  • WXGA (1280x800, medium density, xlarge screen)

Android 2.3.4

Android 2.3.4, Revision 1 (May 2011)

Emulator Skins

The downloadable platform includes a set of emulator skins that you can use for modeling your application in different screen sizes and resolutions. The emulator skins are:

  • QVGA (240x320, low density, small screen)
  • WQVGA400 (240x400, low density, normal screen)
  • WQVGA432 (240x432, low density, normal screen)
  • HVGA (320x480, medium density, normal screen)
  • WVGA800 (480x800, high density, normal screen)
  • WVGA854 (480x854 high density, normal screen)

Android 2.3.3

Android 2.3.3, Revision 2 (July 2011)

Android 2.3.3, Revision 1 (February 2011)

Emulator Skins

The downloadable platform includes a set of emulator skins that you can use for modeling your application in different screen sizes and resolutions. The emulator skins are:

  • QVGA (240x320, low density, small screen)
  • WQVGA400 (240x400, low density, normal screen)
  • WQVGA432 (240x432, low density, normal screen)
  • HVGA (320x480, medium density, normal screen)
  • WVGA800 (480x800, high density, normal screen)
  • WVGA854 (480x854 high density, normal screen)

Android 2.3

Android 2.3, Revision 1 (December 2010)

Emulator Skins

The downloadable platform includes a set of emulator skins that you can use for modeling your application in different screen sizes and resolutions. The emulator skins are:

  • QVGA (240x320, low density, small screen)
  • WQVGA400 (240x400, low density, normal screen)
  • WQVGA432 (240x432, low density, normal screen)
  • HVGA (320x480, medium density, normal screen)
  • WVGA800 (480x800, high density, normal screen)
  • WVGA854 (480x854 high density, normal screen)

Android 2.2

Android {@sdkPlatformVersion}, Revision 3 (July 2011)

Android {@sdkPlatformVersion}, Revision 2 (July 2010)

Android {@sdkPlatformVersion}, Revision 1 (May 2010)

Emulator Skins

The downloadable platform includes a set of emulator skins that you can use for modeling your application in different screen sizes and resolutions. The emulator skins are:

  • QVGA (240x320, low density, small screen)
  • WQVGA (240x400, low density, normal screen)
  • FWQVGA (240x432, low density, normal screen)
  • HVGA (320x480, medium density, normal screen)
  • WVGA800 (480x800, high density, normal screen)
  • WVGA854 (480x854 high density, normal screen)

来源： https://developer.android.com/studio/releases/platforms.html


探索 Android Studio

本文内容

  1. 项目结构
  2. 用户界面
  3. Gradle 构建系统
  4. 调试和配置文件工具

Android Studio 是基于 IntelliJ IDEA 的官方 Android 应用开发集成开发环境 (IDE)。除了 IntelliJ 强大的代码编辑器和开发者工具，Android Studio 提供了更多可提高 Android 应用构建效率的功能，例如：

  • 基于 Gradle 的灵活构建系统
  • 快速且功能丰富的模拟器 + 可针对所有 Android 设备进行开发的统一的环境
  • Instant Run，可将变更推送到运行中的应用，无需构建新的 APK
  • 可帮助您构建常用应用功能和导入示例代码的代码模板和 GitHub 集成
  • 丰富的测试工具和框架
  • 可捕捉性能、可用性、版本兼容性以及其他问题的 Lint 工具
  • C++ 和 NDK 支持
  • 内置对 Google 云端平台的支持，可轻松集成 Google Cloud Messaging 和 App 引擎

本页介绍了 Android Studio 的基本功能。 有关最新变更摘要，请参阅 Android Studio 发行说明。

项目结构

图 1. Android 视图中的项目文件。

Android Studio 中的每个项目包含一个或多个含有源代码文件和资源文件的模块。 模块类型包括：

  • Android 应用模块
  • 库模块
  • Google App 引擎模块

默认情况下，Android Studio 会在 Android 项目视图中显示您的项目文件，如图 1 所示。 该视图按模块组织结构，方便您快速访问项目的关键源文件。

所有构建文件在项目层次结构顶层 Gradle Scripts 下显示，且每个应用模块都包含以下文件夹：

  • manifests：包含 AndroidManifest.xml 文件。
  • java：包含 Java 源代码文件，包括 JUnit 测试代码。
  • res：包含所有非代码资源，例如 XML 布局、UI 字符串和位图图像。

磁盘上的 Android 项目结构与此扁平项目结构有所不同。 要查看实际的项目文件结构，可从 Project下拉菜单（在图 1 中显示为 Android）选择 Project。

您也可以自定义项目文件的视图，重点显示应用开发的特定方面： 例如，选择项目的 Problems 视图会显示指向包含任何已识别编码和语法错误（例如布局文件中缺失一个 XML 元素结束标记）的源文件的链接。

图 2. Problems 视图中的项目文件，显示存在问题的布局文件。

如需了解详细信息，请参阅管理项目。

用户界面

Android Studio 主窗口由图 3 标注的几个逻辑区域组成。

图 3. Android Studio 主窗口。

  1. 工具栏提供执行各种操作的工具，包括运行应用和启动 Android 工具。
  2. 导航栏可帮助您在项目中导航，以及打开文件进行编辑。 此区域提供 Project 窗口所示结构的精简视图。
  3. 编辑器窗口是创建和修改代码的区域。 编辑器可能因当前文件类型的不同而有所差异。 例如，在查看布局文件时，编辑器显示布局编辑器。
  4. 工具窗口提供对特定任务的访问，例如项目管理、搜索和版本控制等。 您可以展开和折叠这些窗口。
  5. 状态栏显示项目和 IDE 本身的状态以及任何警告或消息。

您可以通过隐藏或移动工具栏和工具窗口调整主窗口，以便留出更多屏幕空间。 您还可以使用键盘快捷键访问大多数 IDE 功能。

您可以随时通过按两下 Shift 键或点击 Android Studio 窗口右上角的放大镜搜索源代码、数据库、操作和用户界面的元素等。此功能非常实用，例如在您忘记如何触发特定 IDE 操作时，可以利用此功能进行查找。

工具窗口

Android Studio 不使用预设窗口，而是根据情境在您工作时自动显示相关工具窗口。 默认情况下，最常用的工具窗口固定在应用窗口边缘的工具窗口栏上。

  • 要展开或折叠工具窗口，请在工具窗口栏中点击该工具的名称。 您还可以拖动、固定、取消固定、关联和分离工具窗口。
  • 要返回到当前默认工具窗口布局，请点击 Window > Restore Default Layout 或点击 Window > Store Current Layout as Default 自定义默认布局。
  • 要显示或隐藏整个工具窗口栏，请点击 Android Studio 窗口左下角的窗口图标 [image] 。
  • 要找到特定工具窗口，请将鼠标指针悬停在窗口图标上方，并从菜单选择相应的工具窗口。

您也可以使用键盘快捷键打开工具窗口。 表 1 列出了最常用的窗口的快捷键。

表 1. 部分实用工具窗口的键盘快捷键。

工具窗口 | Windows 和 Linux | Mac
项目 | Alt+1 | Command+1
版本控制 | Alt+9 | Command+9
运行 | Shift+F10 | Control+R
调试 | Shift+F9 | Control+D
Android Monitor | Alt+6 | Command+6
返回至编辑器 | Esc | Esc
隐藏所有工具窗口 | Control+Shift+F12 | Command+Shift+F12

如果您想要隐藏所有工具栏、工具窗口和编辑器选项卡，请点击 View > Enter Distraction Free Mode。 此操作可启用无干扰模式。 要退出“无干扰模式”，请点击 View > Exit Distraction Free Mode。

您可以使用快速搜索在 Android Studio 中的大多数工具窗口中执行搜索和筛选。 要使用快速搜索，请选择工具窗口，然后键入搜索查询。

如需了解更多技巧，请参阅键盘快捷键。

代码自动完成

Android Studio 有三种代码自动完成类型，您可以使用键盘快捷键访问它们。

表 2. 代码自动完成的键盘快捷键

类型 | 说明 | Windows 和 Linux | Mac
基本自动完成 | 显示对变量、类型、方法和表达式等的基本建议。 如果连续两次调用基本自动完成，将显示更多结果，包括私有成员和非导入静态成员。 | Control+空格 | Control+空格
智能自动完成 | 根据上下文显示相关选项。 智能自动完成可识别预期类型和数据流。 如果连续两次调用智能自动完成，将显示更多结果，包括链。 | Control+Shift+空格 | Control+Shift+空格
语句自动完成 | 自动完成当前语句，添加缺失的圆括号、大括号、花括号和格式化等。 | Control+Shift+Enter | Shift+Command+Enter

您还可以按 Alt+Enter 执行快速修复并显示建议的操作。

如需了解有关代码自动完成的详细信息，请参阅代码自动完成。

导航

以下是一些操作 Android Studio 的技巧。

  • 使用最近文件操作在最近访问的文件之间切换。 按 Control+E（在 Mac 上，按 Command+E）调出“最近文件”操作。 默认情况下将选择最后一次访问的文件。 在此操作中您还可以通过左侧列访问任何工具窗口。
  • 使用文件结构操作查看当前文件的结构。 按 Control+F12（在 Mac 上，按 Command+F12）调出“文件结构”操作。您可以使用此操作快速导航至当前文件的任何部分。
  • 使用导航至类操作搜索并导航至项目中的特定类。 按 Control+N（在 Mac 上，按 Command+O）调出此操作。 “导航至类”支持复杂的表达式，包括驼峰、路径、直线导航和中间名匹配等。 如果连续两次调用此操作，将显示项目类以外的结果。
  • 使用导航至文件操作导航至文件或文件夹。 按 Control+Shift+N（在 Mac 上，按 Command+Shift+O）调出“导航至文件”操作。要搜索文件夹，但不搜索文件，请在表达式末尾添加“/”。
  • 使用导航至符号操作按名称导航至方法或字段。按 Control+Shift+Alt+N（在 Mac 上，按 Command+Shift+Alt+O）调出“导航至符号”操作。
  • 按 Alt+F7 查找引用当前光标位置处的类、方法、字段、参数或语句的所有代码片段。

样式和格式化

在您编辑时，Android Studio 将自动应用代码样式设置中指定的格式设置和样式。您可以通过编程语言自定义代码样式设置，包括指定选项卡和缩进、空格、换行、花括号以及空白行的约定。要自定义代码样式设置，请点击 File > Settings > Editor > Code Style（在 Mac 上，点击 Android Studio > Preferences > Editor > Code Style）。

虽然 IDE 会在您工作时自动应用格式化，但您也可以通过按 Control+Alt+L（在 Mac 上，按 Opt+Command+L）显式调用重新格式化代码操作，或按Control+Alt+I（在 Mac 上，按 Alt+Option+I*）自动缩进所有行。

图 4. 格式化前的代码。

图 5. 格式化后的代码。

版本控制基础知识

Android Studio 支持多个版本控制系统 (VCS)，包括 Git、GitHub、CVS、Mercurial、Subversion 和 Google Cloud Source Repositories。

在将您的应用导入 Android Studio 后，使用 Android Studio VCS 菜单选项启用对所需版本控制系统的 VCS 支持、创建存储库、导入新文件至版本控制以及执行其他版本控制操作：

  1. 在 Android Studio VCS 菜单中点击 Enable Version Control Integration。
  2. 从下拉菜单中选择要与项目根目录关联的版本控制系统，然后点击 OK。

此时，VCS 菜单将根据您选择的系统显示多个版本控制选项。

注： 您还可以使用 File > Settings > Version Control 菜单选项设置和修改版本控制设置。

Gradle 构建系统

Android Studio 基于 Gradle 构建系统，并通过 Android Gradle 插件提供更多面向 Android 的功能。

该构建系统可以作为集成工具从 Android Studio 菜单运行，也可从命令行独立运行。

您可以利用构建系统的功能执行以下操作：

  • 自定义、配置和扩展构建流程。
  • 使用相同的项目和模块为您的应用创建多个具有不同功能的 APK。
  • 在不同源代码集中重复使用代码和资源。

利用 Gradle 的灵活性，您可以在不修改应用核心源文件的情况下实现以上所有目的。 Android Studio 构建文件以 build.gradle 命名。 这些文件是纯文本文件，使用 Android Gradle 插件提供的元素以 Groovy 语法配置构建。每个项目有一个用于整个项目的顶级构建文件，以及用于各模块的单独的模块层级构建文件。在导入现有项目时，Android Studio 会自动生成必要的构建文件。

如需了解有关构建系统和如何配置的更多信息，请参阅配置构建。

构建变体

构建系统可帮助您从一个项目创建同一应用的不同版本。 如果您同时拥有免费版本和付费版本的应用，或想要在 Google Play 上为不同设备配置分发多个 APK，则可以使用此功能。

如需了解有关配置构建变体的详细信息，请参阅配置 Gradle 构建。

APK 拆分

通过 APK 拆分，您可以高效地基于屏幕密度或 ABI 创建多个 APK。 例如，您可以利用 APK 拆分创建单独的 hdpi 和 mdpi 版本应用，同时仍将它们视为一个变体，并允许其共享测试应用、javac、dx 和 ProGuard 设置。

如需了解有关使用 APK 拆分的详细信息，请参阅 APK 拆分。

资源压缩

Android Studio 中的资源压缩功能可自动从您打包的应用和库依赖关系中删除不使用的资源。 例如，如果您的应用正在使用 Google Play 服务，以访问 Google 云端硬盘功能，且您当前未使用 Google Sign-In，则资源压缩功能可删除 SignInButton 按钮的各种可绘制资产。

注： 资源压缩与代码压缩工具（例如 ProGuard）协同工作。

如需了解有关压缩代码和资源的详细信息，请参阅压缩代码和资源。

管理依赖关系

项目的依赖关系在 build.gradle 文件中按名称指定。 Gradle 可自动查找您的依赖关系，并在构建中提供。 您可以在 build.gradle 文件中声明模块依赖关系、远程二进制依赖关系以及本地二进制依赖关系。 Android Studio 配置项目时默认使用 Maven 中央存储库。 （该配置包含在项目的顶级构建文件中。） 如需了解有关配置依赖关系的详细信息，请参阅配置构建变体。

调试和配置文件工具

Android Studio 可帮助您调试和改进代码的性能，包括内联调试和性能分析工具。

内联调试

使用内联调试功能在调试程序视图中对引用、表达式和变量值进行内联验证，提高代码走查效率。

内联调试信息包括：

  • 内联变量值
  • 引用某选定对象的引用对象
  • 方法返回值
  • Lambda 和运算符表达式
  • 工具提示值

图 6. 内联变量值。

要启用内联调试，请在 Debug 窗口中点击 Settings [image] 并选中 Show Values Inline 复选框。

性能监视器

Android Studio 提供性能监视器，让您可以更加轻松地跟踪应用的内存和 CPU 使用情况、查找已解除内存分配的对象、查找内存泄漏以及优化图形性能和分析网络请求。在设备或模拟器上运行您的应用时，打开 Android Monitor 工具窗口，然后点击 Monitors 选项卡。

如需了解有关性能监视器的详细信息，请参阅 Android Monitor。

堆转储

在 Android Studio 中监控内存使用情况时，您可以同时启动垃圾回收并将 Java 堆转储为 Android 专有 HPROF 二进制格式的堆快照文件。HPROF 查看器显示类、每个类的实例以及引用树，可以帮助您跟踪内存使用情况，查找内存泄漏。

如需了解有关使用堆转储功能的详细信息，请参阅转储和分析 Java 堆。

分配跟踪器

Android Studio 允许在监视内存使用情况的同时跟踪内存分配情况。 利用跟踪内存分配功能，您可以在执行某些操作时监视对象被分配到哪些位置。 了解这些分配后，您就可以相应地调整与这些操作相关的方法调用，从而优化应用的性能和内存使用。

如需了解有关跟踪和分析分配的详细信息，请参阅分配跟踪器。

数据文件访问

Systrace、logcat 和 Traceview 等 Android SDK 工具可生成性能和调试数据，用于对应用进行详细分析。

要查看已生成的数据文件，请打开“Captures”工具窗口。 在已生成的文件列表中，双击相应的文件即可查看数据。右键点击任何 .hprof 文件即可将其转换为标准 .hprof 文件格式。

代码检查

在您每次编译程序时，Android Studio 都将自动运行已配置的 Lint 及其他 IDE 检查，以帮助您轻松识别和纠正代码结构质量问题。

Lint 工具可检查您的 Android 项目源文件是否有潜在的错误，以及在正确性、安全性、性能、可用性、无障碍性和国际化方面是否需要优化改进。

图 7. Android Studio 中 Lint 检查的结果。

除了 Lint 检查，Android Studio 还可以执行 IntelliJ 代码检查和注解验证，以简化您的编码工作流程。

如需了解详细信息，请参阅使用 Lint 改进代码和 lint 工具。

Android Studio 中的注解

Android Studio 支持为变量、参数和返回值添加注解，以帮助您捕捉错误，例如 null 指针异常和资源类型冲突。 Android SDK 管理器将支持注解库纳入 Android 支持存储库中，供与 Android Studio 结合使用。 Android Studio 在代码检查期间验证已配置的注解。

有关 Android 注解的更多详细信息，请参阅使用注解改进代码检查。

日志消息

在使用 Android Studio 构建和运行应用时，您可以点击窗口底部的 Android Monitor 查看 adb 输出和设备日志消息 (logcat)。

如果您想使用 Android 设备监视器调试您的应用，您可以点击 Tools > Android > Android Device Monitor 启动设备监视器。设备监视器中提供全套的 DDMS 工具，您可以使用这些工具进行应用分析和设备行为控制等操作。此外，该监视器还包括层次结构查看器工具，可帮助您优化布局。

来源： https://developer.android.com/studio/intro/index.html