Android studio русская версия


Знакомьтесь: Android Studio

Статья проплачена кошками - всемирно известными производителями котят.

Если статья вам понравилась, то можете поддержать проект.

Статья была начата, когда студия существовала в бета-версии. По мере развития среды разработки в статью будут добавляться новые материалы.

15 мая на конференции Google I/O 2013 объявили о новой среде разработки Android Studio. Основой для новой IDE стала платформа IntelliJ от компании JetBrains. У этой платформы было много поклонников, поэтому эта новость их сильно обрадовала. На данный момент это только бета-версия для тех, кто любит экспериментировать. Скачать новую среду разработки можно по адресу http://developer.android.com/sdk/installing/studio.html.

Основные особенности - реализована возможность вёрстки в реальном времени, доступно множество вариантов размеров и разрешений экранов. Присутствует раздел справки. Встроены инструменты улучшения качества приложений и монетизации. Имеются инструменты для отслеживания эффективности рекламных объявлений. Добавлено средство взаимодействия с бета-тестерами. И многое другое.

Процесс установки прост (далее мой опыт установки под Windows 8) - скачиваем программу и начинаем процесс установки. После окончания установки, если стоит соответствующий флажок, ждём запуска студии. Но ничего не запускается. Странно. Идем в папку, в которую устанавливали программу и пробуем запустить файл studio.exe Безрезультатно.

В интернете прочитал совет, который помог лично мне. Нужно прописать переменную среды окружения. В проводнике щёлкаем правой кнопкой мыши на значке Computer (у меня английская версия Windows 8) и выбираем Properties, чтобы открыть компонент панели управления System. В данном окне выбираем пункт Advanced system settings - откроется диалоговое окно, в котором нужно щёлкнуть на кнопке Environment Variables.... Откроется ещё одно диалоговое окно.

В секции System variables нажимаем на кнопку New... и добавляем в текстовое поле Variable name новое имя JAVA_HOME, а в текстовом поле Variable value добавляем путь к Java JDK - в моём случае это был C:\Program Files\Java\jdk1.6.0_39. После этого Android Studio запустился.

Если вы уже набили руку на разработке программы в Eclipse, то первые шаги будут знакомы, поменяется только внешний вид мастера создания нового проекта, а принцип остался прежним.

Рассмотрим по шагам. Процесс показан на версии 0.6.1

Запускаем Android Studio:

Выбираем новый проект и заполняем необходимые поля. Надо указать приложения в первом поле. Во втором следует указать домен компании. По умолчанию студия может подставить имя пользователя на компьютере. Лучше сразу изменить на удобное название, которое студия запомнит и будет подставлять в новых проектах. Поле Company Domain используется для формирования пакета (Package name) в перевёрнутом виде, как это принято в Java. Если вы не изменили имя домена, но имя пакета вас не устраивает, то можете нажать на кнопку Edit и отредактировать имя пакета.

Далее выбирается минимальный уровень для приложения. В предыдущем релизе по умолчанию использовался API для Android 2.2. И вот произошло знаковое событие. Теперь предлагают писать приложения сразу для Android 4.0.3. Конечно, вы можете выбрать из списка другой вариант.

Затем выбирается тип приложения. Для новичков следует выбирать вариант Blank Activity.

Последний шаг - выбираем имена для активности, разметки и заголовка. Здесь тоже произошли изменения. Раньше использовался вариант со словом "main" - MainActivity, activity_main.

(Так как потом студия обновляется и нет надобности ставить её с нуля, то я не знаю, осталось ли это в новых версиях). Далее на экране возник индикатор прогресса, который что-то загружал с использованием Gradle. Но индикатор висел на экране долго. Это было в старых версиях.

Удивило, что теперь не надо выбирать значок для программы. Ещё заметил, что в манифесте теперь убрали <uses-sdk></uses-sdk>. Теперь эти настройки хранятся в файлах Gradle.

Старые варианты

Студия в последнее время постоянно меняет свой внешний вид. Оставлю на память.

Выбираем новый проект и заполняем необходимые поля.

Выбираем значок для программы:

Выбираем шаблон:

Настройки для активности:

Далее пошло новшество - на экране возник индикатор прогресса, который что-то загружал с использованием Gradle. Что это такое, я не знаю. Но индикатор висел на экране долго.

На этом процесс создания проекта был закончен. Сама среда разработки выглядела непривычно. Понадобится время на привыкание.

Миграция проектов с Eclipse

Чтобы перенести проект из Eclipse в Android Studio, экспортируйте его в Eclipse через команду File | Export... и выберите в диалоговом окне папку Android, а затем пункт Generate Gradle built files. Затем вы можете импортировать проект в Android Studio.

Изменения

Android Studio 3.0

17 мая 2017 года на Google IO объявили о выходе новой версии Android Studio 3.0 Canary 1 (запись).

Официально объявили о поддержке Kotlin. Добавлены и улучшены многие инструменты в составе студии. Появились новые шаблоны, поддержка Java 8 и многое другое.

Android Studio 2.3

После долгого перерыва 2 марта 2017 года вышла версия 2.3 (запись).

Основные изменения.

  • Поддержка формата WebP. В контекстном меню появилась команда конвертации в данный формат. А также обратный процесс.
  • Добавлен новый макет ConstraintLayout. В шаблонах заменили примеры с RelativeLayout на данный макет
  • Снова переработан Layout Editor - добавлен поиск и возможность настройки панели инструментов
  • В окне свойств компонентов появилась возможность отметить любимые свойства звёздочкой, чтобы они всегда были на виду
  • Окно выбора векторных значков обзавелось поиском, а также названиями под значками
  • Появился новый шаблон Bottom Navigation Activity
  • Можно копировать текст из эмулятора и вставлять в приложение на компьютере
  • Появились новые утилиты командной строки, которые заменили некоторые старые утилиты

Android Studio 2.2

19 сентября 2016 вышла стабильная версия 2.2. Изменения колоссальные, можно было присвоить номер 3.0. Запись в блоге - Android Studio 2.2.

Основные изменения.

  • Новый редактор разметки экрана Layout Editor с поддержкой ConstraintLayout
  • Новый Layout Inspector, позволяющий оценить иерархию элементов макета
  • Новый инструмент Assistant для интеграции Firebase в ваше приложение
  • Новый инструмент Analyzer tool для анализа содержимого приложения
  • Новый Espresso Test Recorder (beta) для создания UI-тестов при помощи записи ваших действий
  • Окно Run window теперь содержит записи логов для текущего запущенного приложения
  • Новые возможности в эмуляторе: новые виртуальные сенсоры и настройки сотовой связи
  • Поддержка OpenJDK 8. Существующие проекты могут использовать прежний JDK, заданный в File > Project Structure > SDK Location. Для переключения используйте File > Project Structure > SDK Location и выберите флажок Use embedded JDK
  • Поменяли значки и некоторые элементы меню
  • Улучшен диалог создания нового класса
  • Улучшен редактор Vector Asset Studio с поддержкой Adobe Photoshop Document (PSD)
  • Улучшен Image Asset Studio
  • Улучшен редактор тем

Это только часть изменений.

Android Studio 2.1.2

Шаблон Blank Activity переименовали в Basic Activity.

Android Studio 2.1

26 апреля вышла финальная версия за номером 2.1. Запись в блоге разработчиков - Android Studio 2.1 supports Android N Developer Preview | Android Developers Blog

Появилась поддержка Java 8. Почитать на русском на странице документации.

Android Studio 2.0

23 ноября 2015 объявили о выходе Android Studio 2.0 Preview. Финальная версия вышла 7 апреля 2016 года. Основные революционные изменения - переработанный эмулятор с сервисами Google, камерой, GPS, который работает намного быстрее и новая функция «Instant Run», которая позволяет почти мгновенно обновлять запущенное под отладкой мобильное приложение при изменении исходного кода.

Скорость эмулятора ускорилась в 3 раза, чем предыдущая версия. А скорость передачи приложения в 10 раз быстрее, чем на реальное устройство.

GPU profiler - появилась версия профилировщика рендера средствами GPU. С помощью этого инструмента разработчики могут анализировать время рендеринга элементов в каждом кадре и находить «узкие места».

Функция Instant Run доступна и на эмуляторе, и на физическом устройстве, при условии что приложение собирается для версии Android «Ice Cream Sandwich» или старше.

Android Studio 1.5

19 ноября 2015 года вышла версия 1.5. Заметных изменений не видно, поправили баги, что-то там улучшили.

Android Studio 1.4

30 сентября 2015 года вышла новая версия с большими изменениями.

Vector Asset Studio

Появился новый мастер Vector Asset Studio для создания векторных значков VectorDrawable. Для этого нужно прописать новую версию Gradle вручную (позже это будет сделано автоматически)

classpath 'com.android.tools.build:gradle:1.4.0-beta3'

После этого вы можете щёлкнуть правой кнопкой мыши на папке res/drawable и выбрать из контекстного меню пункт New | Vector Asset.

Существует некоторая обратная поддержка для устройств ниже версии 21. Плагин Gradle автоматически сгенерирует PNG-файлы для разных разрешений экрана.

Редактор тем

Появился редактор тем для редактирования файла colors.xml, содержащий настройки цвета для Material Design. Пока это экспериментальный выпуск. В дальнешнем редактор обещают доработать для сложных вещей. Доступ к редактору осуществляется через меню Tools | Android | Theme Editor.

Новые шаблоны

Добавились новые шаблоны, включая поддержку Android Design Support Library. Общий внешний вид мастера выбора шаблона был перерисован под новый дизайн. Теперь можно выбрать шаблоны с плавающей кнопкой Floating action button (FAB) Blank Activity, с выдвижной шторкой Navigation Drawer Activity, активность с прокруткой Scrolling Activity.

Стандартный минимальный шаблон для начинающих получил название Empty Activity вместо прежнего Blank Activity.

Новые вкладки

Новые вкладки для мониторинга: GPU Rendering Monitor. На устройстве или эмуляторе включить опцию Setting | Developer Options | Profile GPU rendering _ In adb shell dumpsys gfxinfo.

Новая вкладка Network Monitor.

Firebase

Упрощена работа с Firebase. Выберите File | Project Structure | Cloud.

Android Studio 1.4 | Android Developers Blog

Android Studio 1.3

Get your hands on Android Studio 1.3 | Android Developers Blog

v 1.2. Google AdMob Ads Activity

В версии 1.2 заметил новый шаблон Google AdMob Ads Activity для встраивания рекламы.

Также улучшили редактор кода. Например, если вы редактируете название открывающего тега, то закрывающий тег меняется автоматически. Также были немного переработаны некоторые некоторые детали интерфейса, добавлены новые вкладки.

Множественное выделение - нажмите клавиши Shift+Alt и выделяйте мышкой нужные участи кода.

v 0.5.6. Google Play Services Activity

В версии 0.5.6 появились новые шаблоны Google Play Services Activity, Navigation Drawer Activity, Tabbed Activity.

Navigation Editor

В студии появился новый инструмент Navigation Editor, доступный через меню Tools | Android | Navigation Editor. Он позволяет быстро набросать макет из нескольких экранов и даже получить готовый код.

Небольшое описание, как пользоваться редактором, я выложил на Хабре.

v0.5.4. Карты

Начиная с версии 0.5.4, в Android Studio появился новый шаблон с использованием Гуглокарты - Google Maps Activity.

Дополнительное чтение

Создание фрагментов в Android Studio

Советы для Android Studio

Android Studio Tips & Tricks: Moving Around

Adding a Backend to Your App In Android Studio

Реклама

developer.alexanderklimov.ru

Configure Android Studio | Android Studio

Android Studio provides wizards and templates that verify your system requirements, such as the Java Development Kit (JDK) and available RAM, and configure default settings, such as an optimized default Android Virtual Device (AVD) emulation and updated system images. This document describes additional configuration settings you may want to use to customize your use of Android Studio.

Android Studio provides access to two configuration files through the Help menu:

  • studio.vmoptions: Customize options for Studio's Java Virtual Machine (JVM), such as heap size and cache size. Note that on Linux machines this file may be named studio64.vmoptions, depending on your version of Android Studio.
  • idea.properties: Customize Android Studio properties, such as the plugins folder path or maximum supported file size.

For specific documentation about emulator and device setup and use, see Managing Virtual Devices, Using Hardware Devices, and OEM USB Drivers.

Find your configuration files

Both configuration files are stored in the configuration folder for Android Studio. The name of the folder depends on your Studio version. For example, Android Studio 2.2 has the folder name AndroidStudio2.2. The location of this folder depends on your operating system:

  • Windows: %USERPROFILE%\.<CONFIGURATION_FOLDER>/
  • Mac: ~/Library/Preferences/<CONFIGURATION_FOLDER>/
  • Linux: ~/.<CONFIGURATION_FOLDER>/

You can also use the following environment variables to point to specific override files elsewhere:

  • STUDIO_VM_OPTIONS: set the name and location of the .vmoptions file
  • STUDIO_PROPERTIES: set the name and location of the .properties file
  • STUDIO_JDK: set the JDK with which to run Studio

Customize your VM options

The studio.vmoptions file allows you to customize options for Android Studio's JVM. To improve Studio's performance, the most common option to adjust is the maximum heap size, but you can also use the studio.vmoptions file to override other default settings such as initial heap size, cache size, and Java garbage collection switches.

To create a new studio.vmoptions file or to open your existing one, use the following steps:

  1. Click Help > Edit Custom VM Options. If you have never edited VM options for Android Studio before, the IDE prompts you to create a new studio.vmoptions file. Click Yes to create the file.
  2. The studio.vmoptions file opens in the editor window of Android Studio. Edit the file to add your own customized VM options. For a full list of customizable JVM options, see Oracle's Java HotSpot VM Options page.

The studio.vmoptions file you create gets added to the default studio.vmoptions file, located in the bin/ directory inside your Android Studio installation folder.

Note that you should never directly edit the studio.vmoptions file found inside the Android Studio program folder. While you can access the file to view Studio's default VM options, editing only your own studio.vmoptions file ensures that you don't override important default settings for Android Studio. Therefore, in your studio.vmoptions file, override only the attributes you care about and allow Android Studio to continue using default values for any attributes you have not changed.

Maximum heap size

By default, Android Studio has a maximum heap size of 1280MB. If you are working on a large project, or your system has a lot of RAM, you can improve performance by increasing the maximum heap size in the VM options for Android Studio. If your system is memory-constrained, you may wish to reduce the maximum heap size.

To change the maximum heap size, follow these steps:

  1. Click Help > Edit Custom VM Options to open your studio.vmoptions file.
  2. Add a line to the studio.vmoptions file to set maximum heap size using the syntax -XmxheapSize. The size you choose should be based on the size of your project and the available RAM on your machine. As a baseline, if you have more than 4GB of RAM and a medium-sized project, you should set the maximum heap size to 2GB or more. The following line sets the maximum heap size to 2GB: -Xmx2g
  3. Save your changes to the studio.vmoptions file, and restart Android Studio for your changes to take effect.
  4. To confirm your new maximum heap size, open the command line, and type the following command: jps -lvm

    You will see a list of the instrumented JVMs running on your machine, including the full package name for each and the arguments passed in. Locate the item corresponding to your instance of Android Studio. It should end with -Didea.paths.selector=AndroidStudio[Version]. You should see two arguments beginning with -Xmx for this JVM, one with the default value of 1280mb, and one with your new value, as shown in figure 1.

    Figure 1. The terminal output showing the current arguments for Android Studio's JVM.

    1. The -Xmx argument showing the default maximum heap size, in this case 1280m.
    2. The -Didea.paths.selector showing the version of Android Studio currently running.
    3. The -Xmx argument showing the new custom maximum heap size. Note that this is followed by the location the custom studio.vmoptions file you created above.

Export and import IDE settings

You can export a settings JAR file (Settings.jar) that contains all or a subset of your preferred IDE settings for a project. You can then import the JAR file into your other projects and/or make the JAR file available to your colleagues to import into their projects.

For more information, see Exporting and Importing Settings at IntelliJ IDEA.

Customize your IDE properties

The idea.properties file allows you to customize IDE properties for Android Studio, such as the path to user installed plugins and the maximum file size supported by the IDE. The idea.properties file gets merged with the default properties for the IDE so you can specify just the override properties.

To create a new idea.properties file or to open your existing file, use the following steps:

  1. Click Help > Edit Custom Properties. If you have never edited the IDE properties before, Android Studio prompts you to create a new idea.properties file. Click Yes to create the file.
  2. The idea.properties file opens in the editor window of Android Studio. Edit the file to add your own customized IDE properties.

The following idea.properties file includes the commonly customized IDE properties. For a complete list of properties, read about the idea.properties file for IntelliJ IDEA.

#--------------------------------------------------------------------- # Uncomment this option if you want to customize path to user installed plugins folder. Make sure # you're using forward slashes. #--------------------------------------------------------------------- # idea.plugins.path=${idea.config.path}/plugins #--------------------------------------------------------------------- # Maximum file size (kilobytes) IDE should provide code assistance for. # The larger file is the slower its editor works and higher overall system memory requirements are # if code assistance is enabled. Remove this property or set to very large number if you need # code assistance for any files available regardless their size. #--------------------------------------------------------------------- idea.max.intellisense.filesize=2500 #--------------------------------------------------------------------- # This option controls console cyclic buffer: keeps the console output size not higher than the # specified buffer size (Kb). Older lines are deleted. In order to disable cycle buffer use # idea.cycle.buffer.size=disabled #--------------------------------------------------------------------- idea.cycle.buffer.size=1024 #--------------------------------------------------------------------- # Configure if a special launcher should be used when running processes from within IDE. # Using Launcher enables "soft exit" and "thread dump" features #--------------------------------------------------------------------- idea.no.launcher=false #--------------------------------------------------------------------- # To avoid too long classpath #--------------------------------------------------------------------- idea.dynamic.classpath=false #--------------------------------------------------------------------- # There are two possible values of idea.popup.weight property: "heavy" and "medium". # If you have WM configured as "Focus follows mouse with Auto Raise" then you have to # set this property to "medium". It prevents problems with popup menus on some # configurations. #--------------------------------------------------------------------- idea.popup.weight=heavy #--------------------------------------------------------------------- # Use default anti-aliasing in system, i.e. override value of # "Settings|Editor|Appearance|Use anti-aliased font" option. May be useful when using Windows # Remote Desktop Connection for instance. #--------------------------------------------------------------------- idea.use.default.antialiasing.in.editor=false #--------------------------------------------------------------------- # Disabling this property may lead to visual glitches like blinking and fail to repaint # on certain display adapter cards. #--------------------------------------------------------------------- sun.java2d.noddraw=true #--------------------------------------------------------------------- # Removing this property may lead to editor performance degradation under Windows. #--------------------------------------------------------------------- sun.java2d.d3d=false #--------------------------------------------------------------------- # Workaround for slow scrolling in JDK6 #--------------------------------------------------------------------- swing.bufferPerWindow=false #--------------------------------------------------------------------- # Removing this property may lead to editor performance degradation under X Window. #--------------------------------------------------------------------- sun.java2d.pmoffscreen=false #--------------------------------------------------------------------- # Workaround to avoid long hangs while accessing clipboard under Mac OS X. #--------------------------------------------------------------------- # ide.mac.useNativeClipboard=True #--------------------------------------------------------------------- # Maximum size (kilobytes) IDEA will load for showing past file contents - # in Show Diff or when calculating Digest Diff #--------------------------------------------------------------------- # idea.max.vcs.loaded.size.kb=20480

Configure the IDE for low-memory machines

If you are running Android Studio on a machine with less than the recommended specifications (see System Requirements), you can customize the IDE to improve performance on your machine, as follows:

Configure your project for Instant Run

Instant Run is a behavior for the Run and Debug commands that significantly reduces the time between updates to your app. Although your first build may take longer to complete, Instant Run pushes subsequent updates to your app without building a new APK, so changes are visible much more quickly.

Android Studio enables Instant Run by default for projects built using Android plugin for Gradle 2.0.0 and higher. You can improve build performance with Instant Run by modifying a few settings for your project. For more information about configuring your project for Instant Run, read Configure and optimize your project for Instant Run.

Set the JDK version

A copy of the latest OpenJDK comes bundled with Android Studio 2.2 and higher, and this is the JDK version we recommend you use for your Android projects. To use the bundled JDK, proceed as follows:

  1. Open your project in Android Studio and select File > Project Structure in the menu bar.
  2. In the SDK Location page and under JDK location, check the Use embedded JDK checkbox.
  3. Click OK.

By default, the Java language version used to compile your project is based on your project's compileSdkVersion (because different versions of Android support different versions of Java). If necessary, you can override this default Java version by adding the following CompileOptions {} block to your build.gradle file:

android { compileOptions { sourceCompatibility JavaVersion.VERSION_1_6 targetCompatibility JavaVersion.VERSION_1_6 } }

For more information about where compileSdkVersion is defined, read about the module-level build file.

Set proxy settings

Proxies serve as intermediary connection points between HTTP clients and web servers that add security and privacy to internet connections.

To support running Android Studio behind a firewall, set the proxy settings for the Android Studio IDE. Use the Android Studio IDE HTTP Proxy settings page to set the HTTP proxy settings for Android Studio.

When running the Android plugin for Gradle from the command line or on machines where Android Studio is not installed, such as continuous integration servers, set the proxy settings in the Gradle build file.

Note: After the initial installation of the Android Studio bundle, Android Studio can run with internet access or off-line. However, Android Studio requires an internet connection for Setup Wizard synchronization, 3rd-party library access, access to remote repositories, Gradle initialization and synchronization, and Android Studio version updates.

Set up the Android Studio proxy

Android Studio supports HTTP proxy settings so you can run Android Studio behind a firewall or secure network. To set the HTTP proxy settings in Android Studio:

  1. From the menu bar, click File > Settings (on a Mac, click Android Studio > Preferences).
  2. In the left pane, click Appearance & Behavior > System Settings > HTTP Proxy. The HTTP Proxy page appears.
  3. Select Auto-detect proxy settings to use an automatic proxy configuration URL for the proxy settings or Manual proxy configuration to enter each of the settings yourself. For a detailed explanation of these settings, see HTTP Proxy.
  4. Click Apply or OK for your changes to take effect.

Android plugin for Gradle HTTP proxy settings

When running the Android plugin from the command line or on machines where Android Studio is not installed, set the Android plugin for Gradle proxy settings in the Gradle build file.

For application-specific HTTP proxy settings, set the proxy settings in the build.gradle file as required for each application module.

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

For project-wide HTTP proxy settings, set the proxy settings in the gradle/gradle.properties file.

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

For information about using Gradle properties for proxy settings, see the Gradle User Guide.

Note: When using Android Studio, the settings in the Android Studio IDE HTTP proxy settings page override the HTTP proxy settings in the gradle.properties file.

developer.android.com

Android Studio Release Notes | Android Studio

Android Studio is the official IDE for Android development, and includes everything you need to develop Android apps in a single download. Download Android Studio here and get started by reading 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).

The sections below provide notes about successive releases of Android Studio, as denoted by revision number.

Android Studio v2.3.0 (March 2017)

Android Studio 2.3.0 is primarily a bug fix and stability release, but it also includes a number of new features.

Android Studio v2.3.3 (June 2017)

This is a minor update to add support for Android O (API level 26).

Android Studio v2.3.2 (April 2017)

This is a minor update to Android Studio 2.3 for the following changes:

  • AVD Manager updates to support Google Play in system images.
  • Bug fixes for NDK builds when using R14+ of the NDK.

Also see corresponding updates for Android Emulator 26.0.3.

Android Studio v2.3.1 (April 2017)

This is a minor update to Android Studio 2.3 that fixes an issue where some physical Android devices did not work properly with Instant Run (see Issue #235879).

New

  • Android Studio can now convert PNG, BMP, JPG, and static GIF files to WebP format. WebP is an image file format from Google that provides lossy compression (like JPEG) as well as transparency (like PNG) but can provide better compression than either JPEG or PNG. For more information, see Convert Images to WebP in Android Studio.
  • The new App Links Assistant simplifies the process of adding Android App Links to your app into a step-by-step wizard. Android App Links are HTTP URLs that bring users directly to specific content in your Android app.
  • The Layout Editor now includes support for two new ConstraintLayout features:
    • Define a view size based on an aspect ratio.
    • Create packed, spread, and weighted linear groups with constraint chains.
    For more information, see Build a Responsive UI with ConstraintLayout.
  • The Layout Editor also now lets you create a list of favorite attributes so you don't have to click View all attributes to access the attributes you use most.
  • When adding a material icon using the Vector Import Dialog (File > New > Vector Asset), you can now filter the list of available icons by category or by icon name. For more information, see Adding a material icon.
  • New and updated annotations. The new @RestrictTo annotation for methods, classes, and packages lets you restrict an API. The updated @VisibleForTesting annotation now has an optional otherwise argument that lets you designate what the visibility of a method should be if not for the need to make it visible for testing. Lint uses the otherwise option to enforce the intended visibility of the method.
  • New lint baseline support allows you to use a snapshot of your project's current set of warnings as a baseline for future inspection runs so only new issues are reported. The baseline snapshot lets you start using lint to fail the build for new issues without having to go back and address all existing issues first.
  • New lint checks, including the following:
    • Obsolete SDK_INT Checks: Android Studio removes obsolete code that checks for SDK versions.
    • Object Animator Validation: Lint analyzes your code to make sure that your ObjectAnimator calls reference valid methods with the right signatures and checks that those methods are annotated with @Keep to prevent ProGuard from renaming or removing them during release builds.
    • Unnecessary Item Decorator Copy: Older versions of the RecyclerView library did not include a divider decorator class, but one was provided as a sample in the support demos. Recent versions of the library have a divider decorator class. Lint looks for the old sample and suggests replacing it with the new one.
    • WifiManager Leak: Prior to Android 7.0 (API level 24), initializing the WifiManager with Context.getSystemService() can cause a memory leak if the context is not the application context. Lint looks for these initializations, and if it cannot determine that the context is the application context, it suggests you use Context.getApplicationContext() to get the proper context for the initialization.
    • Improved Resource Prefix: The existing resourcePrefix lint check had many limitations. You can now configure your project with a prefix, such as android { resourcePrefix 'my_lib' }, and lint makes sure that all of your resources are using this prefix. You can use variations of the name for styles and themes. For example for the my_lib prefix, you can have themes named MyLibTheme, myLibAttr, my_lib_layout, and so on.
    • Switch to WebP: This check identifies images in your project that can be converted to WebP format based on your project’s minSdkVersion setting. An associated quickfix can automatically convert the images, or you can convert images to WebP manually.
    • Unsafe WebP: If your project already includes WebP images, this check analyzes your project to ensure that your minSdkVersion setting is high enough to support the included images. For more information about WebP support in Android and Android Studio, see Which browsers natively support WebP? and Create WebP Images Using Android Studio.

Changes

  • A separate button to push changes with Instant Run: After deploying your app, you now click Apply Changes to quickly push incremental changes to your running app using Instant Run. The Run and Debug buttons are always available to you when you want to reliably push your changes and force an app restart.
    • Instant Run is supported only when deploying your app to a target device running Android 5.0 (API level 21) or higher.
    • Instant Run is no longer disabled for projects that link to external native projects using CMake or ndk-build. However, you can only use Instant Run to push incremental changes to your Java code, not your native code.
    • Cold swaps (which you can force for a running app by clicking Run ) are now more reliable. Forcing a cold swap also fixes the issue where changes to notification and widget UIs were not updated on the target device.
    • Includes optimizations that make app startup much faster. These optimizations may affect profiling, so you should temporarily disable Instant Run whenever profiling your app.
  • The AVD Manager and SDK Manager buttons are now included in the lean Navigation Bar as well as the full Toolbar. To use the lean Navigation Bar, click View to open the View menu, then ensure that Navigation Bar is selected and Toolbar is not selected.

  • The "Hybrid" debugger has been renamed to "Dual" debugger.
  • In the Run/Debug Configurations dialog, under Defaults in the left pane, the following run configuration names have changed with no behavior changes:
    • The JUnit name has changed to Android JUnit. If you have a project that uses JUnit run configurations, those configurations are transformed to Android JUnit run configurations the first time you open the project with Android Studio. A dialog appears to inform you of the name change.
    • The Android Tests name has changed to Android Instrumented Tests.
  • The GPU Debugger has been removed from Android Studio as of version 2.3. An open-source, standalone version of the tool is now available on GitHub.
  • The Run/Debug option is no longer available when you right-click a *.gradle build script.
  • All templates now use ConstraintLayout as the default layout.
  • The Widgets palette in the Layout Editor has been redesigned.

This release also includes a number of bug fixes. See all bug fixes in 2.3.0.

Known issue: Some device manufacturers block apps from automatically launching after being installed on the device. When deploying your app to a physical device using Android Studio 2.3, this restriction breaks the intended behavior of Instant Run and causes the following error output: Error: Not found; no service started. To avoid this issue, either use the emulator or enable automatic launching for your app in your device's settings. The proceedure for doing this is different for each device, so check the instructions provided by the manufacturer. For example, some affected Asus devices need to whitelist apps using the Auto-start Manager. To learn more about this issue, see Issue #235879.

Android Studio v2.2.0 (September 2016)

Android Studio v2.2.3 (December 2016)

This is a minor update to Android Studio 2.2. It includes a bug fixes focused around gradle, the core IDE, and lint.

Highlighted build changes:

  • ProGuard version rollback. Due to a correctness issue discovered in ProGuard 5.3.1, we have rolled back to ProGuard 5.2.1. We have worked with the ProGuard team on getting a fix quickly, and we expect to roll forward to ProGuard 5.3.2 in Android Studio 2.3 Canary 3.
  • Bug fix for aaptOptions IgnoreAssetsPattern not working properly (issue 224167)
  • Bug fix for Gradle autodownload for Constraint Layout library (issue 212128)
  • Bug fix for a JDK8/Kotlin compiler + dx issue (issue 227729)

See all bug fixes in 2.2.3.

Android Studio v2.2.2 (October 2016)

This is a minor update to Android Studio 2.2. It includes a number of small changes and bug fixes, including:

  • When reporting Instant Run issues through the IDE, the report now also includes logcat output for InstantRun events. To help us improve Instant Run, please enable extra logging and report any issues.
  • A number of small bug fixes for Gradle.
  • A fix for problems with generating multiple APKs.

Android Studio v2.2.1 (October 2016)

This is a minor update to Android Studio 2.2. It includes several bug fixes and a new feature to enable extra logging to help us troubleshoot Instant Run issues—to help us improve Instant Run, please enable extra logging and report any issues.

New

  • All new Layout Editor with tools custom-built to support ConstraintLayout.
  • New Layout Inspector lets you examine snapshots of your layout hierarchy while your app is running on the emulator or a device.
  • New Assistant window to help you integrate Firebase services into your app.
  • New APK Analyzer tool so you can inspect the contents of your packaged app.
  • New Espresso Test Recorder tool (currently in beta) to help you create UI tests by recording your own interactions.
  • New build cache (currently experimental) to speed up build performance.
  • New C/C++ build integration with CMake and ndk-build. Compile and build new or existing native code into libraries packaged into your APK, and debug using lldb. For new projects, Android Studio uses CMake by default, but also supports ndk-build for existing projects. To learn how to include native code in your Android application, read Add C and C++ Code to Your Project. To learn how to debug native code with lldb, see Debug Native Code.
  • New Samples Browser so you can easily look up Google Android sample code from within Android Studio to jump start app development.
  • New Merged Manifest Viewer to help you diagnose how your manifest file merges with your app dependencies across project build variants.
  • The Run window now contains log messages for the current running app. Note that you can configure the logcat Monitor display, but not the Run window.
  • New Android Emulator features:
    • Added new Virtual Sensors and Cellular > Signal Strength controls.
    • Added an LTE option to the Cellular > Network type control.
    • Added simulated vertical swipes for scrolling through vertical menus with a mouse wheel.
  • New Run/Debug Configuration features:
    • The Debugger tab of the Android App and Android Tests templates now contain several new options for debugging with LLDB.
    • The Profiling tab of the Android App and Android Tests templates now contain a Capture GPU Commands option for enabling GPU tracing. You can display GPU traces in the GPU Debugger (a beta feature).
    • The Android Tests template now has a Firebase Test Lab Device Matrix option for the Deployment Target.
    • The Native Application template has been deprecated. If you use this template in a project, Android Studio automatically converts it to the Android App template.
    • The Android Application template has been renamed to Android App.
  • Improved installation, configuration, performance, and UI features in the GPU Debugger (currently in beta).
  • Android Studio now comes bundled with OpenJDK 8. Existing projects still use the JDK specified in File > Project Structure > SDK Location. You can switch to use the new bundled JDK by clicking File > Project Structure > SDK Location and checking the Use embedded JDK checkbox.
  • Added new help menus and buttons in the UI so you can more easily find the online documentation.

Changes

  • Updated the IDE codebase from IntelliJ 15 to IntelliJ 2016.1
  • Instant Run now requires the platform SDK corresponding to the target device API level to be installed.
  • Instant Run will automatically disabled if user is running the app under a work profile or as a secondary user.
  • Fixed many reliability issues for Instant Run where changes were not getting deployed or the app would crash:
    • Some app assets were not deployed to your running app. ( Bug: #213454)
    • App crashes when user transitions between Instant Run and non Instant Run sessions where a Serializable class does not have serialVersionUID defined. (Bug: #209006)
    • Style changes aren’t reflected with Instant Run. (Bug: #210851)
    • Instant Run session is unreliable and causes FileNotFoundException. (Bug: #213083)
    • Changes to drawables not reflected until full rebuild is performed for KitKat. (Bug: #21530)
    • Resource changes aren’t reflected with Instant Run when custom sourceSets contain nested paths. (Bug: #219145)
    • Hot and warm swap don't work if changed class contains annotation with enum value. (Bug: #209047)
    • Changes to annotation data not reflected with Instant Run. (Bug: #210089)
    • Instant Run doesn't pick up code changes if you make changes outside the IDE. (Bug: #213205)
    • Instant Run session is unreliable due to mismatch security token. (Bug: #211989
    • Cold swap fails for devices that doesn’t properly support run-as. (Bug: #210875)
    • App crash after instant run restart. (Bug: #219744)
    • ClassNotFoundException observed when switching from Instant Run to Instant Debug. (Bug: #215805)
  • Improved performance for Gradle sync within the IDE, especially for large projects.
  • Improved build times for both full and incremental builds with new app packaging code.
  • Improved Jack compiler performance and features, including support for annotation processors and dexing in process. To learn more, read the Android plugin for Gradle 2.2.0 release notes.
  • Added an updated AccelerometerPlay sample so you can try out the emulator Accelerometer control. Select File > New > Import Sample to import the project.
  • Removed the Scale AVD property from the AVD Manager.
  • The Android Emulator -port and -ports command-line options now report which ports and serial number the emulator instance is using, and warn if there are any issues with the values you provided.
  • Improved the Create New Class dialog and the corresponding file templates. Note: If you've previously customized the AnnotationType, Class, Enum, Interface, or Singleton file templates, you need to modify your templates to comply with the new templates or you won’t be able to use the new fields in the Create New Class dialog.
  • Improved the Vector Asset Studio user interface and added support for Adobe Photoshop Document (PSD) files.
  • Improved the Image Asset Studio user interface.
  • Improved the Theme Editor's Resource Picker.
  • Fixed memory leaks and reduced overall memory usage in Android Studio.
  • Added a Background button in the SDK Manager so you can get back to work and install your packages in the background.
  • Improved Accessibility features, including support for screen readers and keyboard navigation.
  • Enhanced Code Analysis includes code quality checks for Java 8 language usage and more cross-file analysis.
  • Several toolbar icons have changed.

Android Studio v2.1.0 (April 2016)

The primary changes in this update provide support for development with the Android N Preview.

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)

This update includes a number of small changes and bug fixes:

  • Instant Run updates and bug fixes.
  • Improvements to LLDB performance and crash notifications.
  • Fixed a regression in the Android Studio 2.1.1 security update that caused git rebase to fail.

Android Studio v2.1.1 (May 2016)

Security release update.

The Android N platform adds support for Java 8 language features, which require a new experimental compiler called Jack. The latest version of Jack is currently supported only in Android Studio 2.1. So if you want to use Java 8 language features, you need to use Android Studio 2.1 to build your app.

Note: Instant Run is disabled when you enable the Jack compiler because they currently are not compatible.

Although Android Studio 2.1 is now stable, the Jack compiler is still experimental and you must enable it with the jackOptions property in your build.gradle file.

Other than the changes to support the N Preview, Android Studio 2.1 includes minor bug fixes and the following enhancements:

  • The Java-aware C++ debugger is now enabled by default when you're using an N device or emulator and select Native debugger mode (in the Debugger tab for your run/debug configuration).

For other build enhancements, including incremental Java compilation and dexing-in-process,update your Android plugin for Gradle to version 2.1.0.

Android Studio v2.0.0 (April 2016)

Note: If you are developing for the N Developer Preview, you should use Android Studio 2.1 Preview. Android Studio 2.0 does not support all the features required to target the N Preview. To learn more, read about how to properly set up your developer environment for the N Preview.

Instant Run:

  • Android Studio now deploys clean builds faster than ever before. Additionally, pushing incremental code changes to the emulator or a physical device is now almost instantaneous. Review your updates without redeploying a new debug build or, in many cases, without restarting the app.
  • Instant Run supports pushing the following changes to a running app:
    • Changes to the implementation of an existing instance method or static method
    • Changes to an existing app resource
    • Changes to structural code, such as a method signature or a static field (requires a target device running API level 21 or higher).
  • Read the documentation to learn more about Instant Run.

    Note: Instant Run is supported only when you deploy the debug build variant, use Android plugin for Gradle version 2.0.0 or higher, and configure your app's module-level build.gradle file for minSdkVersion 15 or higher. For the best performance, configure your app for minSdkVersion 21 or higher.

New additions to Lint:

  • Inspection of switch statements using @IntDef annotated integers to make sure all constants are handled. To quickly add any missing statements, use the intention action drop-down menu and select Add Missing @IntDef Constants.
  • Flags for incorrect attempts to use string interpolation to insert version numbers in the build.gradle file.
  • Flags for anonymous classes that extend the Fragment class.
  • Flags for native code in unsafe locations, such as the res/ and asset/ folders. This flag encourages storing native code in the libs/ folder, which is then securely packaged into the application’s data/app-lib/ folder at install time. AOSP: #169950
  • Flags for unsafe calls to Runtime.load() and System.load() calls. AOSP: #179980
  • Find and remove any unused resources by selecting Refactor > Remove Unused Resources from the menu bar. Unused resource detection now supports resources only referenced by unused resources, references in raw files such as .html image references, and tools:keep and tools:discard attributes used by the Gradle resource shrinker, while considering inactive source sets (such as resources used in other build flavors) and properly handling static field imports.
  • Checks that implicit API references are supported on all platforms targeted by minSdkVersion.
  • Flags improper usage of RecyclerView and Parcelable.
  • @IntDef, @IntRange, and @Size inspections are now also checked for int arrays and varargs.

Additional Improvements:

  • Optimized for Android Emulator 2.0, which is faster than ever before, supports a wider range of virtual devices, and features a drastically improved UI. To learn more about the new emulator, read the SDK Tools release notes.
  • Improvements to the Android Virtual Device Manager:
    • System images are now categorized under the following tabs: Recommended, x86, and Other.
    • Under advanced settings, you can enable multi-core support and specify the number of cores the emulator can use.
    • Under advanced settings, you can determine how graphics are rendered on the emulator by selecting one of the following options:
      • Hardware: use you computer's graphics card for faster rendering.
      • Software: use software-based rendering.
      • Auto: let the emulator decide the best option. This is the default setting.
  • Improved AAPT packaging times by specifying deploy target before the app is built. This allows Android Studio to efficiently package only the resources required by the specified device.
  • Added Cloud Test Lab integration to provide on-demand app testing with the convenience and scalability of a cloud service. Learn more about how you can use Cloud Test Lab with Android Studio.
  • Added a preview of the new GPU Debugger. For graphics intensive applications, you can now visually step through your OpenGL ES code to optimize your app or game.
  • Added Google App Indexing Test. Add support for URLs, app indexing, and search functionality to your apps to help drive more traffic to your app, discover which app content is used most, and attract new users. Test and validate URLs in your app all within Android Studio. See Supporting URLs and App Indexing in Android Studio.
  • Upgrades from the latest IntelliJ 15 release, including improved code analysis and performance. See What's New in IntelliJ for a complete description of the new features and enhancements.
  • XML editor auto-complete now adds quotations marks when completing attributes. To check if this option is enabled, open the Setting or Preferences dialogue, navigate to Editor > General > Smart Keys, and check the box next to Add quotes for attribute value on attribute completion. Issue: 195113
  • The XML editor now supports code completion for data binding expressions.

Older Releases

Android Studio v1.5.1 (December 2015)

Fixes and enhancements:

  • Fixed a rendering failure issue in the Layout Editor. Issue: 194612
  • Added the ability to vary description manifest attributes by configuration. Issue: 194705
  • Improved the contrast of the Android Studio Darcula appearance theme in Vector Asset Studio. Issue: 191819
  • Added Help button support to Vector Asset Studio.
  • Added support for the % operator for data binding. Issue: 194045
  • Fixed a case where launching an app for debugging resulted in the debugger connecting to the wrong device. Issue: 195167
  • Fixed a null pointer exception that could occur when attempting to run an app in certain scenarios.

Android Studio v1.5.0 (November 2015)

Fixes and enhancements:

  • Added new Memory Monitor analysis abilities to Android Monitor. When you view an HPROF file captured from this monitor, the display is now more helpful so you can more quickly locate problems, such as memory leaks. To use this monitor, click Android Monitor at the bottom of the main window. In Android Monitor, click the Memory tab. While the monitor is running, click the Dump Java Heap icon, and then click Captures in the main window and double-click the file to view it. Click Capture Analysis on the right. (The Android Device Monitor can't be running at the same time as Android Monitor.)
  • Added new deep link and app link support. The Code Editor can automatically create an intent filter for deep linking in the AndroidManifest.xml file. It can also generate code to help you integrate with the App Indexing API in an activity in a Java file. A deep link testing feature helps you verify that a specified deep link can launch an app. In the General tab of the Run/Debug Configurations dialog, you can specify deep link launch options. You can also test App Indexing API calls in an activity by using the Android Monitor logcat display. The Android lint tool now has warnings for certain issues involving deep links and the App Indexing API.
  • Added the ability to use short names when code-completing custom views in the Code Editor.
  • Added support for more VectorDrawable elements to Vector Asset Studio for backward-compatibility. Vector Asset Studio can use these elements to convert vector drawables into PNG raster images to use with Android 4.4 (API level 20) and lower.
  • Added new lint checks for Android TV and Android Auto to give you immediate, actionable feedback in Android Studio, along with several quick fixes. For example, for Android TV, it can report and provide a quick fix for permissions, unsupported hardware, uses-feature element, and missing banner issues. For Android Auto, it can validate the correct usage in the descriptor file referred from your AndroidManifest.xml file, report if there isn't an intent filter for the MediaBrowserService class, and identify certain voice actions issues.
  • Added new lint checks for insecure broadcast receivers, SSLCertificateSocketFactory and HostnameVerifier class uses, and File.setReadable() and File.setWritable() calls. It also detects invalid manifest resource lookups, especially for resources that vary by configuration.
  • Fixed a number of stability issues.

Android Studio v1.4.1 (October 2015)

Fixes and enhancements:

  • Fixed a Gradle model caching issue that could lead to excessive Gradle syncing when the IDE was restarted.
  • Fixed a native debugging deadlock issue.
  • Fixed an issue blocking users of the Subversion 1.9 version control system.
  • Fixed a Device Chooser dialog problem where after connecting a device that was unauthorized you could no longer select the emulator. Issue: 189658
  • Fixed incorrect translation error reporting for locales that have a region qualifier and a translation in the region (but not in the base locale). Issue: 188577
  • Fixed a deadlock issue in the Theme Editor related to its interaction with the Layout Editor. Issue: 188070
  • Fixed a Theme Editor reload and edit conflict causing attributes to not properly update. Issue: 187726
  • Improved Theme Editor performance.
  • Fixed an issue where the android:required attribute was ignored in the manifest. Issue: 187665

Android Studio v1.4.0 (September 2015)

Fixes and enhancements:

  • Added the Vector Asset Studio tool for importing vector graphics, such as material icons and SVG files. To use this tool, in the Android view of the Project window, right-click the res folder and select New > Vector Asset.
  • Added new Android Monitor functions, GPU and Network. To use these monitors, click Android Monitor at the bottom of the main window. The Android Device Monitor can't be running at the same time as Android Monitor.
  • Added an early preview of the new Theme Editor. To use this feature, select Tools > Android > Theme Editor.
  • Updated the Android templates for the Design Support Library. Templates now include support for the Material Design specification, as well as the appcompat Support Library for backwards compatibility.

Android Studio v1.3.2 (August 2015)

Fixes and enhancements:

  • Added support for Android 6.0 (API level 23), including new icons and AVD Manager support for creating devices with new screen densities.
  • Fixed an exception that was occurring during update checks. Issue: 183068
  • Fixed problem where unresolved view coordinates could cause the layout editor to crash. Issue: 178690
  • Fixed issue with invalid resource type warnings. Issue: 182433
  • Fixed lint check that was incorrectly flagging resources as private. Issue: 183120

Android Studio v1.3.1 (August 2015)

Fixes and enhancements:

  • Fixed support for creating an Android Wear Android Virtual Device (AVD) on Windows.
  • Updated the Project Wizard to use the entered project name.
  • Added support to allow the Android SDK to be stored in a read-only directory.
  • Updated Android plugin for Gradle version to 1.3.0.
  • Fixed issues with launching a debug session from the Android Debug Bridge (adb) Unix shell.
  • Fixed the Java package renaming message to show the correct package name.

Android Studio v1.3.0 (July 2015)

Fixes and enhancements:

  • Added options to enable developer services, such as AdMob and Analytics, in your app from within Android Studio.
  • Added additional annotations, such as @RequiresPermission, @CheckResults, and @MainThread.
  • Added the capability to generate Java heap dumps and analyze thread allocations from the Memory Monitor. You can also convert Android-specific HPROF binary format files to standard HPROF format from within Android Studio.
  • Integrated the SDK Manager into Android Studio to simplify package and tools access and provide update notifications.

    Note: The standalone SDK Manager is still available from the command line, but is recommended for use only with standalone SDK installations.

  • Added the finger command in the emulator console to simulate fingerprint authentication.
  • Added a <public> resource declaration to designate library resources as public and private resources.

    Note: Requires Android plugin for Gradle version 1.3 or higher.

  • Added data binding support to create declarative layouts that bind your application logic to layout elements.
  • Added support for a separate test APK module to build test APKs in Android Studio.
  • Updated the AVD Manager with HAXM optimizations and improved notifications.
  • Added 64-bit ARM and MIPS emulator support for QEMU 2.1.
  • Simplified the resolution of Lint warnings by adding quick fixes, such as the automatic generation of Parcelable implementation.
  • Added live template support for quick insertion of code snippets.

Android Studio v1.2.2 (June 2015)

Fixes and enhancements:

  • Fixed build issues that were blocking builds from completing.

Android Studio v1.2.1 (May 2015)

Fixes and enhancements:

  • Fixed minor performance and feature issues.

Android Studio v1.2.0 (April 2015)

Android Studio v1.1.0 (February 2015)

Various fixes and enhancements:

  • Added support for the Android Wear watch template.
  • Modified new project and module creation to include res/mipmap folders for density-specific launcher icons. These res/mipmap folders replace the res/drawable folders for launcher icons.
  • Updated launcher icons to have a Material Design look and added an xxxhdpi launcher icon.
  • Added and enhanced Lint checks for region and language combinations, launcher icons, resource names, and other common code problems.
  • Added support for Best Current Practice (BCP) language tag 47.

Android Studio v1.0.1 (December 2014)

Various fixes and enhancements:

  • Fixed AVD Manager and device.xml file lock issue.
  • Fixed the emulator log on Windows systems.
  • Fixed issue with creating AVDs with Android Studio and Android SDK installed on different drives on Windows systems.
  • Sets the default update channel for new downloads to Stable. If you installed the 1.0.0 version of Android Studio and would like stable, production-ready version updates, use File > Settings > Updates to change to the Stable update channel.

Android Studio v1.0 (December 2014)

Initial release of Android Studio.

Android Studio v0.8.14 (October 2014)

See tools.android.com for a full list of changes.

Android Studio v0.8.6 (August 2014)

See tools.android.com for a full list of changes.

Android Studio v0.8.0 (June 2014)

Added support for Android Wear projects.

See tools.android.com for a full list of changes.

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)

  • Merged in the latest IntelliJ codebase changes. Includes fixes for issues reported by Studio users such as tweaks to Linux font sizes and font rendering.
  • Android Gradle plug-in updated to 0.5.0.

    Caution: This new version is not backwards compatible. When opening a project that uses an older version of the plug-in, Studio will show an error stating Gradle <project_name> project refresh failed.

    The updated Gradle plug-in includes the following changes:

    • Fixed IDE model to contain the output file even if it's customized through the DSL. Also fixed the DSL to get/set the output file on the variant object so that it's not necessary to use variant.packageApplication or variant.zipAlign
    • Fixed dependency resolution so that we resolved the combination of (default config, build types, flavor(s)) together instead of separately.
    • Fixed dependency for tests of library project to properly include all the dependencies of the library itself.
    • Fixed case where two dependencies have the same leaf name.
    • Fixed issue where Proguard rules file cannot be applied on flavors.

    All Gradle plugin release notes are available are here: http://tools.android.com/tech-docs/new-build-system.

  • Gradle errors from aapt no longer point to merged output files in the build/ folder, they point back to the real source locations.
  • Parallel Builds. It's now possible to use Gradle's parallel builds. Please be aware that parallel builds are in "incubation" (see Gradle's documentation.) This feature is off by default. To enable it, go to Preferences > Compiler and check the box Compile independent modules in parallel.
  • Further work on the new resource repository used for layout rendering, resource folding in the editor, and more:
    • Basic support for .aar library dependencies (e.g. using a library without a local copy of the sources). Still not working for resource XML validation and navigation in source editors.
    • Cycle detection in resource references.
    • Quick Documentation (F1), which can show all translations of the string under the caret, will now also show all resource overlays from the various Gradle flavors and build types, as well as libraries. They are listed in reverse resource overlay order, with strikethrough on the versions of the string that are masked.
    • Fixes to handle updating the merged resources when the set of module dependencies change.
    • XML rendering fixes to properly handle character entity declarations and XML and unicode escapes.
  • Save screenshot support for the layout preview and layout editor windows.
  • Template bug fixes.
  • Lint bug fixes.
  • Various fixes for crash reports. Thank you, and keep filing crash reports!

Android Studio v0.1.x (May 2013)

  • Various bug fixes, including a fix for a common Windows installation issue.

 

Troubleshooting

If you encounter problems in Android Studio, check the Known Issues or Troubleshoot page.

This site uses cookies to store your preferences for site-specific language and display options. OK

You have successfully signed up for the latest Android developer news and tips.

You requested a page in , but your language preference for this site is .

Would you like to change your language preference and browse this site in ? If you want to change your language preference later, use the language menu at the bottom of each page.

This doc is hidden because your selected API level for the documentation is . You can change the documentation API level with the selector above the left navigation.

For more information about specifying the API level your app requires, read Supporting Different Platform Versions.

developer.android.com

Create an Android Library | Android Studio

  1. Create a library module
    1. Convert an app module to a library module
  2. Add your library as a dependency
  3. Publish non-default variants of your library
  4. Choose resources to make public
  5. Development considerations
  6. Anatomy of an AAR file

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. Unlike JAR files, AAR files can contain Android resources and a manifest file, which allows you to bundle in shared resources like layouts and drawables in addition to Java classes and methods.

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 module-level build.gradle file.
  2. Delete the line for the applicationId. Only an Android app module can define this.
  3. At the top of the file, you should see the following: apply plugin: 'com.android.application'

    Change it to the following:

    apply plugin: 'com.android.library'
  4. Save the file and click Tools > Android > 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.

When you want to build the AAR file, select the library module in the Project window and then click Build > Build 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 either of the following 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 (the library must be already built):
      1. Click File > New > New Module.
      2. Click Import .JAR/.AAR Package then click Next.
      3. Enter the location of the compiled AAR or JAR file then click Finish.
    • Import the library module to your project (the library source becomes part of 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 add 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 compile configuration adds the library named my-library-module as a build dependency for the entire app module. If you instead want the library only for a specific build variant, then instead of compile, use buildVariantNameCompile. For example, if you want to include the library only in your "pro" product flavor, it looks like this:

productFlavors { pro { ... } } dependencies { proCompile project(":my-library-module") }

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.

Publish non-default variants of your library

By default, the library module publishes and exposes only the "release" build variant to other Android projects and modules. That is, if an app module consumes the library as a dependency, Gradle targets only the "release" variant of the library even when it's building a debug version of the app. However, you can tell Gradle to target the "debug" build variant by adding the following to the library's build.gradle file:

android { ... // Sets the "debug" build variant as the default variant // of the library that Gradle should publish. defaultPublishConfig "debug" }

Now Gradle always publishes the "debug" variant of the library to other modules. However, if the library module uses product flavors, you must configure the defaultPublishConfig property and specify a build variant by its full configuration name (otherwise, Gradle doesn't publish your library because the traditional "release" and "debug" variants no longer exist). The following sample targets a build variant that combines the "demo" product flavor and "debug" build type:

android { ... defaultPublishConfig "demoDebug" }

Keep in mind, if you are building a release version of your app for publication, you need to change defaultPublishConfig to use a release variant of the library. Alternatively, you can tell Gradle to publish and expose all available variants of the library and configure each app variant to use only the one it needs. To tell Gradle to publish all variants of the library, include the following line in the library's build.gradle file:

android { ... // Tells Gradle to build all variants of the library. Note that this // may increase build times because Gradle must build multiple AARs, // instead of only one. publishNonDefault true }

Note: When publishing all variants of your library to Maven, the Maven publishing plugin publishes the default variant of the library with each additional variant as an additional artifact. Gradle differentiates each of those artifacts by setting its classifier to the variant name, such as "debug". However, this behavior is not fully supported by the Android plugin for Gradle, and you should either publish a single variant of the library to Maven, or set publishNonDefault to true only when publishing different variants of your library to local Android modules or projects.

Now you can configure the dependencies block in the app's build.gradle file to target any of the available variants of the library. The following code snippet in the app module's build.gradle file instructs Gradle to use the library's "demoDebug" variant when building the "demoDebug" version of the app and to use the library's "fullRelease" variant when building the "fullRelease" version of the app:

android {...} ... // Creates Gradle dependency configurations to use in the dependencies block. configurations { // Initializes placeholder configurations that the Android plugin can use when targeting // the corresponding variant of the app. demoDebugCompile {} fullReleaseCompile {} ... } dependencies { // If the library configures multiple build variants using product flavors, // you must target one of the library's variants using its full configuration name. demoDebugCompile project(path: ':my-library-module', configuration: 'demoDebug') fullReleaseCompile project(path: ':my-library-module', configuration: 'fullRelease') ... }

Choose resources to make public

All resources in a library default to public. To make all resources implicitly private, you must define at least one specific attribute as public. Resources include all files in your project’s res/ directory, such as images. To prevent users of your library from accessing resources intended only for internal use, you should use this automatic private designation mechanism by declaring one or more public resources. Alternately, you can make all resources private by adding an empty <public /> tag , which marks nothing as public, which makes everything else (all resources) private.

To declare a public resource, add a <public> declaration to your library’s public.xml file. If you haven’t added public resources before, you need to create the public.xml file in the res/values/ directory of your library.

The following example code creates two public string resources with the names mylib_app_name and mylib_public_string:

<resources> <public name="mylib_app_name" type="string"/> <public name="mylib_public_string" type="string"/> </resources>

You should make public any resources that you want to remain visible to developers using your library. For example, although most of the resources in the v7 appcompat library are private, attributes controlling the Toolbar widget are public to support material design.

Implicitly making attributes private not only prevents users of your library from experiencing code completion suggestions from internal library resources but also allows you to rename or remove private resources without breaking clients of your library. Private resources are filtered out of code completion and the theme editor, and Lint warns you when you try to reference a private resource.

When building a library, the Android Gradle plugin gets the public resource definitions and extracts them into the public.txt file, which is then packaged inside the AAR file.

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 the dependencies 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's build.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' } ... }

    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.

  • Testing a library module is the same as testing an app

    The main difference is that the library and its dependencies are automatically included as dependencies of the test APK. This means that the test APK includes not only its own code, but also the library's AAR and all its dependencies. Because there is no separate "app under test," the androidTest task installs (and uninstalls) only the test APK.

    When merging multiple manifest files, Gradle follows the default priority order and merges the library's manifest into the test APK's main manifest.

Anatomy of an AAR file

The file extension for an AAR file is .aar, and the Maven artifact type should be aar as well. The file itself is a zip file containing the following mandatory entries:

  • /AndroidManifest.xml
  • /classes.jar
  • /res/
  • /R.txt
  • /public.txt

Additionally, an AAR file may include one or more of the following optional entries:

  • /assets/
  • /libs/name.jar
  • /jni/abi_name/name.so (where abi_name is one of the Android supported ABIs)
  • /proguard.txt
  • /lint.jar

developer.android.com

Create a Project | Android Studio

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 or import an existing project.

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.

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. Use the following steps to create a new project.

Step 1: Start and configure the 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:

Import an existing project

To import an existing project into Android Studio, proceed as follows:

  1. Click File > New > Import Project.
  2. In the Select Eclipse or Gradle Project to Import window that appears, navigate to the root directory of the project you want to import.
  3. Click OK.

Android Studio then opens the project in a new IDE window.

If you are importing a project from version control, use the File > New > Project from Version Control menu. For more information about importing projects from version control, read IntelliJ’s VCS-Specific Procedures.

If you are importing an existing Eclipse ADT project into Android Studio, how you add the project depends on its structure. To read more about importing projects from Eclipse, see Migrate to Android Studio from Eclipse.

developer.android.com

Build and Run Your App

Android Studio sets up new projects to deploy to the Android Emulator or a connected device with just a few clicks. Once your app is installed, Instant Run allows you to push code changes without building a new APK.

To build and run your app, select Run > Run in the menu bar (or click Run in the toolbar). If it's the first time running the app, Android Studio asks you to select a deployment target as shown in figure 1. Select a device to install and run your app.

Figure 1. The Select Deployment Target dialog shows available devices

If the dialog says, "No USB devices or running emulators detected," then you need to set up and connect your device or launch an emulator by clicking a device listed under Available Virtual Devices. If there are no virtual devices listed, click Create New Virtual Device and follow the Virtual Device Configuration wizard (see Create and Manage Virtual Devices).

To display the Select Deployment Target dialog, either deselect Use same device for future launches or stop the app with Run > Stop app or Stop , and then start it again.

Note: You can also deploy your app in debug mode by clicking Debug . Running your app in debug mode allows you to set breakpoints in your code, examine variables and evaluate expressions at run time, and run debugging tools. To learn more, see Debug Your App.

Change the run/debug configuration

When you run your app for the first time, Android Studio uses a default run configuration. The run configuration specifies the module to run, package to deploy, activity to start, target device, emulator settings, logcat options, and more.

The default run/debug configuration launches the default project activity and uses the Select Deployment Target dialog for target device selection. If the default settings don't suit your project or module, you can customize the run/debug configuration, or even create a new one, at the project, default, and module levels. To edit a run/debug configuration, select Run > Edit Configurations. For more information, see Create and Edit Run/Debug Configurations.

Change the build variant

By default, Android Studio builds the debug version of your app, which is intended only for use during development, when you click Run.

To change the build variant Android Studio uses, select Build > Select Build Variant in the menu bar (or click Build Variants in the tool windows bar), and then select a build variant from the drop-down menu. By default, new projects are set up with two build variants: a debug and release variant. You need to build the release variant to prepare your app for public release.

To build other variations of your app, each with different features or device requirements, you can define additional build variants.

Build your project

The Run button compiles and installs the APK, but there are other options in the Build menu that you might want to use to compile parts or all of your project. Before you select any of the build options listed in table 1, you need to select the buid variant you want to build.

Table 1. Build options in the Build menu.

Menu Item Description
Make Module Compiles all source files in the selected module that have been modified since the last build, and all modules the selected module depends on recursively. The compilation includes dependent source files and any associated build tasks. You can select the module to build by selecting either the module name or one of its files in the Project window. This command does not generate an APK.
Make Project Makes all modules.
Clean Project Deletes all intermediate/cached build files.
Rebuild Project Runs Clean Project for the selected build variant and produces an APK.
Build APK(s)

Builds an APK of all the application modules in the current project for their selected variant. When the build completes, a confirmation notification appears, providing a link to the APK file and a link to open it in APK Analyzer.

If the build variant you've selected is a debug build type, then the APK is signed with a debug key and it's ready to install. If you've selected a release variant, then, by default, the APK is unsigned and you must manually sign the APK. However, you can instead configure the build process to automatically sign your APK.

All built APKs are saved in project-name/module-name/build/outputs/apk/.

Generate Signed APK Brings up a dialog with a wizard to set up a new signing configuration. For more information, see Sign an APK.

Note: The Run button builds an APK with testOnly="true", which means the APK can only be installed via adb (which Android Studio uses). If you want a debuggable APK that people can install without adb, select your debug variant and click Build > Build APK(s).

For details about the gradel steps taken for each command, open the Gradle Console. For more information about gradle and the build process, see Configure Your Build.

Monitor the build process

You can view details about the build process by clicking View > Tool Windows > Gradle Console (or by clicking Gradle Console in the tool window bar). The console displays each task that Gradle executes in order to build your app, as shown in figure 2.

Figure 2. The Gradle Console in Android Studio

If your build variants use product flavors, Gradle also invokes tasks to build those product flavors. To view the list of all available build tasks, click View > Tool Windows > Gradle (or click Gradle in the tool window bar).

If an error occurs during the build process, the Messages window appears to describe the issue. Gradle may recommend some command-line options to help you resolve the issue, such as --stacktrace or --debug. To use command-line options with your build process:

  1. Open the Settings or Preferences dialog:
    • On Windows or Linux, select File > Settings from the menu bar.
    • On Mac OSX, select Android Studio > Preferences from the menu bar.
  2. Navigate to Build, Execution, Deployment > Compiler.
  3. In the text field next to Command-line Options, enter your command-line options.
  4. Click OK to save and exit.

Gradle will apply these command-line options the next time you try building your app.

About Instant Run

In Android Studio 2.3 and higher, Instant Run significantly reduces the time it takes to update your app with code and resource changes. After deploying your app to a target device running Android 5.0 (API level 21) or higher, you can click Apply Changes to push certain code and resource changes to your running app without building a new APK—and, in some cases, without even restarting the current activity. The Run and Debug buttons are always available to you when you want to push your changes and force an app restart. However, you may find that using the Apply Changes button provides a faster workflow for most incremental changes to your app.

Tip: You can also press Control + F10 (or Control + Command + R on Mac) to apply changes with Instant Run.

The Apply Changes action is available only when you meet the following conditions:

  • Build your app using a debug build variant.
  • Use Android plugin for Gradle version 2.3.0 or higher.
  • Set minSdkVersion to 15 or higher in your app's module-level build.gradle file.
  • Deploy your app to a target device running Android 5.0 (API level 21) and higher.

For more information about enabling Instant Run, go to the section about configuring your project.

Instant Run pushes your changes by performing a hot swap, warm swap, or cold swap—the type of swap it performs depends on the type of change you made. When you click Apply Changes after making a code or resource change to your running app, Instant Run automatically determines the best way to push your change to the target device, as described in the following table.

Clicking Run (or Debug ) forces a cold swap and an app restart. If you make a change to the app manifest or a resource referenced by the manifest, Android Studio always pushes your changes with a full APK reinstall.

Code Change Apply Changes Behavior
  • Change implementation code of an existing method

Performs a hot swap: This is the fastest type of swap and makes changes visible much more quickly. Your application keeps running and a stub method with the new implementation is used the next time the method is called.

Hot swaps do not re-initialize objects in your running app. Before you see certain updates, you may need to either restart the current activity, by selecting Run > Restart Activity, or restart your app, by clicking Run (or Debug ). By default, Android Studio automatically restarts the current activity after performing a hot swap. If you do not want this behavior, you can disable automatic activity restarts.

  • Change or remove an existing resource
Performs a warm swap: This swap is still very fast, but Instant Run must restart the current activity when it pushes the changed resources to your app. Your app keeps running, but a small flicker may appear on the screen as the activity restarts—this is normal.
Structural code changes, such as:
  • Add, remove, or change:
    • an annotation
    • an instance field
    • a static field
    • a static method signature
    • an instance method signature
  • Change which parent class the current class inherits from
  • Change the list of implemented interfaces
  • Change a class's static initializer
  • Reorder layout elements that use dynamic resource IDs

Performs a cold swap: This swap is a bit slower because, although a new APK is not required, Instant Run must restart the whole app when it pushes structural code changes.

  • Change the app manifest
  • Change resources referenced by the app manifest
  • Change an Android system UI element, such as a widget or notification

When making changes to the app's manifest or resources referenced by the manifest, clicking Apply Changes redeploys a full build of your app with those changes. This is because certain information about the app, such as its name, app icon resources, and intent filters, are determined from the manifest when the APK is installed on the device.

If your build process automatically updates any part of the app manifest, such as automatically iterating versionCode or versionName, you will not be able to benefit from the full performance of Instant Run. When using Instant Run, you should disable automatic updates to any part in the app manifest in your debug build variants.

When updating an Android system UI element, such as a widget or notification, you need to click Run (or Debug ).

Note: If you need to restart your app after a crash, do not launch it from your target device. Restarting your app from your target device does not apply any of your code changes since the last cold swap or incremental build. To launch your app with all your recent changes, click Run (or Debug ) from Android Studio.

Disable automatic activity restart

When performing a hot swap, your app keeps running but Android Studio automatically restarts the current activity. To disable this default setting:

  1. Open the Settings or Preferences dialog:
    • On Windows or Linux, select File > Settings from the menu bar.
    • On Mac OSX, select Android Studio > Preferences from the menu bar.
  2. Navigate to Build, Execution, Deployment > Instant Run.
  3. Uncheck the box next to Restart activity on code changes.

If automatic activity restart is disabled, you can manually restart the current activity from the menu bar by selecting Run > Restart Activity.

Configure your project for Instant Run

Android Studio enables Instant Run by default for projects built using Android plugin for Gradle 2.3.0 and higher.

To update an existing project with the latest version of the plugin:

  1. Open the Settings or Preferences dialog.
  2. Navigate to Build, Execution, Deployment > Instant Run and click Update Project, as shown in figure 3.

    If the option to update the project does not appear, it’s already up-to-date with the latest Android plugin for Gradle. But make sure the box next to Enable Instant Run is checked.

    Figure 3. Updating the Android plugin for Gradle for an existing project

To start using Instant Run, you also need to change the build variant to a debug version of your app and deploy it to a target device running Android 5.0 (API level 21) or higher. To learn about more techniques that speed up your build, read Optimize Your Build Speed

Exclude your project from Windows Defender

On Windows systems, Windows Defender may cause slowdowns while using Instant Run. If you are using Windows Defender, you should exclude your Android Studio project folder from Windows Defender malware scans.

Improve build times when using Crashlytics

If your version of the Fabric Gradle plugin is lower than 1.21.6, Crashlytics may cause slower build times. To improve build performance while developing your app, you can either update the plugin to the latest version or disable Crashlytics for your debug build variant.

Limitations of Instant Run

Instant Run is designed to speed up the build and deploy process in most situations. However, there are some aspects to using Instant Run that might affect its behavior and compatibility with your app. If you experience any other issues while using Instant Run, please enable extra logging and report a bug.

Apps don't launch on some physical devices

Some device manufacturers block apps from automatically launching after being installed on the device. When deploying your app to a physical device using Android Studio 2.3, this restriction breaks the intended behavior of Instant Run and causes the following error output: Error: Not found; no service started. To fix this issue, update Android Studio to 2.3.1 or higher.

Debug mode always uses cold swaps

On Android Studio 2.3, if you deploy your app by clicking Debug , pushing subsequent code changes by clicking Apply Changes always results in a cold swap. To learn more, go to issue #234401.

Deploying to multiple devices

Instant Run uses different techniques to perform hot, warm, and cold swaps that are specific to the API level of the target device. For this reason, while deploying an app to multiple devices at once, Android Studio temporarily turns off Instant Run.

Multidexing your app

If minSdkVersion is set to 21 or higher, Instant Run automatically configures your app for multidex. Because Instant Run only works with the debug version of your app, you may need to configure your app for multidex when deploying your release build variant.

Running instrumented tests and performance profilers

Instrumented tests load both the debug APK and a test APK into the same process on a test device, allowing control methods to override the normal lifecycle of the app and perform tests. While running or debugging instrumented tests, Android Studio does not inject the additional methods required for Instant Run and turns the feature off.

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 overriding methods with a hot swap. This performance impact could interfere with information provided by performance profiling tools. Additionally, the stub methods generated with each hot swap can complicate stack traces.

Using third-party plugins

Android Studio temporarily disables the Java Code Coverage Library (JaCoCo) and ProGuard while using Instant Run. Because Instant Run only works with debug builds, this does not affect your release build.

Certain third-party plugins that perform bytecode enhancement may cause issues with how Instant Run instruments your app. If you experience these issues, but want to continue using Instant Run, you should disable those plugins for your debug build variant. You can also help improve compatibility with third-party plugins by filing a bug.

Pushing changes to multi-process apps

Instant Run only instruments your app's main process in order to perform hot swaps and warm swaps. When pushing code changes to other app processes, such as changes to a method implementation or an existing resource, Instant Run performs a cold swap.

Launching your app in a Work profile

If you run your app with Instant Run and open your app using a Work profile (or other secondary profile), your app will crash because the instrumented DEX files used by Instant Run are accessible only from the primary profile's user space.

If you want to continue using Instant Run, just avoid opening your app with the Work profile and be sure your run configuration does not use the --user user_id flag.

If you need to use your app with the Work profile, we recommend you create a new run configuration that includes the --user user_id flag, specifying the Work profile user ID. You can find the user ID by executing adb shell pm list users from command line. When you use the --user flag, Android Studio disables Instant Run for only that deployment; Instant Run will work again when you switch to a configuration without the --user flag.

Disable Instant Run

To disable Instant Run:

  1. Open the Settings or Preferences dialog.
  2. Navigate to Build, Execution, Deployment > Instant Run.
  3. Uncheck the box next to Enable Instant Run.

developer.android.com

Known Issues - Android Studio Project Site

If you're currently using Android Studio 2.0 Beta, you cannot create AVDs with the N Preview system images, so you currently need to use the Android Studio 2.1 preview to create AVDs until a fix is applied to the 2.0 channel.

Tools and libraries that require the app’s class files not compatible with Jack

Various tools that read .class files (such as JaCoCo, Mockito, and some lint checks) are currently not compatible with the Jack compiler.

Gradle build unable to clean output folders when project is on NTFS on Linux

Due to the file locking behavior of NTFS, on Windows the IDE will automatically copy the classes jars to another location before indexing, so that subsequent Gradle builds can clean and make changes to the build/ tree. This behavior is not automatically enabled when using NTFS on Linux or OS X, as reported in issue 202297, but can be manually specified in idea.properties:#--------------------------------------------------------------------- # IDEA can copy library .jar files to prevent their locking. # By default this behavior is enabled on Windows and disabled on other platforms. # Uncomment this property to override. #--------------------------------------------------------------------- idea.jars.nocopy=false

Mac OS X Performance

The OpenJDK 1.8.0_76 bundled with Studio 2.2 has a few problems on Mac. Using an external 4K monitor with a scaled resolution can adversely impact rendering performance as discussed in issue 203412 and in IDEA-144261, up to the point the IDE becomes unresponsive. Additionally, as reported in issue 223749 and in IDEA-158500, scrolling is very sensitive on OS X 10.12 (Sierra).

Gradle Sync Failed: Broken Pipe

The issue is that the Gradle daemon is trying to use IPv4 instead of IPv6.

Workaround 1: On Linux, put the following in your ~/.profile or ~/.bash_profile: export _JAVA_OPTIONS="-Djava.net.preferIPv6Addresses=true"

Workaround 2: in Android Studio's vmoptions file, change the line -Djava.net.preferIPv6Addresses=true to -Djava.net.preferIPv6Addresses=true  More details: Networking IPv6 User Guide

"peer not authenticated" errors from Gradle sync or SDK Manager

The root cause is a missing certificate in $JAVA_HOME/jre/lib/certificates/cacerts.

  • If you're behind a proxy, try to connect directly. If the direct connection works, then in order to connect via the proxy you may need to use keytool to add the proxy server's certificate to the cacerts file.
  • Re-install a supported, unmodified JDK. There's a known issue affecting Ubuntu users which results in an empty /etc/ssl/certs/java/cacerts, and the workaround is:

$ sudo /var/lib/dpkg/info/ca-certificates-java.postinst configure

Spurious Render Exception

The specific render error message is:

The following classes could not be found:

- android.support.v7.internal.app.WindowDecorActionBar

Despite the error message, the layout preview is correct and the message can be safely ignored. The issue has already been fixed in 2.0 preview. See bug 192102 for more details.

Can't Render Layouts in Android Studio 1.2

The specific render error message is:

The following classes could not be instantiated:

- android.support.v7.internal.widget.ActionBarOverlayLayout

This is bug 170841 which will be fixed in version 1.2.3 of the Android Gradle plugin.

Workaround 1: First manually build the project, then manually sync the project (using the Sync with Gradle files in the toolbar, or from the Tools > Android menu), then finally press Refresh in the toolbar above the layout editor.

Workaround 2: Switch the Android Gradle plugin from 1.2.x to 1.1.3 for now. When 1.2.3 is released you can switch back to the 1.2.x versions.

Workaround 3: Try updating to Android Studio 1.3 Canary. Please report back on the issue tracker whether it worked for you or not.

Frozen Keyboard Input: "iBus" Problems on Linux

"Update & Restart" Doesn't Restart

In Android Studio 1.2 Preview 1 & 2, selecting "Update & Restart" to update from one version to the next, does not actually restart. Just manually exit the IDE, and start it again. Once you do that, the patch will be installed and the IDE updated.

Can't Run SDK Manager (Broken find_java.bat)

There was a bug in the find_java.bat command that shipped with SDK Tools 24.0.0. This was fixed in version 24.0.1, but unfortunately, that command is used on some systems to launch the SDK Manager itself.

If you are unable to launch the SDK Manager to update, you can download find_java.zip from this page, and unzip it into the root of your Android SDK installation; it will replace the files tools\lib\find_java.bat, tools\lib\find_java32.exe and tools\lib\find_java64.exe with the versions from 24.0.1.

(If you are using Android Studio 1.0.1, the IDE will prompt you to update to tools 24.0.1 which it will do inside the IDE, so that update should work without needing to call find_java; similarly, if you are using ADT, you should be able to open the SDK Manager from within the IDE, which should work without find_java).

 Gradle DSL method not found: 'runProguard()'

If you are updating from Android Studio 0.8.x to Android Studio 1.0.0-RC, you'll need to update your Gradle plugin version from 0.13.x to 1.0.0-rc4. There were a couple of last minute API changes; for example, change "runProguard" to "minifyEnabled", etc. See the release notes under http://tools.android.com/tech-docs/new-build-system for more details on the changes if you run into build/Gradle sync issues.

Other Difficulties Loading Older Gradle Projects

"minSdkVersion 19  cannot be smaller than version L"

If your build fails with an error message like this:

:app:processDebugManifest app/src/main/AndroidManifest.xml:0:0 Error:

uses-sdk:minSdkVersion 19 cannot be smaller than version L declared in library app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/21.0.0-rc1/AndroidManifest.xml

Suggestion: use tools:overrideLibrary="android.support.v7.appcompat" to force usage

you are using an obsolete version of the Android support libraries. Open up the SDK manager and update to the latest (non-preview) versions.

"Android SDK folder inside the application folder"

When updating to version 0.8.13 or newer, the patch installation may detect the Android SDK folder inside your application folder. If this occurs, you must move your sdk folder outside of the application folder for the update to take place. Once Android Studio is updated, on its first run it will ask you for the location of the sdk. Projects that were referencing the old sdk location will be automatically updated once opened in Android Studio. We do not recommend moving the sdk directory back into Android Studio as this would interfere with the application signature, particularly on MacOS, and would prevent future updates to do verifications and avoid corrupted installations. More information in issue 78129.

To move the SDK folder in Windows or Linux, simply go to Android Studio's folder and drag the "sdk" folder to another location, such us your user directory or alongside Android Studio's folder. On MacOS go with Finder to the application folder called "Android Studio.app", right click on it and select "Show Package Contents". When its contents are shown you can now drag the "sdk" folder to its new location.

JUnit tests missing resources in classpath when run from Studio

Issue: If you have specific resource folders in your Java modules, then those resources won't be found when running tests from the IDE. Running tests using Gradle from the command line will work. Executing the gradle check task from the IDE will also work. See Issue 64887 for more details.

This issue happens because as of IntelliJ 13, you can only have a single folder as the classpath. IntelliJ's builder copies all resources into that build folder. But Gradle doesn't copy over the resources.

You can use any of the following workarounds until then:

 - Run the gradle check task from the IDE rather than running a unit test

 - Or update your build script to manually copy resources into the build folder. See comment #13.

Running JUnit tests compiles the code twice

When creating a new project, the template JUnit configuration may be created with two "Before launch" steps: Make and Gradle-aware Make. This is then propagated to all created JUnit run configurations. To fix the issue, go to Run -> Edit Configurations and change the default JUnit configuration to only include the Gradle-aware Make step. To fix this for all future projects, close the current project (File -> Close Project) to get to the welcome screen, select Configure -> Project Defaults -> Run Configurations and make the same change.

Some test run configurations don't work

Not all run configurations that are available when right-clicking a test method are valid. Specifically:

  • Gradle run configurations (ones with Gradle logo as the icon) don't work.
  • JUnit run configurations (icon without a green android) don't apply to instrumentation tests, which can't be run on the local JVM.

Additional problem is that Android Studio remembers the run configuration created in a given context (e.g. right-clicking a given class/method) and will not offer to run a different one in the future. To fix this, go to Run > Edit Configurations and remove the incorrectly created configurations.

Linux and the Awesome WM

In Android Studio 0.8.3+:

Studio 0.8.3 does not work properly on Linux with the "Awesome WM" window manager version 3.4. It's supposed to work with 3.5.

Ubuntu and JAyatana

JAyatana allows Java Swing applications to integrate with the global menu in Ubuntu's Unity graphical shell. We have reports of Studio running into a NullPointerException under Unity: java.lang.NullPointerException at com.jarego.jayatana.swing.SwingGlobalMenu.getSwingGlobalMenuWindowController(SwingGlobalMenu.java:204) at com.jarego.jayatana.swing.SwingGlobalMenu.installLockParentGlobalMenu(SwingGlobalMenu.java:160) at ...
  • unset the JAVA_TOOL_OPTIONS environment variable when running Studio;
  • uninstall JAyatana. 

Can't Update to Latest Version

On Windows, files that are in use by a process cannot be deleted. 

When you attempt to use the builtin update mechanism in the IDE, it sometimes refuses to install the update, usually providing an error message like "Can't delete C:\some\path\file".

To work around this, open the task manager and attempt to kill processes that may be using the file, such as any gradle daemons.

Google Play Services 5.0.77

If your builds suddenly stop working with this error message:

  Error: Failed to find: com.google.android.gms:play-services:5.0.77

this is caused by the play services artifact being removed from the local Google Maven repository because it contained some critical bugs. It was been replaced by version 5.0.89 instead. (More information)

Google Play Services "5.2.8"

A new version of the Google Play Services library was released recently: 5.2.08. If you are using an older version of the library, Android Studio will automatically offer to upgrade it to the new version. However, due to a bug, it drops the leading zero in "08", which means it replaces the dependency with "5.2.8" instead of "5.2.08" which does not work. To fix this, edit the dependency to read "5.2.08" instead of "5.2.8". (More information).

tools.android.com


Смотрите также