Старые выпуски

Ниже приведены примечания к выпуску Android Studio 3.6 и более ранних версий, а также плагина Android Gradle 3.6.0 и более ранних версий.

Старые версии Android Studio

3.6 (февраль 2020 г.)

Android Studio 3.6 — это основной выпуск, включающий множество новых функций и улучшений.

Мы также хотели бы поблагодарить всех участников нашего сообщества , которые помогли с этим выпуском.

3.6.3 (апрель 2020 г.)

Это незначительное обновление включает в себя различные исправления ошибок. Чтобы просмотреть список заметных исправлений ошибок, прочитайте соответствующую публикацию в блоге Release Updates .

3.6.2 (март 2020 г.)

Это незначительное обновление включает в себя различные исправления ошибок. Чтобы просмотреть список заметных исправлений ошибок, прочитайте соответствующую публикацию в блоге Release Updates .

3.6.1 (февраль 2020 г.)

Это незначительное обновление включает в себя различные исправления ошибок. Чтобы просмотреть список заметных исправлений ошибок, прочитайте соответствующую публикацию в блоге Release Updates .

Инструменты проектирования

Эта версия Android Studio включает обновления нескольких инструментов дизайна, включая редактор макетов и диспетчер ресурсов.

Разделение просмотра и масштабирование редакторов дизайна

В разделенном представлении одновременно отображаются как дизайн, так и текст.

В этот выпуск включены следующие обновления редакторов визуального дизайна:

  • Редакторы дизайна, такие как редактор макетов и редактор навигации, теперь предоставляют разделенное представление, которое позволяет одновременно видеть представления «Дизайн» и «Код» вашего пользовательского интерфейса. В правом верхнем углу окна редактора теперь есть три кнопки. иконки просмотра для переключения между вариантами просмотра:

    • Чтобы включить разделенное представление, щелкните значок «Разделить» значок разделенного просмотра .
    • Чтобы включить представление источника XML, щелкните значок «Источник» значок просмотра исходного кода .
    • Чтобы включить представление «Дизайн», щелкните значок «Дизайн» . Значок просмотра дизайна .
  • Элементы управления масштабированием и панорамированием в редакторах дизайна переместились на плавающую панель в правом нижнем углу окна редактора.

Дополнительные сведения см. в разделе Создание пользовательского интерфейса с помощью редактора макетов .

Вкладка «Ресурс палитры цветов»

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

Палитра цветов с заполненными значениями цвета

Менеджер ресурсов

Менеджер ресурсов содержит следующие обновления:

  • Менеджер ресурсов теперь поддерживает большинство типов ресурсов.
  • При поиске ресурса Менеджер ресурсов теперь отображает результаты из всех модулей проекта. Раньше поиск возвращал результаты только из выбранного модуля.
  • Кнопка фильтра позволяет просматривать ресурсы из локально зависимых модулей, внешних библиотек и платформы Android. Вы также можете использовать фильтр для отображения атрибутов темы.
  • Теперь вы можете переименовывать ресурсы во время процесса импорта, щелкнув текстовое поле над ресурсом.

Дополнительные сведения см. в разделе Управление ресурсами пользовательского интерфейса вашего приложения с помощью Resource Manager .

Обновления плагина Android Gradle

Последняя версия плагина Android Gradle включает множество обновлений, включая оптимизацию скорости сборки, поддержку плагина публикации Maven и поддержку привязки представления. Чтобы узнать больше, прочтите полные примечания к выпуску .

Посмотреть привязку

Привязка представления позволяет упростить написание кода, взаимодействующего с представлениями, путем создания класса привязки для каждого файла макета XML. Эти классы содержат прямые ссылки на все представления, имеющие идентификатор в соответствующем макете.

Поскольку оно заменяет findViewById() , привязка представления исключает риск возникновения исключений нулевого указателя в результате недопустимого идентификатора представления.

Чтобы включить привязку представления, вам необходимо использовать плагин Android Gradle 3.6.0 или выше и включить следующее в файл build.gradle каждого модуля:

классный

  android {
      buildFeatures.viewBinding = true
  }
  

Котлин

  android {
      buildFeatures.viewBinding = true
  }
  

Применить изменения

Теперь вы можете добавить класс, а затем развернуть это изменение кода в работающем приложении, нажав кнопку «Применить изменения кода» или «Применить изменения и перезапустить действие» .

Чтобы узнать больше о разнице между этими двумя действиями, см. Применить изменения .

Опция меню «Рефакторинг» для включения поддержки Instant Apps

Теперь вы можете мгновенно включить базовый модуль в любое время после создания проекта приложения следующим образом:

  1. Откройте панель «Проект» , выбрав «Просмотр» > «Окна инструментов» > «Проект» в строке меню.
  2. Щелкните правой кнопкой мыши базовый модуль, обычно называемый «приложением», и выберите «Рефакторинг» > «Включить поддержку мгновенных приложений» .
  3. В появившемся диалоговом окне выберите базовый модуль из раскрывающегося меню.
  4. Нажмите ОК .

Примечание. Возможность мгновенного включения модуля базового приложения из мастера создания нового проекта была удалена.

Чтобы узнать больше, прочитайте Обзор Google Play Instant .

Деобфусцировать байт-код класса и метода в анализаторе APK

При использовании анализатора APK для проверки файлов DEX вы можете деобфусцировать байт-код класса и метода следующим образом:

  1. Выберите «Сборка» > «Анализ APK» в строке меню.
  2. В появившемся диалоговом окне перейдите к APK, который вы хотите проверить, и выберите его.
  3. Нажмите Открыть .
  4. В анализаторе APK выберите файл DEX, который вы хотите проверить.
  5. В средстве просмотра файлов DEX загрузите файл сопоставлений ProGuard для анализируемого APK.
  6. Щелкните правой кнопкой мыши класс или метод, который вы хотите проверить, и выберите «Показать байт-код» .

Собственный инструментарий

Следующие обновления поддерживают собственную разработку (C/C++) в Android Studio.

Поддержка Котлина

Следующие функции NDK в Android Studio, ранее поддерживаемые в Java, теперь также поддерживаются в Kotlin:

  • Перейдите от объявления JNI к соответствующей функции реализации на C/C++. Просмотрите это сопоставление, наведя указатель мыши на маркер элемента C или C++ рядом с номером строки в файле управляемого исходного кода.

  • Автоматически создавать функцию реализации-заглушки для объявления JNI. Сначала определите объявление JNI, а затем введите «jni» или имя метода в файле C/C++ для активации.

  • Неиспользуемые встроенные функции реализации выделяются в исходном коде как предупреждение. Объявления JNI с отсутствующей реализацией также выделяются как ошибка.

  • Когда вы переименовываете (рефакторите) встроенную функцию реализации, все соответствующие объявления JNI обновляются. Переименуйте объявление JNI, чтобы обновить встроенную функцию реализации.

  • Проверка подписи для неявно связанных реализаций JNI.

Другие улучшения JNI

Редактор кода в Android Studio теперь поддерживает более удобный рабочий процесс разработки JNI, включая улучшенные подсказки типов, автозаполнение, проверки и рефакторинг кода.

Перезагрузка APK для нативных библиотек {:#3.6-reload-apk}

Вам больше не нужно создавать новый проект, если APK в вашем проекте обновляется вне IDE. Android Studio обнаруживает изменения в APK и дает вам возможность повторно импортировать его.

Прикрепите источники APK только для Kotlin

Теперь можно прикреплять внешние источники APK только для Kotlin при профилировании и отладке готовых APK. Дополнительные сведения см. в разделе Прикрепление исходных кодов Kotlin/Java .

Обнаружение утечек в Memory Profiler

При анализе дампа кучи в профилировщике памяти теперь вы можете фильтровать данные профилирования, которые, по мнению Android Studio, могут указывать на утечки памяти для экземпляров Activity и Fragment в вашем приложении.

Типы данных, отображаемые фильтром, включают следующее:

  • Экземпляры Activity , которые были уничтожены, но на которые все еще ссылаются.
  • Экземпляры Fragment , у которых нет допустимого FragmentManager , но на которые все еще ссылаются.

Прикрепите источники APK только для Kotlin

Теперь можно прикреплять внешние источники APK только для Kotlin при профилировании и отладке готовых APK. Дополнительные сведения см. в разделе Прикрепление исходных кодов Kotlin/Java .

Обнаружение утечек в Memory Profiler

При анализе дампа кучи в профилировщике памяти теперь вы можете фильтровать данные профилирования, которые, по мнению Android Studio, могут указывать на утечки памяти для экземпляров Activity и Fragment в вашем приложении.

Типы данных, отображаемые фильтром, включают следующее:

  • Экземпляры Activity , которые были уничтожены, но на которые все еще ссылаются.
  • Экземпляры Fragment , у которых нет допустимого FragmentManager , но на которые все еще ссылаются.

В определенных ситуациях, например в следующих, фильтр может давать ложные срабатывания:

  • Fragment создан, но еще не использован.
  • Fragment кэшируется, но не как часть FragmentTransaction .

Чтобы использовать эту функцию, сначала сохраните дамп кучи или импортируйте файл дампа кучи в Android Studio. Чтобы отобразить фрагменты и действия, которые могут вызывать утечку памяти, установите флажок «Утечки действий/фрагментов» на панели дампа кучи профилировщика памяти.

Профилировщик: обнаружение утечек памяти

Фильтрация дампа кучи на наличие утечек памяти.

Эмуляторы

Android Studio 3.6 помогает вам воспользоваться преимуществами нескольких обновлений, включенных в эмулятор Android 29.2.7 и более поздних версий, как описано ниже.

Улучшенная поддержка местоположения

Android Emulator 29.2.7 и более поздних версий обеспечивает дополнительную поддержку эмуляции GPS-координат и информации о маршруте. При открытии расширенных элементов управления эмуляторов параметры на вкладке «Местоположение» теперь организованы на двух вкладках: «Отдельные точки» и «Маршруты» .

Отдельные точки

На вкладке «Отдельные точки» вы можете использовать веб-просмотр «Карты Google» для поиска достопримечательностей так же, как при использовании «Карт Google» на телефоне или в браузере. Когда вы ищете или щелкаете местоположение на карте, вы можете сохранить его, выбрав «Точка сохранения» в нижней части карты. Все сохраненные вами местоположения перечислены в правой части окна расширенных элементов управления .

Чтобы установить местоположение эмуляторов в выбранном вами месте на карте, нажмите кнопку «Установить местоположение» в правом нижнем углу окна «Расширенные элементы управления» .

Вкладка «Отдельные точки» в расширенных элементах управления эмулятора. .

Маршруты

Подобно вкладке «Отдельные точки» , вкладка «Маршруты» предоставляет веб-просмотр Google Maps, который можно использовать для создания маршрута между двумя или более местоположениями. Чтобы создать и сохранить маршрут, выполните следующие действия:

  1. В представлении карты используйте текстовое поле для поиска первого пункта назначения на вашем маршруте.
  2. Выберите местоположение из результатов поиска.
  3. Нажмите кнопку «Навигация» .
  4. Выберите начальную точку вашего маршрута на карте.
  5. (Необязательно) Нажмите «Добавить пункт назначения» , чтобы добавить к маршруту дополнительные остановки.
  6. Сохраните свой маршрут, нажав «Сохранить маршрут» в представлении карты.
  7. Укажите имя маршрута и нажмите «Сохранить» .

Чтобы смоделировать движение эмулятора по сохраненному вами маршруту, выберите маршрут из списка сохраненных маршрутов и нажмите «Воспроизвести маршрут» в правом нижнем углу окна «Расширенные элементы управления» . Чтобы остановить симуляцию, нажмите « Остановить маршрут» .

Вкладка «Маршруты» в расширенных элементах управления эмулятора. .

Чтобы непрерывно моделировать движение эмулятора по указанному маршруту, включите переключатель рядом с пунктом «Повторное воспроизведение» . Чтобы изменить скорость следования эмулятора по указанному маршруту, выберите вариант в раскрывающемся списке «Скорость воспроизведения» .

Поддержка нескольких дисплеев

Эмулятор Android теперь позволяет развертывать ваше приложение на нескольких дисплеях, которые поддерживают настраиваемые размеры, и может помочь вам тестировать приложения, поддерживающие многооконный и многоэкранный режим . Пока виртуальное устройство работает, вы можете добавить до двух дополнительных дисплеев следующим образом:

  1. Откройте расширенные элементы управления и перейдите на вкладку «Дисплеи» .

  2. Добавьте еще один дисплей, нажав «Добавить дополнительный дисплей» .

  3. В раскрывающемся меню «Вторичные дисплеи» выполните одно из следующих действий:

  4. Выберите одно из предустановленных соотношений сторон

  5. Выберите «Пользовательский» и установите высоту , ширину и количество точек на дюйм для своего пользовательского дисплея.

  6. (Необязательно) Нажмите «Добавить дополнительный дисплей» , чтобы добавить третий дисплей.

  7. Нажмите «Применить изменения» , чтобы добавить указанные дисплеи к работающему виртуальному устройству.

Добавление нескольких дисплеев. Вкладка «Расширенные элементы управления эмулятора».

Новые виртуальные устройства и шаблоны проектов для Android Automotive OS

При создании нового проекта с помощью Android Studio теперь вы можете выбрать один из трех шаблонов на вкладке «Автомобили» в мастере создания нового проекта : «Нет активности» , «Мультимедийная служба » и «Служба обмена сообщениями» . Для существующих проектов вы можете добавить поддержку устройств Android Automotive, выбрав «Файл» > «Создать» > «Новый модуль» в строке меню и выбрав «Автомобильный модуль» . Затем мастер создания нового модуля поможет вам создать новый модуль с использованием одного из шаблонов проектов Android Automotive.

Выбор шаблона проекта Android Automotive. .

Кроме того, теперь вы можете создать виртуальное устройство Android (AVD) для устройств Android Automotive OS, выбрав один из следующих параметров на вкладке «Автомобили» в мастере настройки виртуального устройства .

  1. Polestar 2 : создайте AVD, который имитирует головное устройство Polestar 2.
  2. Автомобильная промышленность (альбомная ориентация 1024p) : создайте AVD для стандартных автомобильных головных устройств Android размером 1024 x 768 пикселей.

Выбор виртуального устройства Android Automotive. .

Возобновляемые загрузки SDK

При загрузке компонентов и инструментов SDK с помощью SDK Manager Android Studio теперь позволяет возобновить загрузку, которая была прервана (например, из-за проблемы с сетью), вместо того, чтобы перезапускать загрузку с самого начала. Это улучшение особенно полезно для больших загрузок, таких как эмулятор Android или образы системы, когда подключение к Интернету ненадежно.

Кроме того, если у вас в фоновом режиме выполняется задача загрузки SDK, вы теперь можете приостановить или возобновить загрузку с помощью элементов управления в строке состояния.

Задача фоновой загрузки в строке состояния с новыми элементами управления, позволяющими приостанавливать или возобновлять загрузку.

Задача фоновой загрузки в строке состояния с новыми элементами управления, позволяющими приостанавливать или возобновлять загрузку.

Win32 устарел

32-разрядная версия Android Studio для Windows больше не будет получать обновления после декабря 2019 года и не будет получать поддержку после декабря 2020 года. Вы можете продолжать использовать Android Studio. Однако для получения дополнительных обновлений обновите свою рабочую станцию ​​до 64-разрядной версии Windows.

Чтобы узнать больше, прочитайте блог об амортизации 32-разрядной версии Windows.

Новая опция для оптимизации времени синхронизации Gradle.

В предыдущих выпусках Android Studio получала список всех задач Gradle во время синхронизации Gradle. В больших проектах получение списка задач может привести к замедлению синхронизации.

Чтобы улучшить производительность синхронизации Gradle, выберите «Файл» > «Настройки» > «Экспериментальный» и выберите «Не создавать список задач Gradle во время синхронизации Gradle».

Если вы включите эту опцию, Android Studio пропускает построение списка задач во время синхронизации, что позволяет Gradle Sync выполняться быстрее и повышает скорость реагирования пользовательского интерфейса. Имейте в виду, что когда IDE пропускает построение списка задач, списки задач на панели Gradle пусты, а автодополнение имени задачи в файлах сборки не работает.

Новое место для переключения автономного режима Gradle

Чтобы включить или отключить автономный режим Gradle, сначала выберите «Вид» > «Окна инструментов» > Gradle в строке меню. Затем в верхней части окна Gradle нажмите «Переключить автономный режим». Кнопка Gradle в автономном режиме на панели Gradle. .

IntelliJ ИДЕЯ 2019.2

Базовая среда разработки Android Studio была обновлена ​​за счет улучшений от IntelliJ IDEA до версии 2019.2 .

Чтобы узнать больше об улучшениях других версий IntelliJ, включенных в совокупную версию 2019.2, посетите следующие страницы:

Участники сообщества

Благодарим всех участников нашего сообщества, которые помогли нам обнаружить ошибки и найти другие способы улучшения Android Studio 3.6. В частности, мы хотели бы поблагодарить следующих людей, сообщивших об ошибках:

  • Альберт Ло
  • Алексей Ротт
  • Андреа Леганса
  • Бенедикт Кольб
  • Сезар Пуэрта
  • Кертис Кроетч
  • Дамиан Вечорек
  • Дэн Лью
  • Дэвид Бурстрем
  • Дипаншу
  • Егор Андреевич
  • Эли Грабер
  • Эмин Кокалари
  • Эван Татарка
  • Франтишек Надь
  • Грег Моэнс
  • Ханнес Ахляйтнер
  • Ганс Петтер Эйде
  • Хеннинг Банк
  • Хьюго Виссер
  • Игорь Эскодро
  • Иньяки Вильяр
  • Хавентира Лиената
  • Джо Роджерс
  • Кристоффер Дэниэлссон
  • Лиран Барсиса
  • Луис, Канада
  • Лорант Пинтер
  • Лукаш Васильковски
  • Люк Филке
  • Мальвин Сутанто
  • Масатоши Кубоде
  • Мэтью Уинтерс
  • Майкл Бэйли
  • Михал Горный
  • Михай Неашу
  • Майк Скамелл
  • Монте-Кризор
  • Нельсон Осаки
  • Нельсон Осаки
  • Ник Фирмани
  • Никлас Ансман Гирц
  • Никлас Крон
  • Николас Лихтмайер
  • Ник Хаарман
  • Нильс ван Хов
  • Никлас Бауди
  • Ренато Гонсалвес
  • Рев Грёнмо
  • Руслан Баратов
  • Синан Козак
  • Славомир Червинский
  • Стефан Вольф
  • Стивен Д'Амико
  • Тао Ван
  • Томас Хладек
  • Томаш Прохазка
  • Тони Робалик
  • Торбьёрн Сёрли
  • Уоррен Хе
  • Йенчи Лин
  • Зак Свирс
  • 3,5 (август 2019 г.)

    Android Studio 3.5 — это основной выпуск, созданный в рамках Project Marble. Начиная с выпуска Android Studio 3.3 , инициатива Project Marble охватывала несколько выпусков, направленных на улучшение трех основных областей IDE: работоспособность системы , совершенствование функций и исправление ошибок.

    Информацию об этих и других обновлениях Project Marble можно найти в блоге разработчиков Android или в разделах ниже.

    Мы также хотим поблагодарить всех участников нашего сообщества , которые помогли с этим выпуском.

    3.5.3 (декабрь 2019 г.)

    Это незначительное обновление включает в себя различные исправления ошибок и улучшения производительности.

    3.5.2 (ноябрь 2019 г.)

    Это незначительное обновление включает в себя различные исправления ошибок и улучшения производительности. Чтобы просмотреть список заметных исправлений ошибок, прочитайте соответствующую публикацию в блоге Release Updates .

    3.5.1 (октябрь 2019 г.)

    Это незначительное обновление включает в себя различные исправления ошибок и улучшения производительности. Чтобы просмотреть список заметных исправлений ошибок, прочитайте соответствующую публикацию в блоге Release Updates .

    Проект «Мрамор»: здоровье системы

    В этом разделе описаны изменения в Android Studio 3.5, направленные на улучшение работоспособности системы.

    Рекомендуемые настройки памяти

    Android Studio теперь уведомляет вас, если обнаруживает, что вы можете повысить производительность, увеличив максимальный объем оперативной памяти, который ваша ОС должна выделять для процессов Android Studio, таких как базовая среда IDE, демон Gradle и демон Kotlin. Вы можете либо принять рекомендуемые настройки, щелкнув ссылку действия в уведомлении, либо настроить эти параметры вручную, выбрав «Файл» > «Настройки» (или Android Studio > «Настройки» в macOS), а затем найдя раздел «Настройки памяти» в разделе «Внешний вид и поведение» > Системные настройки . Дополнительные сведения см. в разделе Максимальный размер кучи .

    Уведомление о рекомендуемых настройках памяти.

    Уведомление о рекомендуемых настройках памяти.

    Отчет об использовании памяти

    Проблемы с памятью в Android Studio иногда сложно воспроизвести и сообщить о них. Чтобы решить эту проблему, Android Studio позволяет создать отчет об использовании памяти, нажав «Справка» > «Анализ использования памяти» в строке меню. При этом IDE локально очищает данные от личной информации, прежде чем спросить, хотите ли вы отправить их команде Android Studio, чтобы помочь определить источник проблем с памятью. Дополнительные сведения см. в разделе Создание отчета об использовании памяти .

    Отчет об использовании памяти.

    Отчет об использовании памяти.

    Windows: антивирусная оптимизация файлового ввода-вывода

    Android Studio теперь автоматически проверяет, исключены ли определенные каталоги проектов из антивирусного сканирования в реальном времени. Когда можно внести изменения для повышения производительности сборки, Android Studio уведомит вас и предоставит инструкции по оптимизации конфигурации антивируса. Дополнительные сведения см. в разделе Минимизация влияния антивирусного программного обеспечения на скорость сборки .

    Project Marble: полировка функций

    В этом разделе описаны изменения в Android Studio 3.5, направленные на улучшение существующих функций.

    Применить изменения

    Применить изменения позволяет вносить изменения кода и ресурсов в работающее приложение без перезапуска приложения, а в некоторых случаях и без перезапуска текущего действия. Применить изменения реализует совершенно новый подход к сохранению состояния вашего приложения. В отличие от Instant Run, который переписывал байт-код вашего APK, Apply Changes переопределяет классы на лету, используя инструменты среды выполнения, поддерживаемые в Android 8.0 (уровень API 26) или выше.

    Дополнительную информацию см. в разделе «Применить изменения» .

    Кнопки панели инструментов для применения изменений.

    Кнопки панели инструментов для применения изменений.

    Процесс развертывания приложения

    В IDE имеется новое раскрывающееся меню, позволяющее быстро выбрать устройство, на котором вы хотите развернуть свое приложение. В этом меню также есть новая опция, которая позволяет запускать приложение на нескольких устройствах одновременно.

    Раскрывающееся меню целевого устройства.

    Раскрывающееся меню целевого устройства.

    Улучшена синхронизация Gradle и обнаружение кеша.

    IDE теперь лучше определяет, когда Gradle периодически очищает кэш сборки при уменьшении потребления жесткого диска. В предыдущих версиях это состояние приводило к тому, что IDE сообщала об отсутствующих зависимостях и приводила к сбою синхронизации Gradle. Теперь IDE просто загружает зависимости по мере необходимости, чтобы гарантировать успешное завершение синхронизации Gradle.

    Улучшен вывод ошибок сборки.

    Сборка Значок окна сборки Окно теперь предоставляет улучшенные отчеты об ошибках, например ссылку на файл и строку сообщения об ошибке, для следующих процессов сборки:

    • Компиляция и связывание AAPT
    • R8 и ПроГард
    • Дексинг
    • Объединение ресурсов
    • синтаксический анализ XML-файла
    • Компиляция Javac, Kotlinc и CMake

    Обновления проекта

    Улучшен процесс обновления, предоставляющий больше информации и действий, которые помогут вам обновить IDE и плагин Android Gradle. Например, дополнительные ошибки синхронизации и сборки включают действия, которые помогут вам устранить ошибки при обновлении.

    Важно помнить, что вы можете обновлять IDE независимо от других компонентов, таких как плагин Android Gradle. Таким образом, вы можете безопасно обновить IDE, как только станет доступна более новая версия, а другие компоненты обновить позже.

    Редактор макетов

    Android Studio 3.5 включает несколько улучшений в визуализации макета, управлении и взаимодействии.

    При работе с ConstraintLayout в новом разделе «Ограничения» на панели «Атрибуты» перечислены отношения ограничений выбранного компонента пользовательского интерфейса. Вы можете выбрать ограничение либо в области проектирования, либо в списке ограничений, чтобы выделить ограничение в обеих областях.

    Отношения ограничений для выбранного элемента пользовательского интерфейса.

    Отношения ограничений для выбранного элемента пользовательского интерфейса.

    Аналогичным образом теперь вы можете удалить ограничение, выбрав его и нажав клавишу Delete . Вы также можете удалить ограничение, удерживая клавишу Control ( Command в macOS) и щелкнув якорь ограничения. Обратите внимание: когда вы удерживаете клавишу Control или Command и наводите курсор на якорь, все связанные ограничения становятся красными, показывая, что вы можете щелкнуть их, чтобы удалить.

    Когда представление выбрано, вы можете создать ограничение, щелкнув любой из значков + в разделе «Виджет ограничения» на панели «Атрибуты» , как показано на следующем изображении. Когда вы создаете новое ограничение, редактор макета теперь выбирает и выделяет ограничение, обеспечивая немедленную визуальную информацию о том, что вы только что добавили.

    Анимация, показывающая, как использовать виджет ограничений для создания ограничений.

    Использование виджета ограничений для создания ограничений.

    При создании ограничения Редактор макетов теперь показывает только подходящие опорные точки, для которых можно ограничиться. Раньше Редактор макетов выделял все опорные точки во всех представлениях, независимо от того, можно ли их ограничить. Кроме того, синяя накладка теперь выделяет цель ограничения. Это выделение особенно полезно при попытке ограничить компонент, который перекрывается с другим.

    Анимация, показывающая, как создать ограничение для перекрывающегося компонента в Android Studio 3.4.

    Создание ограничения для перекрывающегося компонента в Android Studio 3.4.

    Анимация, показывающая, как создать ограничение для перекрывающегося компонента в Android Studio 3.5.

    Создание ограничения для перекрывающегося компонента в Android Studio 3.5.

    Помимо вышеуказанных обновлений, Android Studio 3.5 также содержит следующие улучшения редактора макетов:

    • Виджет ограничений и раскрывающийся список полей по умолчанию теперь позволяют использовать ресурсы измерений для полей.
    • На панели инструментов редактора макетов обновлен список устройств, определяющих размер области дизайна. Кроме того, было улучшено поведение привязки при изменении размера, а маркеры изменения размера в области дизайна теперь всегда видны. При изменении размера появляются новые наложения, показывающие распространенные размеры устройств.
    • Редактор макетов имеет новую цветовую схему, которая улучшает согласованность и уменьшает контраст между компонентами, текстом и ограничениями.
    • Режим Blueprint теперь включает поддержку текста для некоторых компонентов, где текст не отображался.

    Дополнительные сведения об этих изменениях см. в разделе Android Studio Project Marble: редактор макетов .

    Привязка данных

    Помимо добавления поддержки дополнительной обработки аннотаций для привязки данных, IDE улучшает функции и производительность интеллектуального редактора при создании выражений привязки данных в XML.

    Анимация, показывающая производительность редактора кода в Android Studio 3.4.

    Производительность редактора кода в Android Studio 3.4.

    Анимация, показывающая производительность редактора кода в Android Studio 3.5.

    Улучшена производительность редактирования кода в Android Studio 3.5.

    Улучшенная поддержка проектов C/C++.

    Android Studio 3.5 включает несколько изменений, улучшающих поддержку проектов C/C++.

    Улучшения панели «Варианты сборки» для синхронизации одного варианта

    Теперь вы можете указать как активный вариант сборки, так и активный ABI на панели «Варианты сборки» . Эта функция упрощает настройку сборки для каждого модуля, а также может улучшить производительность синхронизации Gradle.

    Дополнительные сведения см. в разделе Изменение варианта сборки .

    Панель «Варианты сборки», показывающая выбор одного варианта с помощью ABI.

    Панель «Варианты сборки» с выбором одного варианта с помощью ABI.

    Параллельные версии NDK

    Теперь вы можете использовать несколько версий NDK одновременно. Эта функция дает вам большую гибкость при настройке ваших проектов — например, если у вас есть проекты, использующие разные версии NDK на одном компьютере.

    Если в вашем проекте используется плагин Android Gradle 3.5.0 или выше, вы также можете указать версию NDK, которую должен использовать каждый модуль в вашем проекте. Вы можете использовать эту функцию для создания воспроизводимых сборок и устранения несовместимости между версиями NDK и плагином Android Gradle.

    Дополнительные сведения см. в разделе Установка и настройка NDK, CMake и LLDB .

    Поддержка ChromeOS

    Android Studio теперь официально поддерживает устройства ChromeOS, такие как HP Chromebook x360 14, Acer Chromebook 13/Spin 13 и другие, о которых вы можете прочитать в системных требованиях . Для начала загрузите Android Studio на совместимое устройство с ChromeOS и следуйте инструкциям по установке .

    Примечание. Android Studio на ChromeOS в настоящее время поддерживает развертывание вашего приложения только на подключенном аппаратном устройстве. Чтобы узнать больше, прочитайте Запуск приложений на аппаратном устройстве .

    Условная доставка функциональных модулей

    Условная доставка позволяет вам установить определенные требования к конфигурации устройства для автоматических загрузок функциональных модулей во время установки приложения. Например, вы можете настроить функциональный модуль, включающий функции дополненной реальности (AR), который будет доступен при установке приложения только для устройств, поддерживающих AR.

    В настоящее время этот механизм доставки поддерживает управление загрузкой модуля во время установки приложения на основе следующих конфигураций устройства:

    • Аппаратные и программные функции устройства, включая версию OpenGL ES
    • Страна пользователя
    • уровень API

    Если устройство не соответствует всем указанным вами требованиям, модуль не загружается во время установки приложения. Однако позже ваше приложение может запросить загрузку модуля по требованию с помощью основной библиотеки Play. Дополнительные сведения см. в разделе Настройка условной доставки .

    IntelliJ ИДЕЯ 2019.1

    Базовая среда разработки Android Studio была обновлена ​​за счет улучшений от IntelliJ IDEA до версии 2019.1 , таких как настройка тем.

    Последней версией IntelliJ, включенной в Android Studio, была 2018.3.4. Дополнительные сведения об улучшениях других версий IntelliJ, включенных в совокупный выпуск этой версии Android Studio, см. в следующих обновлениях с исправлениями ошибок:

    Обновления плагина Android Gradle 3.5.0

    Информацию о новых возможностях плагина Android Gradle 3.5.0, таких как улучшенная поддержка инкрементной обработки аннотаций и кэшируемых модульных тестов, см. в примечаниях к выпуску .

    Участники сообщества

    Благодарим всех участников нашего сообщества, которые помогли нам обнаружить ошибки и найти другие способы улучшения Android Studio 3.5. В частности, мы хотели бы поблагодарить следующих людей, сообщивших об ошибках P0 и P1:

    3.4 (апрель 2019 г.)

    Android Studio 3.4 — это основной выпуск, включающий множество новых функций и улучшений.

    3.4.2 (июль 2019 г.)

    Это незначительное обновление включает в себя различные исправления ошибок и улучшения производительности. Чтобы просмотреть список заметных исправлений ошибок, прочитайте соответствующую публикацию в блоге Release Updates .

    3.4.1 (май 2019 г.)

    Это незначительное обновление включает в себя различные исправления ошибок и улучшения производительности. Чтобы просмотреть список заметных исправлений ошибок, прочитайте соответствующую публикацию в блоге Release Updates .

    3.4.0 известные проблемы

    • Профилирование отключается при развертывании приложения на устройстве под управлением Android Q Beta.

    • При использовании библиотеки привязки данных LiveDataListener.onChanged() может завершиться ошибкой с NPE. Исправление этой проблемы будет включено в Android Studio 3.4.1 и уже доступно в последней предварительной версии Android Studio 3.5. (См. выпуск № 122066788 )

    IntelliJ ИДЕЯ 2018.3.4

    Базовая среда разработки Android Studio была обновлена ​​за счет улучшений от IntelliJ IDEA до версии 2018.3.4 .

    Обновления плагина Android Gradle 3.4.0

    Информацию о том, что нового в плагине Android Gradle 3.4.0, см. в примечаниях к его выпуску .

    Диалоговое окно «Новая структура проекта»

    Новый диалог структуры проекта (PSD) упрощает обновление зависимостей и настройку различных аспектов вашего проекта, таких как модули, варианты сборки, конфигурации подписи и переменные сборки.

    Вы можете открыть PSD, выбрав «Файл» > «Структура проекта» в строке меню. Вы также можете открыть PSD, нажав Ctrl+Shift+Alt+S в Windows и Linux или Command+; (точка с запятой) в macOS. Ниже вы можете найти описания некоторых новых и обновленных разделов PSD.

    Переменные

    Новый раздел переменных PSD позволяет создавать переменные сборки и управлять ими, например, для обеспечения единообразия номеров версий зависимостей во всем проекте.

    • Быстро просматривайте и редактируйте переменные сборки, которые уже существуют в сценариях сборки Gradle вашего проекта.
    • Добавляйте новые переменные сборки на уровне проекта или модуля непосредственно из PSD.

    Примечание. Если в существующих файлах конфигурации сборки значения присваиваются с помощью сложных сценариев Groovy, возможно, вы не сможете редактировать эти значения с помощью PSD. Кроме того, вы не можете редактировать файлы сборки, написанные на Kotlin, с помощью PSD.

    Модули

    Настройте свойства, которые применяются ко всем вариантам сборки в существующем модуле, или добавьте новые модули в свой проект из раздела «Модули» . Например, здесь вы можете настроить свойства defaultConfig или управлять конфигурациями подписи.

    Зависимости

    Проверьте и визуализируйте каждую зависимость в графе зависимостей вашего проекта, разрешенную Gradle во время синхронизации проекта, выполнив следующие действия:

    1. На левой панели PSD выберите «Зависимости» .
    2. На панели «Модули» выберите модуль, для которого вы хотите проверить разрешенные зависимости.
    3. В правой части PSD откройте панель «Разрешенные зависимости» , как показано ниже.

    Вы также можете быстро найти и добавить зависимости в свой проект, сначала выбрав модуль в разделе «Зависимости» PSD, нажав кнопку (+) в разделе «Объявленные зависимости» и выбрав тип зависимости, которую вы хотите добавить.

    В зависимости от типа выбранной вами зависимости, вы должны увидеть диалог, аналогичный приведенному ниже, который поможет вам добавить зависимость в модуль.

    Построить варианты

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

    Предложения

    См. Предлагаемые обновления для зависимости проекта и переменных построения в разделе предложений , как показано ниже.

    Новый менеджер ресурсов

    Resource Manager - это новое окно инструмента для импорта, создания, управления и использования ресурсов в вашем приложении. Вы можете открыть окно инструмента, выбрав View> Tool Windows> «Ресурсы» из строки меню. Менеджер ресурсов позволяет вам выполнить следующее:

    • Визуализируйте ресурсы: вы можете просмотреть рисунки, цвета и макеты, чтобы быстро найти необходимые вам ресурсы.
    • Основной импорт: вы можете импортировать несколько активов сразу же, либо перетаскивая, и бросив их в окно инструмента «Диспетчер ресурсов» , либо с помощью мастера импортных рисунков . Чтобы получить доступ к мастеру, выберите кнопку (+) в верхнем левом углу окна инструмента, а затем выберите «Импортные притяжения» из раскрывающегося меню.
    • Преобразовать SVG в VectorDrawable Objects: Вы можете использовать мастер импорта Drawables для преобразования ваших изображений SVG в VectorDrawable Objects.
    • Перетащите активы: из окна инструмента «Диспетчер ресурсов» вы можете перетаскивать рисования как на дизайн, так и на XML -виды редактора макета.
    • Просмотреть альтернативные версии: теперь вы можете просмотреть альтернативные версии ваших ресурсов, дважды щелкнув ресурс в окне инструмента . В этом представлении показаны различные версии, которые вы создали, и квалификаторы, которые были включены.
    • Просмотры плитки и списка: Вы можете изменить представление в окне инструмента, чтобы визуализировать свои ресурсы в разных договоренностях.

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

    Проверка идентификаторов сборки при профилировании и отладке APK

    Когда вы предоставляете файлы символов .so для .so .

    Если вы создаете нативные библиотеки в своем APK с помощью идентификатора сборки, Android Studio проверяет, соответствует ли идентификатор сборки в ваших файлах символов идентификатор сборки в ваших родных библиотеках и отклоняет файлы символов, если есть несоответствие. Если вы не строили с помощью идентификатора сборки, то предоставление неверных файлов символов может вызвать проблемы с отладкой.

    R8 включен по умолчанию

    R8 интегрирует десугарирование, сокращение, запутывание, оптимизацию и обезживание всего на одном шаге, что приводит к заметному улучшению производительности сборки . R8 был введен в плагин Android Gradle 3.3.0 и теперь включен по умолчанию как для проектов App, так и для библиотеки Android с использованием плагина 3.4.0 и выше.

    Изображение ниже содержит обзор процесса компиляции высокого уровня до введения R8.

    Перед R8 Proguard был другим шагом компиляции от Dexing и DeSugaring.

    Теперь, с R8, отсугация, сокращение, запутывание, оптимизация и дексинг (D8) завершены за один шаг, как показано ниже.

    С R8, десугарирование, сокращение, запутывание, оптимизация и дексинг выполняется на одном шаге компиляции.

    Имейте в виду, что R8 предназначен для работы с вашими существующими правилами прогноза, поэтому вам, вероятно, не нужно предпринять какие -либо действия, чтобы извлечь выгоду из R8. Однако, поскольку это другая технология для прогноза, которая разработана специально для проектов Android, сокращение и оптимизация могут привести к удалению кода, который, возможно, нет. Таким образом, в этой маловероятной ситуации вам может потребоваться добавить дополнительные правила, чтобы сохранить этот код в выводе сборки.

    Если вы испытываете проблемы с использованием R8, прочитайте FAQ совместимости R8, чтобы проверить, есть ли решение вашей проблемы. Если решение не задокументировано, сообщите об ошибке . Вы можете отключить R8, добавив одну из следующих строк в файл вашего проекта gradle.properties :

        # Disables R8 for Android Library modules only.
        android.enableR8.libraries = false
        # Disables R8 for all modules.
        android.enableR8 = false
        
      

    ПРИМЕЧАНИЕ. Для данного типа сборки, если вы установите useProguard в false в файле вашего приложения build.gradle , плагин Android Gradle использует R8 для сокращения кода вашего приложения для этого типа сборки, независимо от того, отключите ли вы R8 в gradle.properties Файл gradle.properties .

    Все типы аргументов, поддерживаемые навигационным компонентом, теперь поддерживаются в редакторе навигации. Для получения дополнительной информации о поддерживаемых типах см. Данные передачи между направлениями .

    Улучшения редактора макета {:#Mayout-Editor}

    Панель атрибутов в редакторе макета была упорядочена в одну страницу с разделами, которые вы можете развернуть, чтобы раскрыть атрибуты, которые вы можете настроить. Панель атрибутов также включает в себя следующие обновления:

    • В новом разделе «Объявленные атрибуты» перечислены атрибуты, указанные в файле макета, и позволяет быстро добавить новые.
    • Панель атрибутов теперь также показывает индикаторы рядом с каждым атрибутом, которые являются твердыми, когда значение атрибута является ссылкой на ресурс и в противном случае пусты.
    • Атрибуты с ошибками или предупреждениями теперь выделены. Красные выделения указывают на ошибки (например, когда вы используете неверные значения макета), а Orange Highles указывают предупреждения (например, когда вы используете жесткие значения).

    Новое намеренное действие для быстрого импорта зависимостей

    Если вы начнете использовать определенные классы JetPack и Firebase в вашем коде, новое намерение предлагает добавить необходимую зависимость библиотеки Gradle в ваш проект, если вы еще этого не сделали. Например, если вы ссылаетесь на класс WorkManager без сначала импорта требуемой зависимости android.arch.work:work-runtime , намеренное действие позволяет вам делать это легко за один щелчок, как показано ниже.

    В частности, поскольку JetPack переупаковал библиотеку поддержки в отдельные пакеты, которые легче управлять и обновлять, это намеренное действие помогает быстро добавить только зависимости, которые вам нужны для компонентов JetPack, которые вы хотите использовать.

    3.3 (январь 2019 г.)

    Android Studio 3.3 - это основной релиз, который включает в себя множество новых функций и улучшений.

    3.3.2 (март 2019 г.)

    Это незначительное обновление включает в себя различные исправления ошибок и улучшения производительности. Чтобы увидеть список заметных исправлений ошибок, прочитайте связанный пост в блоге обновления релизов .

    3.3.1 (февраль 2019 г.)

    Это незначительное обновление включает в себя различные исправления ошибок и улучшения производительности.

    Intellij Idea 2018.2.2

    Основная Android Studio IDE была обновлена ​​с улучшениями от Intellij Idea до выпуска 2018.2.2 .

    Обновления плагинов Android Gradle

    Для получения информации о том, что нового в плагине Android Gradle, см. Примечания к выпуску .

    Редактор навигации позволяет быстро визуализировать и встроить навигацию в вашем приложении с помощью компонента навигационной архитектуры .

    Для получения дополнительной информации см. Внедрение навигации с компонентом навигационной архитектуры .

    Удалить неиспользованные каталоги Android Studio

    Когда вы впервые запускаете основную версию Android Studio, он ищет каталоги, содержащие кэши, настройки, индексы и журналы для версий Android Studio, для которых невозможно найти соответствующую установку. Диалоговое окно «Удалить неиспользованную Android Studio» затем отображает местоположения, размеры и времена последних модифицированных этих неиспользованных каталогов и предоставляет возможность удалить их.

    Катарии Android Studio рассматривают для удаления, указаны ниже:

    • Linux: ~/.AndroidStudio[Preview] XY
    • Mac: ~/Library/{Preferences, Caches, Logs, Application Support}/AndroidStudio[Preview] XY
    • Windows: %USER%.AndroidStudio[Preview] XY

    Улучшения ворса

    Линт, когда вы призваны из Градл, значительно быстрее - более высокие проекты могут ожидать, что Линт будет работать в четыре раза быстрее.

    Создать новый мастер проекта

    The Create New Project Wizard имеет новый вид и содержит обновления, которые помогают упростить создание новых проектов Android Studio.

    Для получения дополнительной информации см. Создать проект .

    Профилирующие обновления

    Android Studio 3.3 включает в себя обновления нескольких отдельных профилировщиков.

    Улучшенная производительность

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

    Параметры отслеживания распределения памяти профилировщика

    Чтобы повысить производительность приложений при профилировании, профилировщик памяти теперь периодически вызывает распределение памяти по умолчанию. При желании вы можете изменить это поведение, используя раскрывающееся отслеживание распределения при тестировании на устройствах под управлением Android 8.0 (уровень API 26) или выше.

    Используя выпадающий отслеживание распределения , вы можете выбрать из следующих режимов:

    • Полный: захватывает все распределения памяти объекта. Обратите внимание, что если у вас есть приложение, которое выделяет много объектов, вы можете увидеть значительные проблемы с производительностью при профилировании.

    • Отбирается: захватывает периодическую выборку распределения памяти объектов. Это поведение по умолчанию и оказывает меньшее влияние на производительность приложений при профилировании. Вы можете столкнуться с некоторыми проблемами с производительностью с приложениями, которые выделяют много объектов в течение короткого периода времени.

    • OFF: выключает распределение памяти. Если еще не выбрано, этот режим включен автоматически при выполнении записи ЦП, а затем возвращается в предыдущую настройку при завершении записи. Вы можете изменить это поведение в диалоговом окне конфигурации записи ЦП.

      Отслеживание влияет как на объекты Java, так и ссылки на JNI.

    Проверьте данные о рендеринге кадров

    В Profiler CPU вы теперь можете проверить, сколько времени требуется вашему приложению Java, чтобы отобразить каждый кадр в основном потоке пользовательского интерфейса и renderThread. Эти данные могут быть полезны при исследовании узких мест, которые вызывают пользовательский интерфейс и низкие кадры. Например, каждая рама, которая занимает больше времени, чем 16 мс, необходимое для поддержания гладкой кадры, отображается красным.

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

    Чтобы узнать больше о изучении и решении проблем кадров, читайте медленный рендеринг .

    Фрагменты в случае временной шкалы событий

    Временная шкала событий теперь показывает, когда фрагменты прикрепляются и отделены. Кроме того, когда вы падаете над фрагментом, выявление инструментов показывает вам статус фрагмента.

    Просмотр форматированного текста для полезных нагрузок подключения в сетевом профилировке

    Ранее сетевой профилировщик отображал только необработанный текст из полезных нагрузок подключения. Android Studio 3.3 теперь форматирует определенные типы текстов по умолчанию, включая JSON, XML и HTML. На вкладках «Ответ и запрос» нажмите на разведущую ссылку View , чтобы отобразить форматированный текст и нажмите ссылку «Просмотр источника», чтобы отобразить необработанный текст.

    Для получения дополнительной информации см. Проверьте сетевой трафик с помощью сетевого профилировщика .

    Автоматическая загрузка компонентов SDK

    Когда ваш проект нуждается в компоненте SDK с платформ SDK, NDK или CMAKE, Gradle теперь пытается автоматически загружать необходимые пакеты, если вы ранее принимали какие -либо связанные лицензионные соглашения с использованием SDK Manager.

    Для получения дополнительной информации см. Автоматическую загрузку отсутствующих пакетов с Gradle .

    Поддержка Clang-Tidy

    Android Studio теперь включает в себя поддержку анализа статического кода с использованием Clang-Tidy для проектов, которые включают собственный код. Чтобы включить поддержку Clang-Tidy, обновите свой NDK до R18 или выше.

    Затем вы можете включить или повторно включить проверки, открыв диалоговое окно « Настройки или настройки» и перемещаясь в редактор> Инспекции> C/C ++> General> Clang-Tidy . При выборе этого осмотра в диалоговом окне «Настройки или настройки» вы также можете увидеть список чеков Clang-Tidy, которые включены и отключены в разделе «Опция» на самой правой панели. Чтобы включить дополнительные проверки , добавьте их в список и нажмите «Применить» .

    Чтобы настроить Clang-Tidy с дополнительными параметрами , нажмите «Настроить параметры Clang-Tidy» и добавьте их в открытый диалог.

    Удаление параметров для настройки C ++

    Следующие параметры были удалены из диалогового окна «Настройка C ++ поддержки» :

    • Исключения поддержка (-fexceptions)
    • Информационная поддержка типа выполнения (-ftti)

    Соответствующее поведение включено для всех проектов, созданных через Android Studio.

    Cmake версия 3.10.2

    Cmake версия 3.10.2 теперь включена в SDK Manager. Обратите внимание, что Gradle по -прежнему использует версию 3.6.0 по умолчанию.

    Чтобы указать версию Cmake для использования Gradle, добавьте следующее в файл вашего модуля build.gradle :

        android {
            ...
            externalNativeBuild {
                cmake {
                    ...
                    version "3.10.2"
                }
            }
        }
        
      

    Для получения дополнительной информации о настройке cmake в build.gradle см. Вручную настройку Gradle .

    Новый синтаксис «+» для указания минимальных версий Cmake

    При указании версии CMAKE в файле build.gradle вашего основного модуля вы можете добавить «+», чтобы соответствовать поведению команды CMAKE cmake_minimum_required() .

    Осторожность: использование синтаксиса «+» с другими зависимостями для сборки не рекомендуется, поскольку динамические зависимости могут вызвать неожиданные обновления версий и трудности с разрешением различий в версиях.

    Приложения Android теперь поддерживают мгновенные приложения

    Android Studio теперь позволяет создавать пакеты приложений Android с полной поддержкой Google Play Instrant . Другими словами, теперь вы можете создавать и развернуть как установленное приложение, так и мгновенные впечатления от одного проекта Android Studio и включить их в один пакет приложений Android.

    Если вы создаете новый проект Android Studio, используя диалоговое окно «Создать новый проект» , убедитесь, что вы установите флажок рядом с настройкой вашего проекта> Этот проект будет поддерживать Instant Apps . Android Studio затем создает новый проект приложения, как обычно, но включает в себя следующие свойства в вашем манифесте, чтобы добавить мгновенную поддержку приложения к базовому модулю вашего приложения:

        <manifest ... xmlns:dist="http://schemas.android.com/apk/distribution">
            <dist:module dist:instant="true" />
            ...
        </manifest>
        
      

    Затем вы можете создать модуль функции с интенсивным образом с мощностью , выбрав File> Новый> Новый модуль из строки меню, а затем выбрав модуль мгновенной динамической функции из диалога «Создать новый модуль» . Имейте в виду, что создание этого модуля также мгновенными базовыми модулем вашего приложения.

    Чтобы развернуть ваше приложение на локальное устройство в качестве мгновенного опыта, отредактируйте конфигурацию выполнения и установите флажок рядом с General> Deploy в качестве приложения Instant .

    Синхронизация с одним вариантом проекта

    Синхронизация вашего проекта с помощью конфигурации сборки является важным шагом в том, чтобы позволить Android Studio понять, как структурирован ваш проект. Тем не менее, этот процесс может быть трудоемким для крупных проектов. Если ваш проект использует несколько вариантов сборки, теперь вы можете оптимизировать синхронизации проекта, ограничивая их только на выбранном вами варианте.

    Вам необходимо использовать Android Studio 3.3 или выше с плагином Android Gradle 3.3.0 или выше, чтобы включить эту оптимизацию. Когда вы выполняете эти требования, IDE побуждает вас включить эту оптимизацию при синхронизации своего проекта. Оптимизация также по умолчанию включена по новым проектам.

    Чтобы включить эту оптимизацию вручную, нажмите «Файл»> «Настройки»> «Экспериментальная»> «Градл» ( Android Studio> Preferences> Experimental> Gradle на Mac) и выберите единственную синхронизационную флажок.

    Примечание. Эта оптимизация в настоящее время поддерживает проекты, которые включают только язык программирования Java. Если, например, IDE обнаруживает код Kotlin или C ++ в вашем проекте, он не автоматически не позволяет этой оптимизации, и вы не должны включать его вручную.

    Для получения дополнительной информации см. Включите синхронизацию одного варинового проекта .

    Обеспечить быстрый отзыв

    Если вы решили поделиться статистикой использования, чтобы помочь улучшить Android Studio, вы увидите эти две новые значки в строке состояния внизу окна IDE:

    Просто нажмите на значок, который лучше всего представляет ваш текущий опыт с IDE. Когда вы это делаете, IDE отправляет статистику использования, которая позволяет команде Android Studio лучше понять ваши настроения. В некоторых случаях, например, когда вы указываете негативный опыт работы с IDE, у вас будет возможность предоставить дополнительную обратную связь.

    Если вы еще этого не сделали, вы можете включить статистику использования обмена, открыв диалоговые настройки настроек на Mac), навигация на внешний вид и поведение> Настройки системы> Обмен данные и проверка отправки статистики использования в Google .

    3.2 (сентябрь 2018 г.)

    Android Studio 3.2 является основным выпуском, который включает в себя различные новые функции и улучшения.

    3.2.1 (октябрь 2018 г.)

    Это обновление для Android Studio 3.2 включает в себя следующие изменения и исправления:

    • Версия Котлина в комплекте теперь 1.2.71.
    • Версия инструментов по умолчанию теперь 28.0.3.
    • В навигационной библиотеке типы аргументов были переименованы из type в argType .
    • Следующие ошибки были исправлены:
      • При использовании библиотеки привязки данных имена переменных с подчеркиванием вызывали ошибки компиляции.
      • Cmake заставлял Intellisense и другие функции Clion потерпеть неудачу.
      • Добавление SliceProvider вызывало ошибки компиляции в проектах, которые не использовали androidx.* Библиотеки.
      • Некоторые модульные тесты Kotlin не проходили.
      • Проблема с привязкой данных вызывала PsiInvalidElementAccessException .
      • <merge> элементы иногда заставляли редактора макета разбиться.

    3.2.0 Известные проблемы

    Примечание. Эти проблемы были решены в Android Studio 3.2.1

    • Мы настоятельно рекомендуем использовать Kotlin версию 1.2.70.

      Котлин версии 1.2.61 Исправляет ошибку, которая может привести к висел Android Studio, но Kotlin 1.2.70 не включает в себя это исправление .

      Котлин версии 1.2.71 и позже, однако, включают это исправление.

    • Хотя вам обычно не нужно указывать версию инструментов сборки, при использовании плагина Android Gradle 3.2.0 с renderscriptSupportModeEnabled set в true , вам необходимо включить следующее в файл build.gradle каждого модуля:

      android.buildToolsVersion "28.0.3"

    Что нового помощника

    Новый помощник сообщает вам о последних изменениях в Android Studio.

    Помощник открывается, когда вы запускаете Android Studio после новой установки или обновления, если он обнаруживает, что есть новая информация. Вы также можете открыть помощника, выбрав помощь> Что нового в Android Studio .

    Android JetPack

    Android JetPack помогает ускорить разработку Android с помощью компонентов, инструментов и руководств, которые устраняют повторяющиеся задачи и позволяют вам быстрее и легко создавать высококачественные тестируемые приложения. Android Studio включает в себя следующие обновления для поддержки JetPack. Для получения дополнительной информации см. Документацию JetPack .

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

    В Android Studio 3.2 редактор навигации является экспериментальной функцией. Чтобы включить редактор навигации, нажмите «Файл»> «Настройки» ( Android Studio> Настройки на Mac), выберите экспериментальную категорию на левой панели, установите флажок, чтобы включить редактор навигации и перезапустить Android Studio.

    Чтобы узнать больше, прочитайте документацию редактора навигации .

    Миграция Androidx

    В рамках JetPack мы мигрируем библиотеки поддержки Android в новую библиотеку расширения Android с использованием пространства имен androidx . Для получения дополнительной информации см. Обзор Androidx .

    Android Studio 3.2 помогает вам в этом процессе с новой функцией миграции.

    Чтобы мигрировать существующий проект в Androidx, выберите Refactor> Migrate в Androidx . Если у вас есть какие -либо зависимости Maven, которые не мигрировали в пространство имен Androidx, система сборки Android Studio также автоматически преобразует эти зависимости проекта.

    Плагин Android Gradle предоставляет следующие глобальные флаги, которые вы можете установить в своем файле gradle.properties :

    • android.useAndroidX : Когда установлено в true , этот флаг указывает, что вы хотите начать использовать Androidx. Если флаг отсутствует, Android Studio ведет себя так, как будто флаг был установлен на false .
    • android.enableJetifier : при установке true , этот флаг указывает, что вы хотите иметь поддержку инструментов (из плагина Android Gradle) для автоматического преобразования существующих сторонних библиотек, как если бы они были написаны для Androidx. Если флаг отсутствует, Android Studio ведет себя так, как будто флаг был установлен на false .

    Оба флага устанавливаются на true когда вы используете команду Migrate to Androidx .

    Если вы хотите немедленно начать использовать библиотеки Androidx и не нужно преобразовать существующие сторонние библиотеки, вы можете установить флаг android.useAndroidX в true и флаг android.enableJetifier на false .

    Android App Bundle

    Android App Bundle - это новый формат загрузки, который включает в себя все скомпилированные коды и ресурсы вашего приложения, но определяет генерацию APK и подписывает в магазин Google Play.

    Новая модель Google Play для обслуживания приложения использует ваш пакет приложений для генерации и обслуживания оптимизированных APK для конфигурации устройства каждого пользователя, поэтому каждый пользователь загружает только код и ресурсы, которые им необходимы для запуска вашего приложения. Вам больше не нужно строить, подписывать и управлять несколькими APK, и пользователи получают меньшие, более оптимизированные загрузки.

    Кроме того, вы можете добавить модули функций в проект вашего приложения и включить их в свой пакет приложений. Затем ваши пользователи могут загрузить и установить функции вашего приложения по требованию.

    Чтобы построить комплект, выберите Build> Build Bundle (ы) / APK (S)> Build Back (ы) .

    Для получения дополнительной информации, включая инструкции по созданию и анализе пакета приложений Android, см. Adroid App Bundle .

    Пример данных в редакторе макета

    Многие макеты Android имеют данные времени выполнения, которые могут затруднить визуализацию внешнего вида и ощущения макета на этапе разработки приложений. Теперь вы можете легко увидеть предварительный просмотр вашего представления в редакторе макета, заполненного образцами данных. Когда вы добавляете вид, кнопку Появится ниже вида в окне дизайна. Нажмите эту кнопку, чтобы установить атрибуты представления времени дизайна. Вы можете выбрать из множества образцов шаблонов данных и указать количество образцов элементов, с помощью которых можно заполнить представление.

    Чтобы попробовать использование образцов данных, добавьте RecyclerView в новый макет, нажмите кнопку «Время разработки» Под представлением и выберите выбор из карусели шаблонов образцов данных.

    Ломтики

    Среции обеспечивают новый способ внедрить части функциональности вашего приложения в другие поверхности пользовательского интерфейса на Android. Например, срезы позволяют показывать функциональность и контент приложений в предложениях поиска Google.

    Android Studio 3.2 имеет встроенный шаблон, который поможет вам расширить ваше приложение с помощью новых API-провайдеров поставщика среза, а также новые проверки Lint, чтобы убедиться, что вы следите за лучшими практиками при построении срезов.

    Чтобы начать, щелкните правой кнопкой мыши папку проекта и выберите «Новый»> «Другой»> «Поставщик срезов» .

    Чтобы узнать больше, в том числе о том, как проверить взаимодействие с ломтиками, прочитайте руководство по началу работы .

    Котлин 1.2.61

    Android Studio 3.2 Bundles Kotlin 1.2.61, и новый Android SDK лучше интегрируется с Kotlin. Для получения дополнительной информации см. Блог Developers Android .

    Intellij Idea 2018.1.6

    Основная Android Studio IDE была обновлена ​​с улучшениями от Intellij Idea до выпуска 2018.1.6 .

    Android Profilers

    Попробуйте следующие новые функции Android Profiler в Android Studio 3.2.

    Сессии

    Теперь вы можете сохранить данные Profiler в качестве сеансов , чтобы вернуться и осмотреть позже. Профилировщик сохраняет данные вашего сеанса, пока вы не перезапустите IDE.

    Когда вы записываете метод трассировки или захватывают дамп кучи , IDE добавляет эти данные (наряду с сетевой деятельностью вашего приложения) в качестве отдельной записи в текущий сеанс, и вы можете легко переключаться между записями для сравнения данных.

    Системная трасса

    В Profiler CPU выберите новую конфигурацию системы System Trace , чтобы осмотреть системный процессор и активность системы вашего устройства. Эта конфигурация трассировки построена на systrace и полезна для изучения проблем на уровне системы, таких как UI Jank.

    Используя эту конфигурацию трассировки, вы можете визуально отмечать важные процедуры кода в временной шкале Profiler, придавая код C/C ++ с помощью API нативного трассировки или кода Java с классом Trace .

    Осмотрите ссылки на JNI в профилировке памяти

    Если вы развернете свое приложение на устройство, использующее Android 8.0 (уровень API 26) или выше, теперь вы можете проверить распределение памяти для кода JNI вашего приложения, используя профилировщик памяти .

    В то время как ваше приложение работает, выберите часть временной шкалы, которую вы хотите осмотреть, и выберите jni Heap из раскрывающегося меню над списком классов, как показано ниже. Затем вы можете осмотреть объекты в куче, как обычно, и дважды щелкнуть объекты на вкладке стека вызовов распределения , чтобы увидеть, где ссылки JNI выделяются и выпущены в вашем коде.

    Импорт, экспорт и осмотреть файлы дампы кучи памяти

    Теперь вы можете импортировать, экспортировать и осмотреть файлы дамп .hprof кучами памяти, созданные с помощью Profiler Memory .

    Импортируйте свой файл .hprof , нажав STANG New Profiler Session В панели сессий профилировщика, а затем выбирая нагрузку из файла . Затем вы можете осмотреть его данные в профилировке памяти, как и любой другой дамп кучи.

    Чтобы сохранить данные дампа кучи для просмотра позже, используйте кнопку дамп экспорта куча справа от входа на дамп кучи на панели сеансов . В диалоговом окне «Экспорт как» сохраните файл с расширением файла .hprof .

    Запишите активность процессора во время стартапа приложений

    Теперь вы можете записать активность процессора во время стартапа вашего приложения, следующим образом:

    1. Выберите «Запустить»> «Редактировать конфигурации» из главного меню.
    2. Под вкладкой «Профилирование» в вашей желаемой конфигурации запуска установите флажок рядом, чтобы начать запись метода трассировки при запуске .
    3. Выберите конфигурацию записи ЦП, чтобы использовать в раскрывающемся меню.
    4. Разверните ваше приложение на устройство, использующее Android 8.0 (API -уровень 26) или выше, выбрав профиль Run> .
    Экспорт ЦП Троты

    После того, как вы записываете деятельность процессора с профилировщиком ЦП, вы можете экспортировать данные в виде файла .trace , чтобы поделиться с другими или проверять позже.

    Чтобы экспортировать трассировку после того, как вы записали активность процессора, сделайте следующее:

    1. Щелкните правой кнопкой мыши на записи, которую вы хотите экспортировать с временной шкалы процессора.
    2. Выберите экспортный трассировку в раскрывающемся меню.
    3. Перейдите к тому, где вы хотите сохранить файл, и нажмите «Сохранить» .
    Импорт и осмотрите файлы трассировки процессора

    Теперь вы можете импортировать и проверять .trace , созданные с помощью API отладки или профилировщика CPU . (В настоящее время вы не можете импортировать записи System Trace.)

    Импортируйте свой файл трассировки, нажав на начало нового сеанса Profiler В панели сессий профилировщика, а затем выбирая нагрузку из файла . Затем вы можете осмотреть его данные в профилировке процессора, аналогично тому, как вы обычно делаете, за следующими исключениями:

    • Активность ЦП не представлена ​​вдоль временной шкалы процессора.
    • Временная шкала активности потока указывает только на то, где доступны данные трассировки для каждого потока, а не фактические состояния потока (например, запуск, ожидание или сон).
    Запишите активность процессора с использованием API отладки

    Теперь вы можете начать и прекратить запись активности процессора в профилировтеле ЦП, придавая приложение с помощью API отладки . После того, как вы развернете свое приложение на устройство, Profiler автоматически начинает записывать активность процессора, когда ваше приложение вызывает startMethodTracing(String tracePath) , а профилировщик прекращает запись, когда ваше приложение вызывает stopMethodTracing() . При записи активности процессора, которая запускается с использованием этого API, профилировщик ЦП показывает API отладки в качестве выбранной конфигурации записи ЦП.

    Энергетический профилировщик

    Энергетический профилировщик отображает визуализацию предполагаемого использования энергии вашего приложения, а также системных событий, которые влияют на использование энергии, такие как Wakelocks, тревога и задания.

    Профилировщик энергии появляется в виде новой строки в нижней части окна Profiler , когда вы запускаете приложение на подключенном устройстве или эмуляторе Android под управлением Android 8.0 (API 26) или выше.

    Нажмите « Энергетическая строка», чтобы максимизировать представление профилировщика энергии. Поместите указатель мыши на полосу на временной шкале, чтобы увидеть разбивку энергии с помощью ресурсов CPU, сети и местоположения (GPS), а также соответствующих системных событий.

    Системные события, которые влияют на использование энергии, указаны на временной шкале системы под временной шкалой энергии . Детали системных событий в пределах указанного временного диапазона отображаются на панели событий, когда вы выбираете диапазон времени на временной шкале энергии .

    Чтобы увидеть стек вызовов и другие детали для системного события, например Wakelock, выберите его на панели событий. Чтобы перейти к коду, ответственному за системное событие, дважды щелкните запись в стеке вызовов.

    Проверка ворса

    Android Studio 3.2 включает в себя множество новых и улучшенных функций для проверки ворса .

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

    Проверки Lint на совместимость Java/Kotlin

    Чтобы убедиться, что ваш код Java хорошо взаимодействует с вашим кодом Kotlin, новые проверки Lint обеспечивают лучшие практики, описанные в руководстве по взаимодействию Kotlin . Примеры этих проверок включают в себя поиск наличия аннотаций нуля, использование жестких ключевых слов Kotlin и размещение параметров Lambda в течение длительного времени.

    Чтобы включить эти проверки, нажмите «Файл»> «Настройки» ( Android Studio> Настройки на Mac), чтобы открыть диалоговое окно «Настройки» , перейдите к редактору> Investections> Android> Lint> Feelmentability> Раздел взаимодействия Kotlin и выберите правила, которые вы хотите включить.

    Чтобы включить эти проверки для сборки командной строки, добавьте следующее в свой файл build.gradle :

            android {
                lintOptions {
                    check 'Interoperability'
                }
            }
            
          
    Проверки на наличие ломтиков

    Новые чеки на ломтиках помогают убедиться, что вы правильно создаете срезы. Например, проверки Lint предупреждают вас, если вы не назначили первичное действие на срез.

    Новая градл -цель

    Используйте новую задачу lintFix Gradle, чтобы применить все безопасные исправления, предложенные проверкой Lint непосредственно на исходный код. Примером проверки ворса, которая предполагает безопасное исправление для применения, является SyntheticAccessor .

    Обновления метаданных

    Различные метаданные, такие как проверка актерского состава, были обновлены для проверки ворса для работы с Android 9 (уровень API 28).

    Предупреждение, если запустить Lint на новом варианте

    Lint теперь записывает, какой вариант и версию записаны базовая линия, и Линт предупреждает вас, если вы запустите его на другом варианте, чем тот, с которым был создан базовая линия.

    Улучшения в существующих чеков с ворсом

    Android Studio 3.2 включает в себя множество улучшений в существующих чеков ворса. Например, проверки цикла ресурсов теперь применяются к дополнительным типам ресурсов, и детектор перевода может найти отсутствующие переводы на лету, в редакторе.

    Идентификаторы выпуска более обнаружены

    Идентификаторы выпуска теперь теперь показаны в большем количестве мест, в том числе в окне результатов проверки . Это облегчает вам найти информацию, необходимую для включения или отключения конкретных проверок с помощью lintOptions в build.gradle .

    Для получения дополнительной информации см. Настройте параметры Lint с Gradle .

    Привязывание данных v2

    Привлечение данных v2 теперь включено по умолчанию и совместимо с V1. Это означает, что, если у вас есть библиотечные зависимости, которые вы скомпилировали с V1, вы можете использовать их с помощью проектов с использованием привязки данных v2. Однако обратите внимание, что проекты, использующие V1, не могут потреблять зависимости, которые были составлены с V2.

    D8 DeSugaring

    В Android Studio 3.1 мы интегрировали шаг десугарирования в инструмент D8 в качестве экспериментальной функции, сокращая общее время сборки. В Android Studio 3.2, осыпание с D8 включается по умолчанию.

    Новый кодовый усадка

    R8 - это новый инструмент для сокращения кода и запутывания, который заменяет прогибу. Вы можете начать использовать предварительную версию R8, включив следующее в файл вашего проекта gradle.properties :

          android.enableR8 = true
        

    Изменено ABIS по умолчанию для мульти-APK

    При создании нескольких APK , которые каждая нацелена на другой ABI, плагин больше не генерирует APK для следующих ABIS по умолчанию: mips , mips64 и armeabi .

    If you want to build APKs that target these ABIs, you must use NDK r16b or lower and specify the ABIs in your build.gradle file, as shown below:

        splits {
            abi {
                include 'armeabi', 'mips', 'mips64'
                ...
            }
        }
        
        splits {
            abi {
                include("armeabi", "mips", "mips64")
                ...
            }
        }
        

    Note: This behavior change is also included in Android Studio 3.1 RC1 and higher.

    Improved editor features for CMake build files

    If you use CMake to add C and C++ code to your project , Android Studio now includes improved editor features to help you to edit your CMake build scripts, such as the following:

    • Syntax highlighting and code completion: The IDE now highlights and suggests code completion for common CMake commands. Additionally, you can navigate to a file by clicking it while pressing the Control key (Command on Mac).
    • Code reformatting: You can now use IntelliJ's code reformat option to apply code styles to your CMake build scripts.
    • Safe refactoring: The IDE's built-in refactoring tools now also check if you are renaming or deleting files that you reference in your CMake build scripts.

    When using the Project window in previous versions of Android Studio, you could navigate and inspect only the header files that belong to libraries you build from a local project. With this release, you can now also view and inspect header files included with external C/C++ library dependencies that you import into your app project.

    If you already include C/C++ code and libraries in your project , open the Project window on the left side of the IDE by selecting View > Tool Windows > Project from the main menu and select Android from the drop-down menu. In the cpp directory, all headers that are within the scope of your app project are organized under the include node for each of your local C/C++ library dependencies, as shown below.

    Native multidex enabled by default

    Previous versions of Android Studio enabled native multidex when deploying the debug version of an app to a device running Android API level 21 or higher. Now, whether you're deploying to a device or building an APK for release, the Android plugin for Gradle enables native multidex for all modules that set minSdkVersion=21 or higher.

    AAPT2 moved to Google's Maven repository

    Beginning with Android Studio 3.2, the source for AAPT2 (Android Asset Packaging Tool 2) is Google's Maven repository.

    To use AAPT2, make sure that you have a google() dependency in your build.gradle file, as shown here:

        buildscript {
            repositories {
                google() // here
                jcenter()
            }
            dependencies {
                classpath 'com.android.tools.build:gradle:3.2.0'
            }
        }
        allprojects {
            repositories {
                google() // and here
                jcenter()
            }
        }
        
        buildscript {
            repositories {
                google() // here
                jcenter()
            }
            dependencies {
                classpath("com.android.tools.build:gradle:3.2.0")
            }
        }
        allprojects {
            repositories {
                google() // and here
                jcenter()
            }
        }
        

    The new version of AAPT2 fixes many issues, including improved handling of non-ASCII characters on Windows.

    Removal of configuration on demand

    The Configure on demand preference has been removed from Android Studio.

    Android Studio no longer passes the --configure-on-demand argument to Gradle.

    ADB Connection Assistant

    The new ADB Connection Assistant provides step-by-step instructions to help you set up and use a device over the Android Debug Bridge (ADB) connection.

    To start the assistant, choose Tools > Connection Assistant .

    The ADB Connection Assistant provides instructions, in-context controls, and a list of connected devices in a series of pages in the Assistant panel.

    Emulator improvements

    You can now save and load snapshots of an AVD (Android virtual device) at any time in the Android Emulator, making it fast and easy to return an emulated device to a known state for testing. When you edit an AVD using the AVD Manager, you can specify which AVD snapshot to load when the AVD starts.

    Controls for saving, loading, and managing AVD snapshots are now in the Snapshots tab in the emulator's Extended controls window.

    For details, see Snapshots .

    For additional information on what's new and changed in the Emulator, see the Emulator release notes .

    3.1 (March 2018)

    Android Studio 3.1.0 is a major release that includes a variety of new features and improvements.

    3.1.4 (August 2018)

    This update to Android Studio 3.1 includes the following changes and fixes:

    • The bundled Kotlin is now version 1.2.50.
    • New projects are created with kotlin-stdlib-jdk* artifacts , rather than with kotlin-stdlib-jre* artifacts, which are deprecated.
    • R8 parsing of ProGuard rules has been improved.
    • The following bugs have been fixed:
      • Attempting to run the Kotlin Main class failed with an error: "Error: Could not find or load main class..."
      • R8 entered an infinite loop while performing certain optimizations.
      • Using the Rerun failed tests command in the Run window sometimes incorrectly returned the message "No tests were found".
      • D8 did not correctly handle invoke-virtual instances, causing a crash with a VerifyError : invoke-super/virtual can't be used on private method
      • The Data Binding compiler was depending on an old version of com.android.tools:annotations . The compiler now uses tools annotations from the base project when available.
      • Android Studio crashed during fragment transitions when using profilers.
      • The debugger crashed when debugging a layout with a text box.
      • D8 failed to read some ZIP files with special characters.

    3.1.3 (June 2018)

    This update to Android Studio 3.1 includes fixes for the following bugs:

    • Memory leaks caused Android Studio to become slow and unresponsive after you had been using the Layout Editor. This update includes fixes for most of these issues. We intend to release another update soon to address additional memory leaks.
    • Some applications built with D8 crashed on some Verizon Ellipsis tablets.
    • Installation of applications built with D8 failed with an INSTALL_FAILED_DEXOPT error on devices running Android 5.0 or 5.1 (API level 21 or 22).
    • Some applications that used the OkHttp library and were built with D8 crashed on devices running Android 4.4 (API level 19).
    • Android Studio sometimes failed to start, with a ProcessCanceledException during class initialization for com.intellij.psi.jsp.JspElementType .

    3.1.2 (April 2018)

    This update to Android Studio 3.1 includes fixes for the following bugs:

    • In some cases, Android Studio hung indefinitely during exit.
    • Builds configured with source sets failed with the following message when Instant Run was enabled:

      "The SourceSet name is not recognized by the Android Gradle Plugin."

    • When Instant Run was enabled, builds of new Kotlin projects failed when triggered by the Run command.
    • During editing of the build.gradle file, there was sometimes a noticeable delay between typing a character and the character appearing on the screen.
    • Build failures occurred during dexing in some projects with large numbers of modules or external dependencies, with the following error message:

      "RejectedExecutionException: Thread limit exceeded replacing blocked worker"

    • The computation of the D8 main DEX list was not taking into account some reflective invocations.

    This update also includes changes that make running lint checks from Gradle much faster in some scenarios.

    3.1.1 (April 2018)

    This update to Android Studio 3.1 includes fixes for the following bugs:

    • In some cases, when a project created in Android Studio 3.0 was opened for the first time in Android Studio 3.1, the Gradle-aware Make task was removed from the Before launch area in Run/Debug Configurations . The result was that projects did not build when the Run or Debug button was clicked, which in turn caused failures such as deployment of incorrect APKs and crashes when using Instant Run.

      To solve this problem, Android Studio 3.1.1 adds the Gradle-aware Make task to the run configuration for projects that are missing this entry. This modification occurs after the first Gradle sync when the project is loaded.

    • The debugger crashed when debugging a layout with a text box if advanced profiling was enabled.
    • Android Studio froze after you clicked Build Variants .
    • AAR (Android archive) files were extracted twice, once during the Gradle sync process and once during the Gradle build process.
    • Elements were missing from some vector drawables imported from SVG files.
    • The warning regarding the deprecation of the compile dependency configuration has been updated with better guidance regarding the implementation and api configurations. For details of migrating away from using the compile configuration, see the documentation for the new dependency configurations .

    Coding/IDE

    IntelliJ 2017.3.3

    The core Android Studio IDE has been updated with improvements from IntelliJ IDEA through the 2017.3.3 release. Improvements include better control flow analysis for collections and strings, improved nullability inference, new quick fixes, and much more.

    For details, see the JetBrains release notes for IntelliJ IDEA versions 2017.2 and 2017.3 , as well as the JetBrains release notes for bug-fix updates .

    SQL editing improvements with Room

    When you use the Room database library , you can take advantage of several improvements to SQL editing:

    • Code completion within a Query understands SQL tables (entities), columns, query parameters, aliases, joins, subqueries, and WITH clauses.
    • SQL syntax highlighting now works.
    • You can right-click a table name in SQL and rename it, which also rewrites the corresponding Java or Kotlin code (including, for example, the return type of the query). Renaming works in the other direction, too, so renaming a Java class or field rewrites the corresponding SQL code.
    • SQL usages are shown when using Find usages (right-click and choose Find usages from the context menu).
    • To navigate to an SQL entity's declaration in Java or Kotlin code, you can hold Control (Command on Mac) while clicking the entity.

    For information on using SQL with Room, see Save data in a local database using Room .

    Updates to data binding

    This update includes several improvements for data binding :

    • You can now use a LiveData object as an observable field in data binding expressions. The ViewDataBinding class now includes a new setLifecycle() method that you use to observe LiveData objects.

    • The ObservableField class can now accept other Observable objects in its constructor.

    • You can preview a new incremental compiler for your data binding classes. For details of this new compiler and instructions for enabling it, see Data Binding Compiler V2 .

      Benefits of the new compiler include the following:

      • ViewBinding classes are generated by the Android Plugin for Gradle before the Java compiler.
      • Libraries keep their generated binding classes when the app is compiled, rather than being regenerated each time. This can greatly improve performance for multi-module projects.

    Compiler and Gradle

    D8 is the default DEX compiler

    The D8 compiler is now used by default for generating DEX bytecode.

    This new DEX compiler brings with it several benefits, including the following:

    • Faster dexing
    • Lower memory usage
    • Improved code generation (better register allocation, smarter string tables)
    • Better debugging experience when stepping through code

    You don't need to make any changes to your code or your development workflow to get these benefits, unless you had previously manually disabled the D8 compiler.

    If you set android.enableD8 to false in your gradle.properties , either delete that flag or set it to true :

            android.enableD8=true
          

    For details, see New DEX compiler .

    Incremental desugaring

    For projects that use Java 8 language features , incremental desugaring is enabled by default, which can improve build times.

    Desugaring converts syntactic sugar into a form that the compiler can process more efficiently.

    You can disable incremental desugaring by specifying the following in your project's gradle.properties file:

            android.enableIncrementalDesugaring=false
          
    Simplified output window

    The Gradle Console has been replaced with the Build window, which has Sync and Build tabs.

    For details about how to use the new, simplified Build window, see Monitor the build process .

    Batch updates and indexing concurrency

    The Gradle sync and IDE indexing processes are now much more efficient, reducing time wasted on many redundant indexing operations.

    C++ and LLDB

    We have made many quality and performance improvements in the coding, syncing, building, and debugging phases of C++ development. Improvements include the following:

    • If you work with large C++ projects, you should notice a significant improvement in the reduction of time spent building symbols. Sync time is also greatly reduced for large projects.

    • Performance when building and syncing with CMake has been improved through more aggressive reuse of cached results.

    • The addition of formatters ("pretty printers") for more C++ data structures makes LLDB output easier to read.

    • LLDB now works with only Android 4.1 (API level 16) and higher.

    Note: Native debugging with Android Studio 3.0 or greater does not work on 32-bit Windows. If you are using 32-bit Windows and need to debug native code, use Android Studio 2.3.

    Котлин

    Kotlin upgraded to version 1.2.30

    Android Studio 3.1 includes Kotlin version 1.2.30 .

    Kotlin code now analyzed with command-line lint check

    Running lint from the command line now analyzes your Kotlin classes.

    For each project that you would like to run lint on, Google's Maven repository must be included in the top-level build.gradle file. The Maven repository is already included for projects created in Android Studio 3.0 and higher.

    Performance tools

    Sample native C++ processes with CPU Profiler

    The CPU Profiler now includes a default configuration to record sampled traces of your app's native threads. You can use this configuration by deploying your app to a device running Android 8.0 (API level 26) or higher and then selecting Sampled (Native) from the CPU Profiler's recording configurations dropdown menu. After that, record and inspect a trace as you normally would.

    You can change default settings, such as the sampling interval, by creating a recording configuration .

    To switch back to tracing your Java threads, select either a Sampled (Java) or Instrumented (Java) configuration.

    Filter CPU traces, memory allocation results, and heap dumps

    The CPU Profiler and Memory Profiler include a search feature that allows you to filter results from recording a method trace, memory allocations, or heap dump.

    To search, click Filterin the top-right corner of the pane, type your query, and press Enter.

    Tip: You can also open the search field by pressing Control + F (Command + F on Mac).

    In the CPU Profiler's Flame Chart tab, call stacks that include methods related to your search query are highlighted and moved to the left side of the chart.

    For more information on filtering by method, class, or package name, see Record and inspect method traces .

    Request tab in the Network Profiler

    The Network Profiler now includes a Request tab that provides details about network requests during the selected timeline. In previous versions, the Network Profiler only provided information about network responses.

    Thread View in the Network Profiler

    After selecting a portion of the timeline in the Network Profiler , you can select one of the following tabs to see more detail about the network activity during that timeframe:

    • Connection View : Provides the same information as previous versions of Android Studio—it lists files that were sent or received during the selected portion of the timeline across all of your app's CPU threads. For each request, you can inspect the size, type, status, and transmission duration.
    • Thread View : Displays network activity of each of your app's CPU threads. This view allows you to inspect which of your app's threads are responsible for each network request.

    Layout Inspector

    The Layout Inspector gained new features, including some functionality previously provided by the deprecated Hierarchy Viewer and Pixel Perfect tools:

    • Zoom buttons and keyboard shortcuts for navigating and inspecting layouts
    • Reference grid overlay
    • Ability to load a reference image and use it as an overlay (useful for comparing your layout with a UI mockup)
    • Render subtree preview to isolate a view in a complex layout

    Layout Editor

    The Palette in the Layout Editor has received many improvements:

    • Reorganization of categories for views and layouts.
    • New Common category for views and layouts, which you can add to with a Favorite command.
    • Improved search for views and layouts .
    • New commands for opening documentation for a specific view or layout element.

    You can use the new Convert view command in the Component tree or design editor to convert a view or layout to another type of view or layout.

    You can now easily create constraints to items near the selected view using the new Create a connection buttons in the view inspector at the top of the Attributes window.

    Run and Instant Run

    The behavior of the Use same selection for future launches option in the Select deployment target dialog has been made more consistent. If the Use same selection option is enabled, then the Select deployment target dialog opens only the first time that you use the Run command until the selected device is no longer connected.

    When targeting a device running Android 8.0 (API level 26) or higher, Instant Run can deploy changes to resources without causing an application restart. This is possible because the resources are contained in a split APK.

    Эмулятор

    For details of what's new and changed in the emulator since Android Studio 3.0, see the Android Emulator release notes from version 27.0.2 through version 27.1.12 .

    Major improvements include the following:

    • Quick Boot snapshots for saving of emulator state and faster start, with the ability to use the Save now command to save a custom start state.
    • Windowless emulator screen.
    • System images for Android 8.0 (API level 26), Android 8.1 (API level 27), and Android P Developer Preview.

    User interface and user experience improvements

    More tooltips, keyboard shortcuts, and helpful messages

    We have added tooltips and helpful message overlays in many places throughout Android Studio.

    To see keyboard shortcuts for many commands, just hold the mouse pointer over a button until the tooltip appears.

    Tools > Android menu removed

    The Tools > Android menu has been removed. Commands that were previously under this menu have been moved.

    • Many commands moved to directly under the Tools menu.
    • The Sync project with gradle files command moved to the File menu.
    • The Device Monitor command has been removed, as described below.

    Device Monitor available from the command line

    In Android Studio 3.1, the Device Monitor serves less of a role than it previously did. In many cases, the functionality available through the Device Monitor is now provided by new and improved tools.

    See the Device Monitor documentation for instructions for invoking the Device Monitor from the command line and for details of the tools available through the Device Monitor.

    3.0 (October 2017)

    Android Studio 3.0.0 is a major release that includes a variety of new features and improvements.

    macOS users: If you are updating an older version of Android Studio, you may encounter an update error dialog that says "Some conflicts were found in the installation area". Simply ignore this error and click Cancel to resume the installation.

    3.0.1 (ноябрь 2017 г.)

    This is a minor update to Android Studio 3.0 that includes general bug fixes and performance improvements.

    Android Plugin for Gradle 3.0.0

    The new Android plugin for Gradle includes a variety of improvements and new features, but it primarily improves build performance for projects that have a large number of modules. When using the new plugin with these large projects, you should experience the following:

    • Faster build configuration times due to new delayed dependency resolution.
    • Variant-aware dependency resolution for only the projects and variants you are building.
    • Faster incremental build times when applying simple changes to code or resources.

    Note: These improvements required significant changes that break some of the plugin's behaviors, DSL, and APIs. Upgrading to version 3.0.0 might require changes to your build files and Gradle plugins.

    This version also includes the following:

    • Support for Android 8.0.
    • Support for building separate APKs based on language resources.
    • Support for Java 8 libraries and Java 8 language features (without the Jack compiler).
    • Support for Android Test Support Library 1.0 (Android Test Utility and Android Test Orchestrator ).
    • Improved ndk-build and cmake build speeds.
    • Improved Gradle sync speed.
    • AAPT2 is now enabled by default.
    • Using ndkCompile is now more restricted. Вместо этого вам следует перейти на использование CMake или ndk-build для компиляции собственного кода, который вы хотите упаковать в свой APK. Чтобы узнать больше, прочтите «Миграция с ndkcompile» .

    For more information about what's changed, see the Android Plugin for Gradle release notes .

    If you're ready to upgrade to the new plugin, see Migrate to Android Plugin for Gradle 3.0.0 .

    Kotlin support

    As announced at Google I/O 2017 , the Kotlin programming language is now officially supported on Android. So with this release, Android Studio includes Kotlin language support for Android development.

    You can incorporate Kotlin into your project by converting a Java file to Kotlin (click Code > Convert Java File to Kotlin File ) or by creating a new Kotlin- enabled project using the New Project wizard.

    To get started, read how to add Kotlin to your project .

    Java 8 language features support

    You can now use certain Java 8 language features and consume libraries built with Java 8. Jack is no longer required , and you should first disable Jack to use the improved Java 8 support built into the default toolchain.

    To update your project to support the new Java 8 language toolchain, update the Source Compatibility and Target Compatibility to 1.8 in the Project Structure dialog (click File > Project Structure ). To learn more, read how to use Java 8 language features .

    Android Profiler

    The new Android Profiler replaces the Android Monitor tool and provides a new suite of tools to measure your app's CPU, memory, and network usage in realtime. You can perform sample-based method tracing to time your code execution, capture heap dumps, view memory allocations, and inspect the details of network-transmitted files.

    To open, click View > Tool Windows > Android Profiler (or click Android Profiler in the toolbar).

    The event timeline at the top of the window shows touch events, key presses, and activity changes so you have more context to understand other performance events in the timeline.

    Note: The Logcat view also moved to a separate window (it was previously inside Android Monitor, which was removed).

    From the Android Profiler's overview timeline, click on the CPU , MEMORY , or NETWORK timelines to access the corresponding profiler tools.

    CPU Profiler

    The CPU Profiler helps you analyze the CPU thread usage of your app by triggering a sample or instrumented CPU trace. Then, you can troubleshoot CPU performance issues using a variety of data views and filters.

    For more information, see the CPU Profiler guide .

    Memory Profiler

    The Memory Profiler helps you identify memory leaks and memory churn that can lead to stutter, freezes, and even app crashes. It shows a realtime graph of your app's memory use, lets you capture a heap dump, force garbage collections, and track memory allocations.

    For more information, see the Memory Profiler guide .

    Network Profiler

    The Network Profiler allows you to monitor the network activity of your app, inspect the payload of each of your network requests, and link back to the code that generated the network request.

    For more information, see the Network Profiler guide .

    APK profiling and debugging

    Android Studio now allows you to profile and debug any APK without having to build it from an Android Studio project—as long as the APK is built to enable debugging and you have access to the debug symbols and source files.

    To get started, click Profile or debug APK from the Android Studio Welcome screen. Or, if you already have a project open, click File > Profile or debug APK from the menu bar. This displays the unpacked APK files, but it does not decompile the code. So, to properly add breakpoints and view stack traces, you need to attach Java source files and native debug symbols.

    For more information, see Profile and Debug Pre-built APKs .

    Device File Explorer

    The new Device File Explorer allows you to inspect your connected device's filesystem, and transfer files between the device and your computer. This replaces the filesystem tool available in DDMS.

    To open, click View > Tool Windows > Device File Explorer .

    For more information, see the Device File Explorer guide .

    Instant Apps support

    New support for Android Instant Apps allows you to create Instant Apps in your project using two new module types : Instant App modules and Feature modules (these require that you install the Instant Apps Development SDK ).

    Android Studio also includes a new modularize refactoring action to help you add support for Instant Apps in an existing project. For example, if you want to refactor your project to place some classes in an Instant App feature module, select the classes in the Project window and click Refactor > Modularize . In the dialog that appears, select the module where the classes should go and click OK .

    And when you're ready to test your Instant App, you can build and run your Instant App module on a connected device by specifying the Instant App's URL within the run configuration launch options : Select Run > Edit Configurations , select your Instant App module, and then set the URL under Launch Options .

    For more information, see Android Instant Apps .

    Android Things modules

    New Android Things templates in the New Project and New Module wizards to help you start developing for Android-powered IOT devices.

    For more information, see how to create an Android Things project .

    Adaptive Icons wizard

    Image Asset Studio now supports vector drawables and allows you to create adaptive launcher icons for Android 8.0 while simultaneously creating traditional icons ("Legacy" icons) for older devices.

    To start, right-click on the res folder in your project, and then click New > Image Asset . In the Asset Studio window, select Launcher Icons (Adaptive and Legacy) as the icon type.

    Note: You must set compileSdkVersion to 26 or higher to use adaptive launcher icons.

    For more information, read about Adaptive Icons .

    Support for font resources

    To support the new font resources in Android 8.0, Android Studio includes a font resources selector to help bundle fonts into your app or configure your project to download the fonts on the device (when available). The layout editor can also preview the fonts in your layout.

    To try downloadable fonts, ensure that your device or emulator is running Google Play Services v11.2.63 or higher. For more information, read about Downloadable Fonts .

    Firebase App Indexing Assistant

    The Firebase Assistant has been updated with a new tutorial to test App Indexing . To open the Assistant, select Tools > Firebase . Then select App Indexing > Test App Indexing .

    The tutorial includes new buttons to test your public and personal content indexing:

    • In step 2, click Preview search results to verify that your URLs are showing up in Google Search results.
    • In step 3, click Check for errors to verify that the indexable objects in your app have been added to the personal content index.

    The App Links Assistant has been updated with the following new capabilities:

    • Add URL tests for each URL mapping to be sure your intent filters handle real-world URLs.

      You can also define these URL tests by hand using the <tools:validation> tag described below.

    • Create a Digital Asset Links file with the appropriate object entry to support Google Smart Lock , and add the corresponding asset_statements <meta-data> tag to your manifest file.

    URL intent-filter validator

    Android Studio now supports a special tag in the manifest file that allows you to test your intent filter URLs . These are the same tags that the App Links Assistant can create for you .

    To declare a test URL for an intent filter, add a <tools:validation> element alongside the corresponding <intent-filter> element. Например:

          <activity ...>
              <intent-filter>
                  ...
              </intent-filter>
              <tools:validation testUrl="https://www.example.com/recipe/1138" />
          </activity>
        
        

    Be sure to also include xmlns:tools="http://schemas.android.com/tools" in the <manifest> tag.

    If any one of the test URLs does not pass the intent filter definition, a lint error appears. Such an error still allows you to build debug variants, but it will break your release builds.

    Layout Editor

    The Layout Editor has been updated with a number of enhancements, including the following:

    • New toolbar layout and icons.
    • Updated layout in the component tree.
    • Improved drag-and-drop view insertions.
    • New error panel below the editor, showing all issues with suggestions to fix (if available).
    • Various UI enhancements for building with ConstraintLayout , including the following:
      • New support to create barriers .
      • New support to create groups: In the toolbar, select Guidelines > Add Group (requires ConstraintLayout 1.1.0 beta 2 or higher)
      • New UI to create chains: Select multiple views, and then right-click and select Chain .

    Layout Inspector

    The Layout Inspector includes enhancements to make it easier to debug issues with your app layouts, including grouping properties into common categories and new search functionality in both the View Tree and the Properties panes.

    APK Analyzer

    You can now use the APK Analyzer from the command line with the apkanalyzer tool.

    The APK Analyzer has also been updated with the following improvements:

    • For APKs built with ProGuard, you can load ProGuard mapping files that add capabilities to the DEX viewer, including:
      • Bolded nodes to indicate that the nodes should not be removed when shrinking code.
      • A button to show nodes that were removed during the shrinking process.
      • A button that restores the original names of nodes in the tree view that were obfuscated by ProGuard.
    • The DEX Viewer now shows the estimated size impact of each package, class and method.
    • New filtering options at the top to show and hide fields and methods.
    • In the tree view, nodes that are references not defined in the DEX file appear in italics.

    For more information, see Analyze Your Build with APK Analyzer .

    Preview for D8 DEX compiler

    Android Studio 3.0 includes an optional new DEX compiler called D8. It will eventually replace the DX compiler, but you can opt-in to use the new D8 compiler now.

    DEX compilation directly impacts your app's build time, .dex file size, and runtime performance. And when comparing the new D8 compiler with the current DX compiler, D8 compiles faster and outputs smaller .dex files, while having the same or better app runtime performance.

    To try it, set the following in your project's gradle.properties file:

    android.enableD8=true
        

    For more information, see the blog post about the D8 compiler .

    Google's Maven repository

    Android Studio now uses Google's Maven Repository by default instead of depending on the Android SDK Manager to get updates for Android Support Library, Google Play Services, Firebase, and other dependencies. This makes it easier to keep your libraries up to date, especially when using a continuous integration (CI) system.

    All new projects now include the Google Maven repository by default. To update your existing project, add google() in the repositories block of the top-level build.gradle file:

          allprojects {
              repositories {
                  google()
              }
          }
        
        

    Learn more about Google's Maven repository here .

    Другие изменения

    • Native debugging with Android Studio no longer supports 32-bit Windows. We've chosen to focus on other platforms because very few developers are using this platform. If you are using 32-bit Windows and you plan to debug native code, you should keep using Android Studio 2.3 .
    • Upgraded the base IDE to IntelliJ 2017.1.2 , which adds a number of new features from 2016.3 and 2017.1 , such as Java 8 language refactoring, parameter hints, semantic highlighting, draggable breakpoints, instant results in search, and much more.
    • Added many new lint checks.
    • Also see the latest Android Emulator updates .

    2.3 (March 2017)

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

    2.3.3 (June 2017)

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

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

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

    <h3 class="hide-from-toc">
      New
    </h3>
    
    <div class="video-wrapper-left">
      <iframe class="devsite-embedded-youtube-video" data-video-id="VFyKclKBGf0"
              data-autohide="1" data-showinfo="0" frameborder="0" allowfullscreen>
      </iframe>
    </div>
    
    <ul>
      <li>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
        <a href="/studio/write/convert-webp.html">Convert images to WebP in Android
        Studio</a>.
      </li>
    
      <li>The new <a href="/studio/write/app-link-indexing.html">App Links
      Assistant</a> 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.
      </li>
    
      <li>The Layout Editor now includes support for two new ConstraintLayout
      features:
        <ul>
          <li>Define a view size based on an aspect ratio.
          </li>
          <li>Create packed, spread, and weighted linear groups with constraint
          chains.
          </li>
        </ul>
        For more information, see <a href=
        "/training/constraint-layout/index.html">Build a Responsive UI with
        ConstraintLayout</a>.
      </li>
    
      <li>The Layout Editor also now lets you create a list of <a href=
      "/studio/write/layout-editor.html#edit-properties">favorite attributes</a> so
      you don't have to click <b>View all attributes</b> to access the attributes
      you use most.
      </li>
    
      <li>When adding a material icon using the Vector Import Dialog (<b>File &gt;
      New &gt; Vector Asset</b>), you can now filter the list of available icons by
      category or by icon name. For more information, see <a href=
      "/studio/write/vector-asset-studio.html#materialicon">Adding a material
      icon</a>.
      </li>
    
      <li>
        <a href="/studio/write/annotations.html#accessibility">New and updated
        annotations</a>. The new <code>@RestrictTo</code> annotation for methods,
        classes, and packages lets you restrict an API. The updated
        <code>@VisibleForTesting</code> annotation now has an optional
        <code>otherwise</code> 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 <code>otherwise</code> option to enforce the intended
        visibility of the method.
      </li>
    
      <li>New <a href="/studio/write/lint.html#snapshot">lint baseline support</a>
      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.
      </li>
    
      <li>New lint checks, including the following:
        <ul>
          <li>Obsolete <code>SDK_INT</code> Checks: Android Studio removes obsolete
          code that checks for SDK versions.
          </li>
          <li>Object Animator Validation: Lint analyzes your code to make sure that
          your <code>ObjectAnimator</code> calls reference valid methods with the
          right signatures and checks that those methods are annotated with <code>
            @Keep</code> to prevent ProGuard from renaming or removing them during
            release builds.
          </li>
          <li>Unnecessary Item Decorator Copy: Older versions of the
          <code>RecyclerView</code> 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.
          </li>
          <li>WifiManager Leak: Prior to Android 7.0 (API level 24), initializing
          the <code>WifiManager</code> with <code><a href="/reference/android/content/Context.html#getSystemService(java.lang.Class&lt;T&gt;)">Context.getSystemService()</a></code>
          can cause a memory leak if the context is not the application context.
          Lint looks for these initializations, and if it <em>cannot</em> determine
          that the context is the application context, it suggests you use <code><a href="/reference/android/content/Context.html#getApplicationContext()">Context.getApplicationContext()</a></code> to get the proper context for the
          initialization.
          </li>
          <li>Improved Resource Prefix: The existing <code>resourcePrefix</code>
          lint check had many limitations. You can now configure your project with
          a prefix, such as <code>android { resourcePrefix '<var>my_lib</var>'
          }</code>, 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 <var>my_lib</var> prefix, you can have themes named
          <code>MyLibTheme</code>, <code>myLibAttr</code>,
          <code>my_lib_layout</code>, and so on.
          </li>
          <li>Switch to WebP: This check identifies images in your project that can
          be converted to WebP format based on your projects
          <code>minSdkVersion</code> setting. An associated quickfix can
          automatically convert the images, or you can <a href=
          "/studio/write/convert-webp.html">convert images to WebP</a> manually.
          </li>
          <li>Unsafe WebP: If your project already includes WebP images, this check
          analyzes your project to ensure that your <code>minSdkVersion</code>
          setting is high enough to support the included images. For more
          information about WebP support in Android and Android Studio, see
          <a class="external" href=
          "https://developers.google.com/speed/webp/faq#which_web_browsers_natively_support_webp">
            Which browsers natively support WebP?</a> and <a href=
            "/studio/write/convert-webp.html">Create WebP Images Using Android
            Studio</a>.
          </li>
        </ul>
      </li>
    </ul>
    
    <h3 class="hide-from-toc">
      Changes
    </h3>
    
    <ul>
      <li>A separate button to push changes with Instant Run: After deploying your
      app, you now click <b>Apply Changes</b> <img src=
      "/studio/images/buttons/toolbar-apply-changes.svg" alt="" class=
      "inline-icon"> to quickly push incremental changes to your running app using
      Instant Run. The <b>Run</b> <img src="/studio/images/buttons/toolbar-run.png"
        alt="" class="inline-icon"> and <b>Debug</b> <img src=
        "/studio/images/buttons/toolbar-debug.png" alt="" class="inline-icon">
        buttons are always available to you when you want to reliably push your
        changes and force an app restart.
        <ul>
          <li>Instant Run is supported only when deploying your app to a target
          device running Android 5.0 (API level 21) or higher.
          </li>
          <li>Instant Run is no longer disabled for projects that <a href=
          "/studio/projects/add-native-code.html">link to external native
          projects</a> using CMake or ndk-build. However, you can only use Instant
          Run to push incremental changes to your Java code, not your native code.
          </li>
          <li>Cold swaps (which you can force for a running app by clicking
          <strong>Run</strong> <img src="/studio/images/buttons/toolbar-run.png"
          alt="" class="inline-icon">) 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.
          </li>
          <li>Includes optimizations that make app startup much faster. These
          optimizations may affect profiling, so you should temporarily <a href=
          "/studio/run/index.html#disable-ir">disable Instant Run</a> whenever
          profiling your app.
          </li>
        </ul>
      </li>
    
      <li>
        <p>
          The <b>AVD Manager</b> <img src=
          "/studio/images/buttons/toolbar-avd-manager.png" alt="" class=
          "inline-icon"> and <b>SDK Manager</b> <img src=
          "/studio/images/buttons/toolbar-sdk-manager.png" alt="" class=
          "inline-icon"> buttons are now included in the lean Navigation Bar as
          well as the full Toolbar. To use the lean Navigation Bar, click
          <b>View</b> to open the View menu, then ensure that <b>Navigation Bar</b>
          is selected and <b>Toolbar</b> is <em>not</em> selected.
        </p>
        <img src="/studio/images/releases/navigationbar_sdkavd_2x.png" width="757">
      </li>
    
      <li>The "Hybrid" debugger has been renamed to "Dual" debugger.
      </li>
    
      <li>In the <a href="/studio/run/rundebugconfig.html">Run/Debug
      Configurations</a> dialog, under Defaults in the left pane, the following run
      configuration names have changed with no behavior changes:
        <ul>
          <li>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.
          </li>
          <li>The Android Tests name has changed to Android Instrumented Tests.
          </li>
        </ul>
      </li>
    
      <li>The <a href="/studio/debug/am-gpu-debugger.html">GPU Debugger</a> has
      been removed from Android Studio as of version 2.3. An open-source,
      standalone version of the tool is now available on <a href=
      "https://github.com/google/gapid" class="external-link">GitHub</a>.
      </li>
    
      <li>The Run/Debug option is no longer available when you right-click a <code>
        *.gradle build</code> script.
      </li>
    
      <li>All templates now use <code>ConstraintLayout</code> as the default
      layout.
      </li>
    
      <li>The Widgets palette in the Layout Editor has been redesigned.
      </li>
    </ul>
    
    <p>
      This release also includes a number of bug fixes. <a href=
      "https://code.google.com/p/android/issues/list?can=1&amp;q=target%3D2.3+status%3DReleased&amp;colspec=ID+Status+Priority+Owner+Summary+Stars+Reporter+Opened&amp;cells=tiles">
      See all bug fixes in 2.3.0.</a>
    </p>
    
    <p class="note">
      <b>Known issue:</b> 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:
      <code>Error: Not found; no service started</code>. To avoid this issue,
      either <a href="/studio/run/emulator.html">use the emulator</a> or enable
      automatic launching for your app in your device's settings. The procedure
      for doing this is different for each device, so check the instructions
      provided by the manufacturer. To learn more about this issue, see
      <a href="https://code.google.com/p/android/issues/detail?id=235879">Issue
        #235879</a>.
    </p>
    

    2.2 (September 2016)

    2.2.3 (December 2016)

    <p>
      This is a minor update to Android Studio 2.2. It includes a bug fixes
      focused around gradle, the core IDE, and lint.
    </p>
    
    <p>
      Highlighted build changes:
    </p>
    
    <ul>
      <li>ProGuard version rollback. Due to a <a href=
      "https://sourceforge.net/p/proguard/bugs/625/">correctness issue</a>
      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.
      </li>
      <li>Bug fix for <code>aaptOptions</code> <code>IgnoreAssetsPattern</code>
      not working properly (<a href="http://b.android.com/224167">issue
      224167</a>)
      </li>
      <li>Bug fix for Gradle autodownload for Constraint Layout library
        (<a href="https://code.google.com/p/android/issues/detail?id=212128">issue
        212128</a>)
      </li>
      <li>Bug fix for a JDK8/Kotlin compiler + dx issue (<a href=
      "http://b.android.com/227729">issue 227729</a>)
      </li>
    </ul>
    
    <p>
      <a href=
      "https://code.google.com/p/android/issues/list?can=1&amp;q=target%3D2.2.3+status%3AReleased+&amp;colspec=ID+Status+Priority+Owner+Summary+Stars+Reporter+Opened&amp;cells=tiles">
      See all bug fixes in 2.2.3</a>.
    </p>
    

    2.2.2 (October 2016)

    <p>
      This is a minor update to Android Studio 2.2. It includes a number of small
      changes and bug fixes, including:
    </p>
    
    <ul>
      <li>When reporting Instant Run issues through the IDE, the report now also
      includes logcat output for <code>InstantRun</code> events. To help us
      improve Instant Run, please <a href=
      "/studio/run/index.html#submit-feedback">enable extra logging and report
      any issues</a>.
      </li>
      <li>A number of small bug fixes for Gradle.
      </li>
      <li>A fix for problems with generating multiple APKs.
      </li>
    </ul>
    

    2.2.1 (October 2016)

    <p>
      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 <a href=
      "/studio/run/index.html#submit-feedback">enable extra logging and report
      any issues</a>.
    </p>
    

    Новый

    • All new Layout Editor with tools custom-built to support ConstraintLayout .
    • <li>New <strong><a href=
      "http://tools.android.com/tech-docs/layout-inspector">Layout
      Inspector</a></strong> lets you examine snapshots of your layout hierarchy
      while your app is running on the emulator or a device.
      </li>
      
      <li>New <strong><a href="/studio/write/firebase.html">Assistant</a></strong>
      window to help you integrate Firebase services into your app.
      </li>
      
      <li>New <strong><a href="/studio/debug/apk-analyzer.html">APK
      Analyzer</a></strong> tool so you can inspect the contents of your packaged
      app.
      </li>
      
      <li>New <strong><a href=
      "http://tools.android.com/tech-docs/test-recorder">Espresso Test
      Recorder</a></strong> tool (currently in beta) to help you create UI tests by
      recording your own interactions.
      </li>
      
      <li>New <strong><a href=
      "http://tools.android.com/tech-docs/build-cache">build cache</a></strong>
      (currently experimental) to speed up build performance.
      </li>
      
      <li>New <strong>C/C++ build integration with CMake and ndk-build</strong>.
      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 <a href=
      "/studio/projects/add-native-code.html">Add C and C++ Code to Your
      Project</a>. To learn how to debug native code with lldb, see <a href=
      "/studio/debug/index.html#debug-native">Debug Native Code</a>.
      </li>
      
      <li>New <strong><a href="/studio/intro/index.html#sample-code">Samples
      Browser</a></strong> so you can easily look up Google Android sample code
      from within Android Studio to jump start app development.
      </li>
      
      <li>New <strong>Merged Manifest Viewer</strong> to help you diagnose how your
      manifest file merges with your app dependencies across project build
      variants.
      </li>
      
      <li>The <strong>Run</strong> window now contains log messages for the current
      running app. Note that you can configure the <a href=
      "/studio/debug/am-logcat.html">logcat Monitor</a> display, but not the
      <strong>Run</strong> window.
      </li>
      
      <li>New <strong><a href="/studio/run/emulator.html">Android
      Emulator</a></strong> features:
        <ul>
          <li>Added new <strong>Virtual</strong> <strong>Sensors</strong> and
          <strong>Cellular</strong> &gt; <strong>Signal Strength</strong> controls.
          </li>
          <li>Added an <strong>LTE</strong> option to the <strong>Cellular</strong>
          &gt; <strong>Network type</strong> control.
          </li>
          <li>Added simulated vertical swipes for scrolling through vertical menus
          with a mouse wheel.
          </li>
        </ul>
      </li>
      
      <li>New <strong><a href="/studio/run/rundebugconfig.html">Run/Debug
      Configuration</a></strong> features:
        <ul>
          <li>The <strong>Debugger</strong> tab of the Android App and Android
          Tests templates now contain several new options for debugging with LLDB.
          </li>
          <li>The <strong>Profiling</strong> tab of the Android App and Android
          Tests templates now contain a <strong>Capture GPU Commands</strong>
          option for enabling GPU tracing. You can display GPU traces in the GPU
          Debugger (a beta feature).
          </li>
          <li>The Android Tests template now has a <strong>Firebase Test Lab Device
          Matrix</strong> option for the <strong>Deployment Target</strong>.
          </li>
          <li>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.
          </li>
          <li>The Android Application template has been renamed to Android App.
          </li>
        </ul>
      </li>
      
      <li>Improved installation, configuration, performance, and UI features in the
      <strong><a href="/studio/debug/am-gpu-debugger.html">GPU
      Debugger</a></strong> (currently in beta).
      </li>
      
      <li>Android Studio now comes bundled with <strong>OpenJDK 8</strong>.
      Existing projects still use the JDK specified in <strong>File &gt; Project
      Structure &gt; SDK Location</strong>. You can switch to use the new bundled
      JDK by clicking <strong>File &gt; Project Structure &gt; SDK
      Location</strong> and checking the <strong>Use embedded JDK</strong>
      checkbox.
      </li>
      
      <li>Added new <strong>help menus and buttons</strong> in the UI so you can
      more easily find the online documentation.
      </li>
      

    Изменения

    • 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 )
    • <li>Improved performance for <strong>Gradle sync</strong> within the IDE,
      especially for large projects.
      </li>
      
      <li>Improved build times for both full and incremental builds with new app
      packaging code.
      </li>
      
      <li>Improved <strong>Jack compiler performance and features</strong>,
      including support for annotation processors and dexing in process. To learn
      more, read the <a href=
      "/studio/releases/gradle-plugin.html#revisions">Android plugin for Gradle
      2.2.0 release notes</a>.
      </li>
      
      <li>Removed the <strong>Scale</strong> AVD property from the AVD Manager.
      </li>
      
      <li>The Android Emulator <strong>-port</strong> and <strong>-ports</strong>
      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.
      </li>
      
      <li>Improved the <strong><a href=
      "/studio/write/create-java-class.html">Create New Class dialog</a></strong>
      and the corresponding file templates. <strong>Note:</strong> If you've
      previously customized the <strong>AnnotationType</strong>,
      <strong>Class</strong>, <strong>Enum</strong>, <strong>Interface</strong>, or
      <strong>Singleton</strong> file templates, you need to modify your templates
      to comply with the new templates or you wont be able to use the new fields
      in the <strong>Create New Class</strong> dialog.
      </li>
      
      <li>Improved the <strong><a href=
      "/studio/write/vector-asset-studio.html">Vector Asset Studio</a></strong>
      user interface and added support for Adobe Photoshop Document (PSD) files.
      </li>
      
      <li>Improved the <strong><a href=
      "/studio/write/image-asset-studio.html">Image Asset Studio</a></strong> user
      interface.
      </li>
      
      <li>Improved the <strong>Theme Editor</strong>'s Resource Picker.
      </li>
      
      <li>Fixed memory leaks and reduced overall memory usage in Android Studio.
      </li>
      
      <li>Added a <strong>Background</strong> button in the <strong><a href=
      "/studio/intro/update.html#sdk-manager">SDK Manager</a></strong> so you can
      get back to work and install your packages in the background.
      </li>
      
      <li>Improved <strong><a href="/studio/intro/accessibility.html">Accessibility
      features</a></strong>, including support for screen readers and keyboard
      navigation.
      </li>
      
      <li>Enhanced <strong>Code Analysis</strong> includes code quality checks for
      Java 8 language usage and more cross-file analysis.
      </li>
      
      <li>Several toolbar icons have changed.
      </li>
      

    2.1 (April 2016)

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

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

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

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

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

    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. Это настройка по умолчанию.
    • 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.

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

    Fixes and enhancements:

    • Updated the Android runtime window to include the Memory Monitor tool and added a tab for CPU performance monitoring.
    • Added a Captures tab in the left margin to display the captured memory and CPU performance data files, such as CPU method tracking and memory heap snapshots.
    • Expanded annotation support with additional metadata annotations and inferred nullability.
    • Enhanced the Translations Editor with additional support for Best Current Practice (BCP) 47, which uses 3-letter language and region codes.
    • Integrated IntelliJ 14 and 14.1 features for improved code analysis and performance:
      • Enhanced debugging to show inline values for variables and referring objects, as well as perform inline evaluation of lambda and operator expressions.
      • Added code style detection for tab and indent sizes.
      • Added scratch files for code experiments and prototyping without project files.
      • Added the simultaneous insertion of opening and closing tags in HTML and XML files.
      • Added a built-in Java class decompiler so you can look at what's inside a library for which the source code is not available.

      See What's New in IntelliJ for a complete description of the new features and enhancements.

    • Added additional Project Views for Scratches , Project Files , Problems , Production , and Tests to enhance project management and access.
    • Enhanced the File > Settings menu and dialogs for improved settings access and management.
    • Added support for high-density displays for Windows and Linux.
    • Added support for 280 dpi resources in the res/drawable-280dpi/ folder.

    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 (eg 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.

    Older releases of Android Gradle Plugin

    3.6.0 (February 2020)

    Для этой версии плагина Android требуется следующее:

    3.6.4 (July 2020)

    This minor update supports compatibility with new default settings and features for package visibility in Android 11 .

    See the 4.0.1 release notes for details.

    Новые возможности

    This version of the Android Gradle plugin includes the following new features.

    View Binding

    View binding provides compile-time safety when referencing views in your code. You can now replace findViewById() with the auto-generated binding class reference. To start using View binding, include the following in each module's build.gradle file:

          android {
              viewBinding.enabled = true
          }
          
          android {
              viewBinding.enabled = true
          }
          

    To learn more, read the View Binding documentation .

    Support for the Maven Publish plugin

    The Android Gradle plugin includes support for the Maven Publish Gradle plugin , which allows you to publish build artifacts to an Apache Maven repository. The Android Gradle plugin creates a component for each build variant artifact in your app or library module that you can use to customize a publication to a Maven repository.

    To learn more, go to the page about how to use the Maven Publish plugin .

    New default packaging tool

    When building the debug version of your app, the plugin uses a new packaging tool, called zipflinger , to build your APK. This new tool should provide build speed improvements. If the new packaging tool doesn't work as you expect, please report a bug . You can revert to using the old packaging tool by including the following in your gradle.properties file:

            android.useNewApkCreator=false
          
    Native build attribution

    You can now determine the length of time it takes Clang to build and link each C/C++ file in your project. Gradle can output a Chrome trace that contains timestamps for these compiler events so you can better understand the time required to build your project. To output this build attribution file, do the following:

    1. Add the flag -Pandroid.enableProfileJson=true when running a Gradle build. Например:

      gradlew assembleDebug -Pandroid.enableProfileJson=true

    2. Open the Chrome browser and type chrome://tracing in the search bar.

    3. Click the Load button and navigate to <var>project-root</var>/build/android-profile to find the file. The file is named profile-<var>timestamp</var>.json.gz .

    You can see the native build attribution data near the top of the viewer:

    Native build attribution trace in Chrome

    Изменения в поведении

    When using this version of the plugin, you might encounter the following changes in behavior.

    Native libraries packaged uncompressed by default

    When you build your app, the plugin now sets extractNativeLibs to "false" by default. That is, your native libraries are page aligned and packaged uncompressed. While this results in a larger upload size, your users benefit from the following:

    • Smaller app install size because the platform can access the native libraries directly from the installed APK, without creating a copy of the libraries.
    • Smaller download size because Play Store compression is typically better when you include uncompressed native libraries in your APK or Android App Bundle.

    If you want the Android Gradle plugin to instead package compressed native libraries, include the following in your app's manifest:

            <application
              android:extractNativeLibs="true"
              ... >
            </application>
            
          

    Note: The extractNativeLibs manifest attribute has been replaced by the useLegacyPackaging DSL option. For more information, see the release note Use the DSL to package compressed native libraries .

    Default NDK version

    If you download multiple versions of the NDK, the Android Gradle plugin now selects a default version to use in compiling your source code files. Previously, the plugin selected the latest downloaded version of the NDK. Use the android.ndkVersion property in the module's build.gradle file to override the plugin-selected default.

    Simplified R class generation

    The Android Gradle plugin simplifies the compile classpath by generating only one R class for each library module in your project and sharing those R classes with other module dependencies. This optimization should result in faster builds, but it requires that you keep the following in mind:

    • Because the compiler shares R classes with upstream module dependencies, it's important that each module in your project uses a unique package name.
    • The visibility of a library's R class to other project dependencies is determined by the configuration used to include the library as a dependency. For example, if Library A includes Library B as an 'api' dependency, Library A and other libraries that depend on Library A have access to Library B's R class. However, other libraries might not have access to Library B's R class. If Library A uses the implementation dependency configuration. To learn more, read about dependency configurations .
    Remove resources missing from default configuration

    For Library modules, if you include a resource for a language that you do not include in the default set of resources—for example, if you include hello_world as a string resource in /values-es/strings.xml but you don't define that resource in /values/strings.xml —the Android Gradle plugin no longer includes that resource when compiling your project. This behavior change should result in fewer Resource Not Found runtime exceptions and improved build speed.

    D8 now respects CLASS retention policy for annotations

    When compiling your app, D8 now respects when annotations apply a CLASS retention policy, and those annotations are no longer available at runtime. This behavior also exists when setting the app's target SDK to API level 23, which previously allowed access to these annotations during runtime when compiling your app using older versions of the Android Gradle plugin and D8.

    Other behavior changes
    • aaptOptions.noCompress is no longer case sensitive on all platforms (for both APK and bundles) and respects paths that use uppercase characters.
    • Data binding is now incremental by default. To learn more, see issue #110061530 .

    • All unit tests, including Roboelectric unit tests, are now fully cacheable. To learn more, see issue #115873047 .

    Исправления ошибок

    This version of the Android Gradle plugin includes the following bug fixes:

    • Robolectric unit tests are now supported in library modules that use data binding. To learn more, see issue #126775542 .
    • You can now run connectedAndroidTest tasks across multiple modules while Gradle's parallel execution mode is enabled.

    Известные проблемы

    This section describes known issues that exist in Android Gradle plugin 3.6.0.

    Slow performance of Android Lint task

    Android Lint can take much longer to complete on some projects due to a regression in its parsing infrastructure, resulting in slower computation of inferred types for lambdas in certain code constructs.

    The issue is reported as a bug in IDEA and will be fixed in Android Gradle Plugin 4.0.

    Missing Manifest class {:#agp-missing-manifest}

    If your app defines custom permissions in its manifest, the Android Gradle plugin typically generates a Manifest.java class that includes your custom permissions as string constants. The plugin packages this class with your app, so you can more easily reference those permissions at runtime.

    Generating the manifest class is broken in Android Gradle plugin 3.6.0. If you build your app with this version of the plugin, and it references the manifest class, you might see a ClassNotFoundException exception. To resolve this issue, do one of the following:

    • Reference your custom permissions by their fully-qualified name. For example, "com.example.myapp.permission.DEADLY_ACTIVITY" .

    • Define your own constants, as shown below:

                  public final class CustomPermissions {
                    public static final class permission {
                      public static final String DEADLY_ACTIVITY="com.example.myapp.permission.DEADLY_ACTIVITY";
                    }
                  }
                  
                

    3.5.0 (August 2019)

    Android Gradle plugin 3.5.0, along with Android Studio 3.5 , is a major release and a result of Project Marble, which is a focus on improving three main areas of the Android developer tools: system health, feature polish, and fixing bugs. Notably, improving project build speed was a main focus for this update.

    For information about these and other Project Marble updates, read the Android Developers blog post or the sections below.

    Для этой версии плагина Android требуется следующее:

    3.5.4 (July 2020)

    This minor update supports compatibility with new default settings and features for package visibility in Android 11 .

    See the 4.0.1 release notes for details.

    3.5.3 (December 2019)

    This minor update supports Android Studio 3.5.3 and includes various bug fixes and performance improvements.

    3.5.2 (November 2019)

    This minor update supports Android Studio 3.5.2 and includes various bug fixes and performance improvements. To see a list of noteable bug fixes, read the related post on the Release Updates blog .

    3.5.1 (October 2019)

    This minor update supports Android Studio 3.5.1 and includes various bug fixes and performance improvements. To see a list of noteable bug fixes, read the related post on the Release Updates blog .

    Incremental annotation processing

    The Data Binding annotation processor supports incremental annotation processing if you set android.databinding.incremental=true in your gradle.properties file. This optimization results in improved incremental build performance. For a full list of optimized annotation processors, refer to the table of incremental annotation processors .

    Additionally, KAPT 1.3.30 and higher also support incremental annotation processors, which you can enable by including kapt.incremental.apt=true in your gradle.properties file.

    Cacheable unit tests

    When you enable unit tests to use Android resources, assets, and manifests by setting includeAndroidResources to true , the Android Gradle plugin generates a test config file containing absolute paths, which breaks cache relocatability. You can instruct the plugin to instead generate the test config using relative paths, which allows the AndroidUnitTest task to be fully cacheable, by including the following in your gradle.properties file:

          android.testConfig.useRelativePath = true
        

    Известные проблемы

    • When using Kotlin Gradle plugin 1.3.31 or earlier, you might see the following warning when building or syncing your project:

                WARNING: API 'variant.getPackageLibrary()' is obsolete and has been replaced
                        with 'variant.getPackageLibraryProvider()'.
                
              

      To resolve this issue , upgrade the plugin to version 1.3.40 or higher.

    3.4.0 (April 2019)

    Для этой версии плагина Android требуется следующее:

    3.4.3 (July 2020)

    This minor update supports compatibility with new default settings and features for package visibility in Android 11 .

    See the 4.0.1 release notes for details.

    3.4.2 (July 2019)

    This minor update supports Android Studio 3.4.2 and includes various bug fixes and performance improvements. To see a list of noteable bug fixes, read the related post on the Release Updates blog .

    3.4.1 (May 2019)

    This minor update supports Android Studio 3.4.1 and includes various bug fixes and performance improvements. To see a list of noteable bug fixes, read the related post on the Release Updates blog .

    Новые возможности

    • New lint check dependency configurations: The behavior of lintChecks has changed and a new dependency configuration, lintPublish , has been introduced to give you more control over which lint checks are packaged in your Android libraries.

      • lintChecks : This is an existing configuration that you should use for lint checks you want to only run when building your project locally. If you were previously using the lintChecks dependency configuration to include lint checks in the published AAR, you need to migrate those dependencies to instead use the new lintPublish configuration described below.
      • lintPublish : Use this new configuration in library projects for lint checks you want to include in the published AAR, as shown below. This means that projects that consume your library also apply those lint checks.

      The following code sample uses both dependency configurations in a local Android library project.

      dependencies {
        // Executes lint checks from the ':lint' project at build time.
        lintChecks project(':lint')
        // Packages lint checks from the ':lintpublish' in the published AAR.
        lintPublish project(':lintpublish')
      }
              
      dependencies {
        // Executes lint checks from the ':lint' project at build time.
        lintChecks(project(":lint"))
        // Packages lint checks from the ':lintpublish' in the published AAR.
        lintPublish(project(":lintpublish"))
          }
              
      • In general, packaging and signing tasks should see an overall build speed improvement. If you notice a performance regression related to these tasks, please report a bug .

    Изменения в поведении

    • Android Instant Apps Feature plugin deprecation warning: If you're still using the com.android.feature plugin to build your instant app, Android Gradle plugin 3.4.0 will give throw you a deprecation warning. To make sure you can still build you instant app on future versions of the plugin, migrate your instant app to using the dynamic feature plugin , which also allows you to publish both your installed and instant app experiences from a single Android App Bundle.

    • R8 enabled by default: R8 integrates desugaring, shrinking, obfuscating, optimizing, and dexing all in one step—resulting in noticeable build performance improvements . R8 was introduced in Android Gradle plugin 3.3.0 and is now enabled by default for both app and Android library projects using plugin 3.4.0 and higher.

    The image below provides a high-level overview of the compile process before R8 was introduced.

    Before R8, ProGuard was a different compile step from dexing and
              desugaring.

    Now, with R8, desugaring, shrinking, obfuscating, optimizing, and dexing (D8) are all completed in one step, as illustrated below.

    With R8, desugaring, shrinking, obfuscating, optimizing, and
      dexing are all performed in a single compile step.

    Keep in mind, R8 is designed to work with your existing ProGuard rules, so you'll likely not need to take any actions to benefit from R8. However, because it's a different technology to ProGuard that's designed specifically for Android projects, shrinking and optimization may result in removing code that ProGuard may have not. So, in this unlikely situation, you might need to add additional rules to keep that code in your build output.

    If you experience issues using R8, read the R8 compatibility FAQ to check if there's a solution to your issue. If a solution isn't documented, please report a bug . You can disable R8 by adding one of the following lines to your project's gradle.properties file:

          # Disables R8 for Android Library modules only.
          android.enableR8.libraries = false
          # Disables R8 for all modules.
          android.enableR8 = false
          
        

    Note: For a given build type, if you set useProguard to false in your app module's build.gradle file, the Android Gradle plugin uses R8 to shrink your app's code for that build type, regardless of whether you disable R8 in your project's gradle.properties file.

    • ndkCompile is deprecated: You now get a build error if you try to use ndkBuild to compile your native libraries. You should instead use either CMake or ndk-build to Add C and C++ code to your project .

    Известные проблемы

    • The correct usage of unique package names are currently not enforced but will become more strict on later versions of the plugin. On Android Gradle plugin version 3.4.0, you can opt-in to check whether your project declares acceptable package names by adding the line below to your gradle.properties file.

                android.uniquePackageNames = true
                
              

      To learn more about setting a package name through the Android Gradle plugin, see Set the application ID .

    3.3.0 (January 2019)

    Для этой версии плагина Android требуется следующее:

    3.3.3 (July 2020)

    This minor update supports compatibility with new default settings and features for package visibility in Android 11 .

    See the 4.0.1 release notes for details.

    3.3.2 (March 2019)

    This minor update supports Android Studio 3.3.2 and includes various bug fixes and performance improvements. To see a list of noteable bug fixes, read the related post on the Release Updates blog .

    3.3.1 (February 2019)

    This minor update supports Android Studio 3.3.1 and includes various bug fixes and performance improvements.

    Новые возможности

    • Improved classpath synchronization: When resolving dependencies on your runtime and compile time classpaths, the Android Gradle plugin attempts to fix certain downstream version conflicts for dependencies that appear across multiple classpaths.

      For example, if the runtime classpath includes Library A version 2.0 and the compile classpath includes Library A version 1.0, the plugin automatically updates the dependency on the compile classpath to Library A version 2.0 to avoid errors.

      However, if the runtime classpath includes Library A version 1.0 and the compile includes Library A version 2.0, the plugin does not downgrade the dependency on the compile classpath to Library A version 1.0, and you will get an error. To learn more, see Fix conflicts between classpaths .

    • Improved incremental Java compilation when using annotation processors: This update decreases build time by improving support for incremental Java compilation when using annotation processors.

      Note: This feature is compatible with Gradle 4.10.1 and higher, except Gradle 5.1 due to Gradle issue 8194 .

      • For projects using Kapt (most Kotlin-only projects and Kotlin-Java hybrid projects): Incremental Java compilation is enabled, even when you use data binding or the retro-lambda plugin. Annotation processing by the Kapt task is not yet incremental.

      • For projects not using Kapt (Java-only projects): If the annotation processors you use all support incremental annotation processing , incremental Java compilation is enabled by default. To monitor incremental annotation processor adoption, watch Gradle issue 5277 .

        If, however, one or more annotation processors do not support incremental builds, incremental Java compilation is not enabled. Instead, you can include the following flag in your gradle.properties file:

        android.enableSeparateAnnotationProcessing=true
                    

        When you include this flag, the Android Gradle plugin executes the annotation processors in a separate task and allows the Java compilation task to run incrementally.

    • Better debug info when using obsolete API: When the plugin detects that you're using an API that's no longer supported, it can now provide more-detailed information to help you determine where that API is being used. To see the additional info, you need to include the following in your project's gradle.properties file:

                android.debug.obsoleteApi=true
              

      You can also enable the flag by passing -Pandroid.debug.obsoleteApi=true from the command line.

    • You can run instrumentation tests on feature modules from the command line.

    Изменения в поведении

    • Lazy task configuration: The plugin now uses Gradle's new task creation API to avoid initializing and configuring tasks that are not required to complete the current build (or tasks not on the execution task graph). For example, if you have multiple build variants, such as “release” and “debug” build variants, and you're building the “debug” version of your app, the plugin avoids initializing and configuring tasks for the “release” version of your app.

      Calling certain older methods in the Variants API, such as variant.getJavaCompile() , might still force task configuration. To make sure that your build is optimized for lazy task configuration, invoke new methods that instead return a TaskProvider object, such as variant.getJavaCompileProvider() .

      If you execute custom build tasks, learn how to adapt to Gradle's new task-creation API .

    • For a given build type, when setting useProguard false , the plugin now uses R8 instead of ProGuard to shrink and obfuscate your app's code and resources. To learn more about R8, read this blog post from the Android Developer's Blog.

    • Faster R class generation for library projects: Previously, the Android Gradle plugin would generate an R.java file for each of your project's dependencies and then compile those R classes alongside your app's other classes. The plugin now generates a JAR containing your app's compiled R class directly, without first building intermediate R.java classes. This optimization may significantly improve build performance for projects that include many library subprojects and dependencies, and improve the indexing speed in Android Studio.

    • When building an Android App Bundle , APKs generated from that app bundle that target Android 6.0 (API level 23) or higher now include uncompressed versions of your native libraries by default. This optimization avoids the need for the device to make a copy of the library and thus reduces the on-disk size of your app. If you'd rather disable this optimization, add the following to your gradle.properties file:

      android.bundle.enableUncompressedNativeLibs = false
              
    • The plugin enforces minimum versions of some third-party plugins.

    • Single-variant project sync : Syncing your project with your build configuration is an important step in letting Android Studio understand how your project is structured. However, this process can be time-consuming for large projects. If your project uses multiple build variants, you can now optimize project syncs by limiting them to only the variant you have currently selected.

      You need to use Android Studio 3.3 or higher with Android Gradle Plugin 3.3.0 or higher to enable this optimization. When you meet these requirements, the IDE prompts you to enable this optimization when you sync your project. The optimization is also enabled by default on new projects.

      To enable this optimization manually, click File > Settings > Experimental > Gradle ( Android Studio > Preferences > Experimental > Gradle on a Mac) and select the Only sync the active variant checkbox.

      Note : This optimization fully supports projects that include Java and C++ languages, and has some support for Kotlin. When enabling the optimization for projects with Kotlin content, Gradle sync falls back to using full variants internally.

    • Automatic downloading of missing SDK packages : This functionality has been expanded to support NDK. To learn more, read Auto-download missing packages with Gradle .

    Исправления ошибок

    • Android Gradle plugin 3.3.0 fixes the following issues:

      • The build process calling android.support.v8.renderscript.RenderScript instead of the AndroidX version, despite Jetifier being enabled
      • Clashes due to androidx-rs.jar including statically bundled annotation.AnyRes
      • When using RenderScript, you no longer have to manually set the Build Tools version in your build.gradle files

    3.2.0 (September 2018)

    Для этой версии плагина Android требуется следующее:

    3.2.1 (October 2018)

    With this update, you no longer need to specify a version for the SDK Build Tools. The Android Gradle plugin now uses version 28.0.3 by default.

    Новые возможности

    • Support for building Android App Bundles: The app bundle is a new upload format that includes all your app's compiled code and resources while deferring APK generation and signing to the Google Play Store. You no longer have to build, sign, and manage multiple APKs, and users get smaller downloads that are optimized for their device. To learn more, read About Android App Bundles .

    • Support for improved incremental build speeds when using annotation processors: The AnnotationProcessorOptions DSL now extends CommandLineArgumentProvider , which enables either you or the annotation processor author to annotate arguments for the processor using incremental build property type annotations . Using these annotations improves the correctness and performance of incremental and cached clean builds. To learn more, read Pass arguments to annotation processors .

    • Migration tool for AndroidX: When using Android Gradle plugin 3.2.0 with Android 3.2 and higher, you can migrate your project's local and Maven dependencies to use the new AndroidX libraries by selecting Refactor > Migrate to AndroidX from the menu bar. Using this migration tool also sets the following flags to true in your gradle.properties file:

      • android.useAndroidX : When set to true , the Android plugin uses the appropriate AndroidX library instead of a Support Library. When this flag is not specified, the plugin sets it to false by default.

      • android.enableJetifier : When set to true , the Android plugin automatically migrates existing third-party libraries to use AndroidX by rewriting their binaries. When this flag is not specified, the plugin sets it to false by default. You can set this flag to true only while android.useAndroidX is also set to true , otherwise you get a build error.

        To learn more, read the AndroidX overview .

    • New code shrinker, R8: R8 is a new tool for code shrinking and obfuscation that replaces ProGuard. You can start using the preview version of R8 by including the following in your project's gradle.properties file:

              android.enableR8 = true
              
              android.enableR8 = true
              

    Изменения в поведении

    • Desugaring with D8 is now enabled by default.

    • AAPT2 is now on Google's Maven repo. To use AAPT2, make sure that you have the google() dependency in your build.gradle file, as shown below:

                buildscript {
                      repositories {
                          google() // here
                          jcenter()
                      }
                      dependencies {
                          classpath 'com.android.tools.build:gradle:3.2.0'
                      }
                  }
                  allprojects {
                      repositories {
                          google() // and here
                          jcenter()
                  }
                
                buildscript {
                      repositories {
                          google() // here
                          jcenter()
                      }
                      dependencies {
                          classpath 'com.android.tools.build:gradle:3.2.0'
                      }
                  }
                  allprojects {
                      repositories {
                          google() // and here
                          jcenter()
                  }
                
    • Native multidex is now enabled by default. Previous versions of Android Studio enabled native multidex when deploying the debug version of an app to a device running Android API level 21 or higher. Now, whether you're deploying to a device or building an APK for release, the Android Gradle plugin enables native multidex for all modules that set minSdkVersion=21 or higher.

    • The plugin now enforces a minimum version of the protobuf plugin (0.8.6), Kotlin plugin (1.2.50), and Crashlytics plugin (1.25.4).

    • The feature module plugin, com.android.feature , now enforces the use of only letters, digits, and underscores when specifying a module name. For example, if your feature module name includes dashes, you get a build error. This behavior matches that of the dynamic feature plugin.

    Исправления ошибок

    3.1.0 (March 2018)

    Для этой версии плагина Android требуется следующее:

    • Gradle 4.4 or higher.

      Чтобы узнать больше, прочитайте раздел об обновлении Gradle .

    • Build Tools 27.0.3 or higher.

      Keep in mind, you no longer need to specify a version for the build tools using the android.buildToolsVersion property—the plugin uses the minimum required version by default.

    New DEX compiler, D8

    By default, Android Studio now uses a new DEX compiler called D8. DEX compilation is the process of transforming .class bytecode into .dex bytecode for the Android Runtime (or Dalvik, for older versions of Android). Compared to the previous compiler, called DX, D8 compiles faster and outputs smaller DEX files, all while having the same or better app runtime performance.

    D8 shouldn't change your day-to-day app development workflow. However, if you experience any issues related to the new compiler, please report a bug . You can temporarily disable D8 and use DX by including the following in your project's gradle.properties file:

          android.enableD8=false
        

    For projects that use Java 8 language features , incremental desugaring is enabled by default. You can disable it by specifying the following in your project's gradle.properties file:

          android.enableIncrementalDesugaring=false.
        

    Preview users: If you're already using a preview version of D8, note that it now compiles against libraries included in the SDK build tools —not the JDK. So, if you are accessing APIs that exist in the JDK but not in the SDK build tools libraries, you get a compile error.

    Изменения в поведении

    • When building multiple APKs that each target a different ABI, the no longer generates APKs for the following ABIs by default: mips , mips64 , and armeabi .

      If you want to build APKs that target these ABIs, you must use NDK r16b or lower and specify the ABIs in your build.gradle file, as shown below:

                splits {
                    abi {
                        include 'armeabi', 'mips', 'mips64'
                        ...
                    }
                }
              
                splits {
                    abi {
                        include("armeabi", "mips", "mips64")
                        ...
                    }
                }
              
    • The Android plugin's build cache now evicts cache entries that are older than 30 days.

    • Passing "auto" to resConfig no longer automatically picks string resources to package into your APK. If you continue to use "auto" , the plugin packages all string resources your app and its dependencies provide. So, you should instead specify each locale that you want the plugin to package into your APK.

    • Because local modules can't depend on your app's test APK, adding dependencies to your instrumented tests using the androidTestApi configuration, instead of androidTestImplementation , causes Gradle to issue the following warning:

              WARNING: Configuration 'androidTestApi' is obsolete
              and has been replaced with 'androidTestImplementation'
              
              WARNING: Configuration 'androidTestApi' is obsolete
              and has been replaced with 'androidTestImplementation'
              

    Исправления

    • Fixes an issue where Android Studio doesn't properly recognize dependencies in composite builds.
    • Fixes an issue where you get a project sync error when loading the Android plugin multiple times in a single build–for example, when multiple subprojects each include the Android plugin in their buildscript classpath.

    3.0.0 (October 2017)

    Плагин Android Gradle 3.0.0 включает в себя множество изменений, направленных на решение проблем с производительностью крупных проектов.

    Например, в примере скелетного проекта с примерно 130 модулями и большим количеством внешних зависимостей (но без кода и ресурсов) вы можете получить повышение производительности, подобное следующему:

    Версия плагина Android + версия Gradle Плагин Android 2.2.0 + Gradle 2.14.1 Плагин Android 2.3.0 + Gradle 3.3 Плагин Android 3.0.0 + Gradle 4.1
    Конфигурация (например, запуск ./gradlew --help ) ~2 минуты ~9 с ~2,5 с
    Изменение Java в 1 строку (изменение реализации) ~2 минуты 15 с ~29 с ~6,4 с

    Some of these changes break existing builds. So, you should consider the\ effort of migrating your project before using the new plugin.

    Если вы не заметили описанного выше улучшения производительности, сообщите об ошибке и включите трассировку своей сборки с помощью Gradle Profiler .

    Для этой версии плагина Android требуется следующее:

    • Gradle 4.1 или выше. Чтобы узнать больше, прочитайте раздел об обновлении Gradle .
    • Инструменты сборки 26.0.2 или выше. С этим обновлением вам больше не нужно указывать версию для инструментов сборки — плагин по умолчанию использует минимально необходимую версию. Итак, теперь вы можете удалить свойство android.buildToolsVersion .

    3.0.1 (ноябрь 2017 г.)

    Это небольшое обновление для поддержки Android Studio 3.0.1, включающее общие исправления ошибок и улучшения производительности.

    Optimizations

    • Улучшенный параллелизм для многомодульных проектов за счет детального графа задач.
    • При внесении изменений в зависимость Gradle выполняет более быструю сборку, не перекомпилируя модули, у которых нет доступа к API этой зависимости. Вам следует ограничить, какие зависимости передают свои API другим модулям , используя новые конфигурации зависимостей Gradle : implementation , api , compileOnly и runtimeOnly .
    • Более быстрая дополнительная скорость сборки благодаря индексированию каждого класса. Каждый класс теперь компилируется в отдельные файлы DEX, и повторно индексируются только измененные классы. Также следует ожидать повышения скорости сборки для приложений, для которых minSdkVersion установлено значение 20 или ниже и которые используют устаревший multi-dex .
    • Повышена скорость сборки за счет оптимизации определенных задач для использования кэшированных выходных данных. To benefit from this optimization, you need to first enable the Gradle build cache .
    • Улучшена добавочная обработка ресурсов с использованием AAPT2, который теперь включен по умолчанию. Если у вас возникли проблемы при использовании AAPT2, сообщите об ошибке . Вы также можете отключить AAPT2, установив android.enableAapt2=false в файле gradle.properties и перезапустив демон Gradle, запустив ./gradlew --stop из командной строки.

    Новые возможности

    • Управление зависимостями с учетом вариантов . При сборке определенного варианта модуля плагин теперь автоматически сопоставляет варианты зависимостей модуля локальной библиотеки с вариантом создаваемого вами модуля.
    • Включает новый плагин функционального модуля для поддержки Android Instant Apps и Android Instant Apps SDK (который можно загрузить с помощью менеджера SDK ). Чтобы узнать больше о создании функциональных модулей с помощью нового плагина, прочтите «Структура мгновенного приложения с несколькими функциями» .
    • Встроенная поддержка использования определенных функций языка Java 8 и библиотек Java 8. Jack теперь устарел и больше не требуется , и вам следует сначала отключить Jack, чтобы использовать улучшенную поддержку Java 8, встроенную в набор инструментов по умолчанию. Дополнительные сведения см. в статье Использование функций языка Java 8 .
    • Добавлена ​​поддержка запуска тестов с помощью Android Test Orchestrator , который позволяет запускать каждый тест вашего приложения в рамках отдельного вызова Instrumentation. Поскольку каждый тест выполняется в своем собственном экземпляре инструментария, любое общее состояние между тестами не накапливается в процессоре или памяти вашего устройства. И даже если один тест выйдет из строя, он уничтожит только свой собственный экземпляр инструментария, поэтому остальные тесты продолжат работать.

      • Добавлен testOptions.execution , чтобы определить, следует ли использовать оркестрацию тестов на устройстве. Если вы хотите использовать Android Test Orchestrator , вам необходимо указать ANDROID_TEST_ORCHESTRATOR , как показано ниже. По умолчанию для этого свойства установлено значение HOST , что отключает оркестровку на устройстве и является стандартным методом запуска тестов.

      классный

              android {
                testOptions {
                  execution 'ANDROID_TEST_ORCHESTRATOR'
                }
              }
              

      Котлин

              android {
                testOptions {
                  execution = "ANDROID_TEST_ORCHESTRATOR"
                }
              }
              
    • Новая конфигурация зависимостей androidTestUtil позволяет вам установить еще один вспомогательный APK-файл для тестирования перед запуском инструментальных тестов, например Android Test Orchestrator:

      классный

              dependencies {
                androidTestUtil 'com.android.support.test:orchestrator:1.0.0'
                ...
              }
              

      Котлин

              dependencies {
                androidTestUtil("com.android.support.test:orchestrator:1.0.0")
                ...
              }
              
    • Добавлен testOptions.unitTests.includeAndroidResources для поддержки модульных тестов, требующих ресурсов Android, таких как Roboelectric . Когда вы устанавливаете для этого свойства значение true , плагин выполняет объединение ресурсов, активов и манифеста перед запуском модульных тестов. Затем ваши тесты смогут проверять com/android/tools/test_config.properties в пути к классам на наличие следующих ключей:

      • android_merged_assets : абсолютный путь к каталогу объединенных ресурсов.

        Примечание. Для модулей библиотеки объединенные ресурсы не содержат ресурсы зависимостей (см. проблему №65550419 ).

      • android_merged_manifest : абсолютный путь к объединенному файлу манифеста.

      • android_merged_resources : абсолютный путь к каталогу объединенных ресурсов, который содержит все ресурсы модуля и все его зависимости.

      • android_custom_package : имя пакета окончательного класса R. Если вы динамически изменяете идентификатор приложения, это имя пакета может не совпадать с атрибутом package в манифесте приложения.

    • Поддержка шрифтов в качестве ресурсов (это новая функция, представленная в Android 8.0 (уровень API 26) ).
    • Поддержка языковых APK-файлов с помощью Android Instant Apps SDK 1.1 и более поздних версий.
    • Теперь вы можете изменить выходной каталог для вашего внешнего собственного проекта сборки, как показано ниже:

      классный

              android {
                  ...
                  externalNativeBuild {
                      // For ndk-build, instead use the ndkBuild block.
                      cmake {
                          ...
                          // Specifies a relative path for outputs from external native
                          // builds. You can specify any path that's not a subdirectory
                          // of your project's temporary build/ directory.
                          buildStagingDirectory "./outputs/cmake"
                      }
                  }
              }
              

      Котлин

              android {
                  ...
                  externalNativeBuild {
                      // For ndk-build, instead use the ndkBuild block.
                      cmake {
                          ...
                          // Specifies a relative path for outputs from external native
                          // builds. You can specify any path that's not a subdirectory
                          // of your project's temporary build/ directory.
                          buildStagingDirectory = "./outputs/cmake"
                      }
                  }
              }
              
    • Теперь вы можете использовать CMake 3.7 или более поздней версии при создании собственных проектов из Android Studio.
    • Новая конфигурация зависимостей lintChecks позволяет создавать JAR-файлы, определяющие пользовательские правила lint, и упаковывать их в проекты AAR и APK.

      Ваши пользовательские правила проверки должны принадлежать отдельному проекту, который выводит один JAR-файл и включает только зависимости compileOnly . Другие модули приложений и библиотек могут зависеть от вашего проекта lint, используя конфигурацию lintChecks :

      классный

              dependencies {
                  // This tells the Gradle plugin to build ':lint-checks' into a lint.jar file
                  // and package it with your module. If the module is an Android library,
                  // other projects that depend on it automatically use the lint checks.
                  // If the module is an app, lint includes these rules when analyzing the app.
                  lintChecks project(':lint-checks')
              }
              

      Котлин

              dependencies {
                  // This tells the Gradle plugin to build ':lint-checks' into a lint.jar file
                  // and package it with your module. If the module is an Android library,
                  // other projects that depend on it automatically use the lint checks.
                  // If the module is an app, lint includes these rules when analyzing the app.
                  lintChecks(project(":lint-checks"))
              }
              

    Изменения в поведении

    • Плагин Android 3.0.0 удаляет некоторые API, и ваша сборка сломается, если вы их используете. Например, вы больше не можете использовать Variants API для доступа к объектам outputFile() или processManifest.manifestOutputFile() для получения файла манифеста для каждого варианта. Чтобы узнать больше, прочтите изменения API .
    • Вам больше не нужно указывать версию для инструментов сборки (поэтому теперь вы можете удалить свойство android.buildToolsVersion ). По умолчанию плагин автоматически использует минимально необходимую версию инструментов сборки для используемой вами версии плагина Android.
    • Теперь вы включаете/отключаете сжатие PNG в блоке buildTypes , как показано ниже. Обработка PNG включена по умолчанию для всех сборок, кроме отладочных, поскольку она увеличивает время сборки для проектов, включающих много файлов PNG. Таким образом, чтобы сократить время сборки для других типов сборки, вам следует либо отключить сжатие PNG, либо преобразовать изображения в WebP .

      классный

            android {
              buildTypes {
                release {
                  // Disables PNG crunching for the release build type.
                  crunchPngs false
                }
              }
            }
            

      Котлин

            android {
              buildTypes {
                release {
                  // Disables PNG crunching for the release build type.
                  isCrunchPngs = false
                }
              }
            }
            
    • Плагин Android теперь автоматически создает исполняемые объекты, которые вы настраиваете во внешних проектах CMake.
    • Теперь вам необходимо добавить процессоры аннотаций в путь к классам процессоров, используя конфигурацию зависимостей annotationProcessor .
    • Использование устаревшего ndkCompile теперь более ограничено. Вместо этого вам следует перейти на использование CMake или ndk-build для компиляции собственного кода, который вы хотите упаковать в свой APK. Чтобы узнать больше, прочтите «Миграция с ndkcompile» .

    3.0.0 (October 2017)

    Плагин Android Gradle 3.0.0 включает в себя множество изменений, направленных на решение проблем с производительностью крупных проектов.

    Например, в примере скелетного проекта с примерно 130 модулями и большим количеством внешних зависимостей (но без кода и ресурсов) вы можете получить повышение производительности, подобное следующему:

    Версия плагина Android + версия Gradle Плагин Android 2.2.0 + Gradle 2.14.1 Плагин Android 2.3.0 + Gradle 3.3 Плагин Android 3.0.0 + Gradle 4.1
    Конфигурация (например, запуск ./gradlew --help ) ~2 минуты ~9 с ~2,5 с
    Изменение Java в 1 строку (изменение реализации) ~2 минуты 15 с ~29 с ~6,4 с

    Some of these changes break existing builds. So, you should consider the\ effort of migrating your project before using the new plugin.

    Если вы не заметили описанного выше улучшения производительности, сообщите об ошибке и включите трассировку своей сборки с помощью Gradle Profiler .

    Для этой версии плагина Android требуется следующее:

    • Gradle 4.1 или выше. Чтобы узнать больше, прочитайте раздел об обновлении Gradle .
    • Инструменты сборки 26.0.2 или выше. С этим обновлением вам больше не нужно указывать версию для инструментов сборки — плагин по умолчанию использует минимально необходимую версию. Итак, теперь вы можете удалить свойство android.buildToolsVersion .

    3.0.1 (ноябрь 2017 г.)

    Это небольшое обновление для поддержки Android Studio 3.0.1, включающее общие исправления ошибок и улучшения производительности.

    Optimizations

    • Улучшенный параллелизм для многомодульных проектов за счет детального графа задач.
    • При внесении изменений в зависимость Gradle выполняет более быструю сборку, не перекомпилируя модули, у которых нет доступа к API этой зависимости. Вам следует ограничить, какие зависимости передают свои API другим модулям , используя новые конфигурации зависимостей Gradle : implementation , api , compileOnly и runtimeOnly .
    • Более быстрая дополнительная скорость сборки благодаря индексированию каждого класса. Каждый класс теперь компилируется в отдельные файлы DEX, и повторно индексируются только измененные классы. Также следует ожидать повышения скорости сборки для приложений, для которых minSdkVersion установлено значение 20 или ниже и которые используют устаревший multi-dex .
    • Повышена скорость сборки за счет оптимизации определенных задач для использования кэшированных выходных данных. To benefit from this optimization, you need to first enable the Gradle build cache .
    • Улучшена добавочная обработка ресурсов с использованием AAPT2, который теперь включен по умолчанию. Если у вас возникли проблемы при использовании AAPT2, сообщите об ошибке . Вы также можете отключить AAPT2, установив android.enableAapt2=false в файле gradle.properties и перезапустив демон Gradle, запустив ./gradlew --stop из командной строки.

    Новые возможности

    • Управление зависимостями с учетом вариантов . При сборке определенного варианта модуля плагин теперь автоматически сопоставляет варианты зависимостей модуля локальной библиотеки с вариантом создаваемого вами модуля.
    • Включает новый плагин функционального модуля для поддержки Android Instant Apps и Android Instant Apps SDK (который можно загрузить с помощью менеджера SDK ). Чтобы узнать больше о создании функциональных модулей с помощью нового плагина, прочтите «Структура мгновенного приложения с несколькими функциями» .
    • Встроенная поддержка использования определенных функций языка Java 8 и библиотек Java 8. Jack теперь устарел и больше не требуется , и вам следует сначала отключить Jack, чтобы использовать улучшенную поддержку Java 8, встроенную в набор инструментов по умолчанию. Дополнительные сведения см. в статье Использование функций языка Java 8 .
    • Добавлена ​​поддержка запуска тестов с помощью Android Test Orchestrator , который позволяет запускать каждый тест вашего приложения в рамках отдельного вызова Instrumentation. Поскольку каждый тест выполняется в своем собственном экземпляре инструментария, любое общее состояние между тестами не накапливается в процессоре или памяти вашего устройства. И даже если один тест выйдет из строя, он уничтожит только свой собственный экземпляр инструментария, поэтому остальные тесты продолжат работать.

      • Добавлен testOptions.execution , чтобы определить, следует ли использовать оркестрацию тестов на устройстве. Если вы хотите использовать Android Test Orchestrator , вам необходимо указать ANDROID_TEST_ORCHESTRATOR , как показано ниже. По умолчанию для этого свойства установлено значение HOST , что отключает оркестровку на устройстве и является стандартным методом запуска тестов.

      классный

              android {
                testOptions {
                  execution 'ANDROID_TEST_ORCHESTRATOR'
                }
              }
              

      Котлин

              android {
                testOptions {
                  execution = "ANDROID_TEST_ORCHESTRATOR"
                }
              }
              
    • Новая конфигурация зависимостей androidTestUtil позволяет вам установить еще один вспомогательный APK-файл для тестирования перед запуском инструментальных тестов, например Android Test Orchestrator:

      классный

              dependencies {
                androidTestUtil 'com.android.support.test:orchestrator:1.0.0'
                ...
              }
              

      Котлин

              dependencies {
                androidTestUtil("com.android.support.test:orchestrator:1.0.0")
                ...
              }
              
    • Добавлен testOptions.unitTests.includeAndroidResources для поддержки модульных тестов, требующих ресурсов Android, таких как Roboelectric . Когда вы устанавливаете для этого свойства значение true , плагин выполняет объединение ресурсов, активов и манифеста перед запуском модульных тестов. Затем ваши тесты смогут проверять com/android/tools/test_config.properties в пути к классам на наличие следующих ключей:

      • android_merged_assets : абсолютный путь к каталогу объединенных ресурсов.

        Примечание. Для модулей библиотеки объединенные ресурсы не содержат ресурсы зависимостей (см. проблему №65550419 ).

      • android_merged_manifest : абсолютный путь к объединенному файлу манифеста.

      • android_merged_resources : абсолютный путь к каталогу объединенных ресурсов, который содержит все ресурсы модуля и все его зависимости.

      • android_custom_package : имя пакета окончательного класса R. Если вы динамически изменяете идентификатор приложения, это имя пакета может не совпадать с атрибутом package в манифесте приложения.

    • Поддержка шрифтов в качестве ресурсов (это новая функция, представленная в Android 8.0 (уровень API 26) ).
    • Поддержка языковых APK-файлов с помощью Android Instant Apps SDK 1.1 и более поздних версий.
    • Теперь вы можете изменить выходной каталог для вашего внешнего собственного проекта сборки, как показано ниже:

      классный

              android {
                  ...
                  externalNativeBuild {
                      // For ndk-build, instead use the ndkBuild block.
                      cmake {
                          ...
                          // Specifies a relative path for outputs from external native
                          // builds. You can specify any path that's not a subdirectory
                          // of your project's temporary build/ directory.
                          buildStagingDirectory "./outputs/cmake"
                      }
                  }
              }
              

      Котлин

              android {
                  ...
                  externalNativeBuild {
                      // For ndk-build, instead use the ndkBuild block.
                      cmake {
                          ...
                          // Specifies a relative path for outputs from external native
                          // builds. You can specify any path that's not a subdirectory
                          // of your project's temporary build/ directory.
                          buildStagingDirectory = "./outputs/cmake"
                      }
                  }
              }
              
    • Теперь вы можете использовать CMake 3.7 или более поздней версии при создании собственных проектов из Android Studio.
    • Новая конфигурация зависимостей lintChecks позволяет создавать JAR-файлы, определяющие пользовательские правила lint, и упаковывать их в проекты AAR и APK.

      Ваши пользовательские правила проверки должны принадлежать отдельному проекту, который выводит один JAR-файл и включает только зависимости compileOnly . Другие модули приложений и библиотек могут зависеть от вашего проекта lint, используя конфигурацию lintChecks :

      классный

              dependencies {
                  // This tells the Gradle plugin to build ':lint-checks' into a lint.jar file
                  // and package it with your module. If the module is an Android library,
                  // other projects that depend on it automatically use the lint checks.
                  // If the module is an app, lint includes these rules when analyzing the app.
                  lintChecks project(':lint-checks')
              }
              

      Котлин

              dependencies {
                  // This tells the Gradle plugin to build ':lint-checks' into a lint.jar file
                  // and package it with your module. If the module is an Android library,
                  // other projects that depend on it automatically use the lint checks.
                  // If the module is an app, lint includes these rules when analyzing the app.
                  lintChecks(project(":lint-checks"))
              }
              

    Изменения в поведении

    • Плагин Android 3.0.0 удаляет некоторые API, и ваша сборка сломается, если вы их используете. Например, вы больше не можете использовать Variants API для доступа к объектам outputFile() или processManifest.manifestOutputFile() для получения файла манифеста для каждого варианта. Чтобы узнать больше, прочтите изменения API .
    • Вам больше не нужно указывать версию для инструментов сборки (поэтому теперь вы можете удалить свойство android.buildToolsVersion ). По умолчанию плагин автоматически использует минимально необходимую версию инструментов сборки для используемой вами версии плагина Android.
    • Теперь вы включаете/отключаете сжатие PNG в блоке buildTypes , как показано ниже. Обработка PNG включена по умолчанию для всех сборок, кроме отладочных, поскольку она увеличивает время сборки для проектов, включающих много файлов PNG. Таким образом, чтобы сократить время сборки для других типов сборки, вам следует либо отключить сжатие PNG, либо преобразовать изображения в WebP .

      классный

            android {
              buildTypes {
                release {
                  // Disables PNG crunching for the release build type.
                  crunchPngs false
                }
              }
            }
            

      Котлин

            android {
              buildTypes {
                release {
                  // Disables PNG crunching for the release build type.
                  isCrunchPngs = false
                }
              }
            }
            
    • Плагин Android теперь автоматически создает исполняемые объекты, которые вы настраиваете во внешних проектах CMake.
    • Теперь вам необходимо добавить процессоры аннотаций в путь к классам процессоров, используя конфигурацию зависимостей annotationProcessor .
    • Использование устаревшего ndkCompile теперь более ограничено. Вместо этого вам следует перейти на использование CMake или ndk-build для компиляции собственного кода, который вы хотите упаковать в свой APK. Чтобы узнать больше, прочтите «Миграция с ndkcompile» .

    2.3.0 (February 2017)

    2.3.3 (June 2017)

    This is a minor update that adds compatibility with Android Studio 2.3.3 .

    2.3.2 (May 2017)

    This is a minor update that adds compatibility with Android Studio 2.3.2 .

    2.3.1 (April 2017)

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

    Dependencies:
    Новый:
    • Uses Gradle 3.3, which includes performance improvements and new features. For more details, see the Gradle release notes .
    • Build cache : stores certain outputs that the Android plugin generates when building your project (such as unpackaged AARs and pre-dexed remote dependencies). Your clean builds are much faster while using the cache because the build system can simply reuse those cached files during subsequent builds, instead of recreating them. Projects using Android plugin 2.3.0 and higher use the build cache by default. To learn more, read Improve Build Speed with Build Cache .
      • Includes a cleanBuildCache task that clears the build cache .
      • If you are using the experimental version of build cache (included in earlier versions of the plugin), you should update your plugin to the latest version.
    Изменения:

    2.2.0 (September 2016)

    Dependencies:
    Новый:
    • Uses Gradle 2.14.1, which includes performance improvements and new features, and fixes a security vulnerability that allows local privilege escalation when using the Gradle daemon. For more details, see the Gradle release notes .
    • Using the externalNativeBuild {} DSL, Gradle now lets you link to your native sources and compile native libraries using CMake or ndk-build. After building your native libraries, Gradle packages them into your APK. To learn more about using CMake and ndk-build with Gradle, read Add C and C++ Code to Your Project .
    • When you run a build from the command line , Gradle now attempts to auto-download any missing SDK components or updates that your project depends on. To learn more, read Auto-download missing packages with Gradle .
    • A new experimental caching feature lets Gradle speed up build times by pre-dexing, storing, and reusing the pre-dexed versions of your libraries. To learn more about using this experimental feature, read the Build Cache guide.
    • Improves build performance by adopting a new default packaging pipeline which handles zipping, signing, and zipaligning in one task. You can revert to using the older packaging tools by adding android.useOldPackaging=true to your gradle.properties file. While using the new packaging tool, the zipalignDebug task is not available. However, you can create one yourself by calling the createZipAlignTask(String taskName, File inputFile, File outputFile) method.
    • APK signing now uses APK Signature Scheme v2 in addition to traditional JAR signing. All Android platforms accept the resulting APKs. Any modification to these APKs after signing invalidates their v2 signatures and prevents installation on a device. To disable this feature, add the following to your module-level build.gradle file:

      классный

      android {
        ...
        signingConfigs {
          config {
            ...
            v2SigningEnabled false
          }
        }
      }
            

      Котлин

      android {
        ...
        signingConfigs {
          create("config") {
            ...
            v2SigningEnabled = false
          }
        }
      }
            
    • For multidex builds, you can now use ProGuard rules to determine which classes Gradle should compile into your app's main DEX file. Because the Android system loads the main DEX file first when starting your app, you can prioritize certain classes at startup by compiling them into the main DEX file. After you create a ProGuard configuration file specifically for your main DEX file, pass the configuration file's path to Gradle using buildTypes.multiDexKeepProguard . Using this DSL is different from using buildTypes.proguardFiles , which provides general ProGuard rules for your app and does not specify classes for the main DEX file.
    • Adds support for the android:extractNativeLibs flag, which can reduce the size of your app when you install it on a device. When you set this flag to false in the <application> element of your app manifest, Gradle packages uncompressed and aligned versions of your native libraries with your APK. This prevents PackageManager from copying out your native libraries from the APK to the device's file system during installation and has the added benefit of making delta updates of your app smaller.
    • You can now specify versionNameSuffix and applicationIdSuffix for product flavors. ( Issue 59614 )
    Изменения:
    • getDefaultProguardFile now returns the default ProGuard files that Android plugin for Gradle provides and no longer uses the ones in the Android SDK.
    • Improved Jack compiler performance and features:
      • Jack now supports Jacoco test coverage when setting testCoverageEnabled to true .
      • Improved support for annotation processors. Annotation processors on your classpath, such as any compile dependencies, are automatically applied to your build. You can also specify an annotation processor in your build and pass arguments by using the javaCompileOptions.annotationProcessorOptions {} DSL in your module-level build.gradle file:

        классный

        android {
          ...
          defaultConfig {
            ...
            javaCompileOptions {
              annotationProcessorOptions {
                className 'com.example.MyProcessor'
                // Arguments are optional.
                arguments = [ foo : 'bar' ]
              }
            }
          }
        }
            

        Котлин

        android {
          ...
          defaultConfig {
            ...
            javaCompileOptions {
              annotationProcessorOptions {
                className = "com.example.MyProcessor"
                // Arguments are optional.
                arguments(mapOf(foo to "bar"))
              }
            }
          }
        }
            

        If you want to apply an annotation processor at compile time but not include it in your APK, use the annotationProcessor dependency scope:

        классный

        dependencies {
            compile 'com.google.dagger:dagger:2.0'
            annotationProcessor 'com.google.dagger:dagger-compiler:2.0'
           // or use buildVariantAnnotationProcessor to target a specific build variant
        }
            

        Котлин

        dependencies {
            implementation("com.google.dagger:dagger:2.0")
            annotationProcessor("com.google.dagger:dagger-compiler:2.0")
           // or use buildVariantAnnotationProcessor to target a specific build variant
        }
            
      • For a list of parameters you can set, run the following from the command line:

        java -jar /build-tools/jack.jar --help-properties
        
      • By default, if the Gradle daemon's heap size is at least 1.5 GB, Jack now runs in the same process as Gradle. To adjust the daemon heap size, add the following to your gradle.properties file:
        # This sets the daemon heap size to 1.5GB.
        org.gradle.jvmargs=-Xmx1536M
        

    2.1.0 (April 2016)

    2.1.3 (August 2016)

    This update requires Gradle 2.14.1 and higher. Gradle 2.14.1 includes performance improvements, new features, and an important security fix . For more details, see the Gradle release notes .

    Dependencies:
    Новый:
    • Added support for the N Developer Preview, JDK 8, and Java 8 language features using the Jack toolchain. To find out more, read the N Preview guide .

      Note: Instant Run does not currently work with Jack and will be disabled while using the new toolchain. You only need to use Jack if you are developing for the N Preview and want to use the supported Java 8 language features.

    • Added default support for incremental Java compilation to reduce compilation time during development. It does this by only recompiling portions of the source that have changed or need to be recompiled. To disable this feature, add the following code to your module-level build.gradle file:

      классный

      android {
        ...
        compileOptions {
          incremental false
        }
      }

      Котлин

      android {
        ...
        compileOptions {
          incremental = false
        }
      }
    • Added support for dexing-in-process which performs dexing within the build process rather than in a separate, external VM processes. This not only makes incremental builds faster, but also speeds up full builds. The feature is enabled by default for projects that have set the Gradle daemon's maximum heap size to at least 2048 MB. You can do this by including the following in your project's gradle.properties file:

      ```none org.gradle.jvmargs = -Xmx2048m ```

      If you have defined a value for javaMaxHeapSize in your module-level build.gradle file, you need to set org.gradle.jvmargs to the value of javaMaxHeapSize + 1024 MB. For example, if you have set javaMaxHeapSize to "2048m", you need to add the following to your project's gradle.properties file:

      ```none org.gradle.jvmargs = -Xmx3072m ```

      To disable dexing-in-process, add the following code to your module-level build.gradle file:

      классный

      android {
        ...
        dexOptions {
            dexInProcess false
        }
      }

      Котлин

      android {
        ...
        dexOptions {
            dexInProcess = false
        }
      }

    2.0.0 (April 2016)

    Dependencies:
    Новый:
    • Enables Instant Run by supporting bytecode injection, and pushing code and resource updates to a running app on the emulator or a physical device.
    • Added support for incremental builds, even when the app isn't running. Full build times are improved by pushing incremental changes through the Android Debug Bridge to the connected device.
    • Added maxProcessCount to control how many worker dex processes can be spawned concurrently. The following code, in the module-level build.gradle file, sets the maximum number of concurrent processes to 4:

      классный

      android {
        ...
        dexOptions {
          maxProcessCount = 4 // this is the default value
        }
      }

      Котлин

      android {
        ...
        dexOptions {
          maxProcessCount = 4 // this is the default value
        }
      }
        </li>
      
        <li>Added an experimental code shrinker to support pre-dexing and reduce re-dexing
        of dependencies, which are not supported with Proguard. This improves the build
        speed of your debug build variant. Because the experimental shrinker does not
        support optimization and obfuscation, you should enable Proguard for your
        release builds. To enable the experimental shrinker for your debug builds, add
        the following to your module-level <code>build.gradle</code> file:
      

      классный

      android {
        ...
        buildTypes {
          debug {
            minifyEnabled true
            useProguard false
          }
          release {
            minifyEnabled true
            useProguard true // this is a default setting
          }
        }
      }

      Котлин

      android {
        ...
        buildTypes {
          getByName("debug") {
            minifyEnabled = true
            useProguard = false
          }
          getByName("release") {
            minifyEnabled = true
            useProguard = true // this is a default setting
          }
        }
      }
        </li>
      
        <li>Added logging support and improved performance for the resource shrinker.
        The resource shrinker now logs all of its operations into a <code>resources.txt</code>
        file located in the same folder as the Proguard log files.
        </li>
      </ul>
      

    Changed behavior:
    • When minSdkVersion is set to 18 or higher, APK signing uses SHA256.
    •   <li>DSA and ECDSA keys can now sign APK packages.
      
          <p class="note">
            <strong>Note:</strong> The <a href=
            "/training/articles/keystore.html">Android keystore</a> provider no
            longer supports <a href=
            "/about/versions/marshmallow/android-6.0-changes.html#behavior-keystore">
            DSA keys on Android 6.0</a> (API level 23) and higher.
          </p>
      
        </li>
      </ul>
      

    Fixed issues:
    • Fixed an issue that caused duplicate AAR dependencies in both the test and main build configurations.

    Android plugin for Gradle, revision 1.5.0 (November 2015)

    Dependencies:
    • Gradle 2.2.1 or higher.
    • Build Tools 21.1.1 or higher.
    General Notes:
    • Integrated the Data Binding plugin into the Android plugin for Gradle. To enable it, add the following code to each per-project build.gradle file that uses the plugin:
    • android {
          dataBinding {
              enabled = true
          }
      }
              
      android {
          dataBinding {
              enabled = true
          }
      }
              
    • Added a new Transform API to allow third-party plugins to manipulate compiled .class files before they're converted to .dex files. The Transform API simplifies injecting custom class manipulations while offering more flexibility regarding what you can manipulate. To insert a transform into a build, create a new class implementing one of the Transform interfaces, and register it with android.registerTransform(theTransform) or android.registerTransform(theTransform, dependencies) . There's no need to wire tasks together. Note the following about the Transform API:
      • A transform can apply to one or more of the following: the current project, subprojects, and external libraries.
      • A transform must be registered globally, which applies them to all variants.
      • Internal code processing, through the Java Code Coverage Library (JaCoCo), ProGuard, and MultiDex, now uses the Transform API. However, the Java Android Compiler Kit (Jack) doesn't use this API: only the javac/dx code path does.
      • Gradle executes the transforms in this order: JaCoCo, third-party plugins, ProGuard. The execution order for third-party plugins matches the order in which the transforms are added by the third party plugins; third-party plugin developers can't control the execution order of the transforms through an API.
    • Deprecated the dex getter from the ApplicationVariant class. You can't access the Dex task through the variant API anymore because it's now accomplished through a transform. There's currently no replacement for controlling the dex process.
    • Fixed incremental support for assets.
    • Improved MultiDex support by making it available for test projects, and tests now automatically have the com.android.support:multidex-instrumentation dependency.
    • Added the ability to properly fail a Gradle build and report the underlying error cause when the Gradle build invokes asynchronous tasks and there's a failure in the worker process.
    • Added support for configuring a specific Application Binary Interface (ABI) in variants that contain multiple ABIs.
    • Added support for a comma-separated list of device serial numbers for the ANDROID_SERIAL environment variable when installing or running tests.
    • Fixed an installation failure on devices running Android 5.0 (API level 20) and higher when the APK name contains a space.
    • Fixed various issues related to the Android Asset Packaging Tool (AAPT) error output.
    • Added JaCoCo incremental instrumentation support for faster incremental builds. The Android plugin for Gradle now invokes the JaCoCo instrumenter directly. To force a newer version of the JaCoCo instrumenter, you need to add it as a build script dependency.
    • Fixed JaCoCo support so it ignores files that aren't classes.
    • Added vector drawable support for generating PNGs at build time for backward-compatibility. Android plugin for Gradle generates PNGs for every vector drawable found in a resource directory that doesn't specify an API version or specifies an android:minSdkVersion attribute of 20 or lower in the <uses-sdk> element in the app manifest. You can set PNG densities by using the generatedDensities property in the defaultConfig or productFlavor sections of a build.gradle file.
    • Added sharing of the mockable android.jar , which the plugin generates only once and uses for unit testing. Multiple modules, such as app and lib , now share it. Delete $rootDir/build to regenerate it.
    • Changed the processing of Java resources to occur before the obfuscation tasks instead of during the packaging of the APK. This change allows the obfuscation tasks to have a chance to adapt the Java resources following packages obfuscation.
    • Fixed an issue with using Java Native Interface (JNI) code in the experimental library plugin.
    • Added the ability to set the platform version separately from the android:compileSdkVersion attribute in the experimental library plugin.

    Android plugin for Gradle, revision 1.3.1 (August 2015)

    Dependencies:
    • Gradle 2.2.1 or higher.
    • Build Tools 21.1.1 or higher.
    General Notes:
    • Fixed the ZipAlign task to properly consume the output of the previous task when using a customized filename.
    • Fixed Renderscript packaging with the NDK .
    • Maintained support for the createDebugCoverageReport build task.
    • Fixed support for customized use of the archiveBaseName property in the build.gradle build file.
    • Fixed the Invalid ResourceType lint warning caused by parameter method annotation lookup when running lint outside of Android Studio.

    Android plugin for Gradle, revision 1.3.0 (July 2015)

    Dependencies:
    • Gradle 2.2.1 or higher.
    • Build Tools 21.1.1 or higher.
    General Notes:
    • Added support for the com.android.build.threadPoolSize property to control the Android task thread pool size from the gradle.properties file or the command line. The following example sets this property to 4.

              
              -Pcom.android.build.threadPoolSize=4
              
            
    • Set the default build behavior to exclude LICENSE and LICENSE.txt files from APKs. To include these files in an APK, remove these files from the packagingOptions.excludes property in the build.gradle file. Например:
      android {
            packagingOptions.excludes = []
          }
            
      android {
            packagingOptions.excludes.clear()
          }
          
    • Added the sourceSets task to inspect the set of all available source sets.
    • Enhanced unit test support to recognize multi-flavor and build variant source folders. For example, to test an app with multi-flavors flavor1 and flavorA with the Debug build type, the test source sets are:
      • тест
      • testFlavor1
      • testFlavorA
      • testFlavor1FlavorA
      • testFlavor1FlavorADebug

      Android tests already recognized multi-flavor source folders.

    • Improved unit test support to:
      • Run javac on main and test sources, even if the useJack property is set to true in your build file.
      • Correctly recognize dependencies for each build type.
    • Added support for specifying instrumentation test-runner arguments from the command line. Например:
      ./gradlew connectedCheck \
         -Pandroid.testInstrumentationRunnerArguments.size=medium \
         -Pandroid.testInstrumentationRunnerArguments.class=TestA,TestB
              
    • Added support for arbitrary additional Android Asset Packaging Tool (AAPT) parameters in the build.gradle file. Например:

      android {
          aaptOptions {
            additionalParameters "--custom_option", "value"
          }
      }
            
      android {
          aaptOptions {
            additionalParameters += listOf("--custom_option", "value")
          }
      }
            
    • Added support for a test APK module as a separate test module, using the targetProjectPath and targetVariant properties to set the APK path and target variant.

      Note: A test APK module does not support product flavors and can only target a single variant. Also, Jacoco is not supported yet.

    • Added resource name validation before merging resources.
    • When building an AAR (Android ARchive) package for library modules, do not provide an automatic @{applicationId} placeholder in the manifest merger settings. Instead, use a different placeholder, such as @{libApplicationId} and provide a value for it if you want to include application Ids in the archive library.

    Android plugin for Gradle, revision 1.2.0 (April 2015)

    Dependencies:
    • Gradle 2.2.1 or higher.
    • Build Tools 21.1.1 or higher.
    General Notes:
    • Enhanced support for running unit tests with Gradle.
      • Added support to include Java-style resources in the classpath when running unit tests directly from Gradle.
      • Added unit test dependency support for Android Archive (AAR) artifacts.
      • Added support for the unitTestVariants property so unit test variants can be manipulated using the build.gradle file.
      • Added the unitTest.all code block under testOptions to configure customized tasks for unit test. The following sample code shows how to add unit test configuration settings using this new option:
        android {
          testOptions {
            unitTest.all {
              jvmArgs '-XX:MaxPermSize=256m' // Or any other gradle option.
            }
          }
        }
        android {
          testOptions {
            unitTest.all {
              jvmArgs += listOf("-XX:MaxPermSize=256m") // Or any other gradle option.
            }
          }
        }
                    
      • Fixed the handling of enums and public instance fields in the packaging of the mockable-android.jar file.
      • Fixed library project task dependencies so test classes recompile after changes.
    • Added the testProguardFile property to apply ProGuard files when minifying a test APK.
    • Added the timeOut property to the adbOptions code block for setting the maximum recording time for Android Debug Bridge screen recording.
    • Added support for 280 dpi resources.
    • Improved performance during project evaluation.

    Android plugin for Gradle, revision 1.1.3 (March 2015)

    Dependencies:
    • Gradle 2.2.1 or higher.
    • Build Tools 21.1.1 or higher.
    General Notes:
    • Fixed issue with duplicated dependencies on a test app that triggered a ProGuard failure.
    • Fixed Comparator implementation which did not comply with the JDK Comparator contract and generated a JDK 7 error.

    Android plugin for Gradle, revision 1.1.2 (February 2015)

    Dependencies:
    • Gradle 2.2.1 or higher.
    • Build Tools 21.1.1 or higher.
    General Notes:
    • Normalized path when creating a mockable JAR for unit testing.
    • Fixed the archivesBaseName setting in the build.gradle file.
    • Fixed the unresolved placeholder failure in manifest merger when building a library test application.

    Android plugin for Gradle, revision 1.1.1 (February 2015)

    Dependencies:
    • Gradle 2.2.1 or higher.
    • Build Tools 21.1.1 or higher.
    General Notes:
    • Modified build variants so only variants that package a Wear app trigger Wear-specific build tasks.
    • Changed dependency related issues to fail at build time rather than at debug time. This behavior allows you to run diagnostic tasks (such as 'dependencies') to help resolve the conflict.
    • Fixed the android.getBootClasspath() method to return a value.

    Android plugin for Gradle, revision 1.1.0 (February 2015)

    Dependencies:
    • Gradle 2.2.1 or higher.
    • Build Tools 21.1.1 or higher.
    General Notes:
    • Added new unit test support
      • Enabled unit tests to run on the local JVM against a special version of the android.jar file that is compatible with popular mocking frameworks, for example Mockito.
      • Added new test tasks testDebug , testRelease , and testMyFlavorDebug when using product flavors.
      • Added new source folders recognized as unit tests: src/test/java/ , src/testDebug/java/ , src/testMyFlavor/java/ .
      • Added new configurations in the build.gradle file for declaring test-only dependencies, for example, testCompile 'junit:junit:4.11' , testMyFlavorCompile 'some:library:1.0' .

        Note: Test-only dependencies are not currently compatible with Jack (Java Android Compiler Kit).

      • Added the android.testOptions.unitTests.returnDefaultValues option to control the behaviour of the mockable android.jar.
    • Replaced Test in test task names with AndroidTest . For example, the assembleDebugTest task is now assembleDebugAndroidTest task. Unit test tasks still have UnitTest in the task name, for example assembleDebugUnitTest .
    • Modified ProGuard configuration files to no longer apply to the test APK. If minification is enabled, ProGuard processes the test APK and applies only the mapping file that is generated when minifying the main APK.
    • Updated dependency management
      • Fixed issues using provided and package scopes.

        Note: These scopes are incompatible with AAR (Android ARchive) packages and will cause a build with AAR packages to fail.

      • Modified dependency resolution to compare the dependencies of an app under test and the test app. If an artifact with the same version is found for both apps, it's not included with the test app and is packaged only with the app under test. If an artifact with a different version is found for both apps, the build fails.
    • Added support for anyDpi resource qualifier in resource merger.
    • Improved evaluation and IDE sync speeds for projects with a large number of Android modules .

    Android plugin for Gradle, revision 1.0.1 (January 2015)

    Dependencies:
    • Gradle 2.2.1 up to 2.3.x.

      Note: This version of the Android plugin for Gradle is not compatible with Gradle 2.4 and higher.

    • Build Tools 21.1.1 or higher.
    General Notes:
    • Fixed issue with Gradle build failure when accessing the extractReleaseAnnotations module. ( Issue 81638 ).
    • Fixed issue with Disable passing the --no-optimize setting to the Dalvik Executable (dex) bytecode. ( Issue 82662 ).
    • Fixed manifest merger issues when importing libraries with a targetSdkVersion less than 16.
    • Fixed density ordering issue when using Android Studio with JDK 8.

    Android plugin for Gradle, revision 1.0.0 (December 2014)

    Dependencies:
    • Gradle 2.2.1 up to 2.3.x.

      Note: This version of the Android plugin for Gradle is not compatible with Gradle 2.4 and higher.

    • Build Tools 21.1.1 or higher.
    General Notes:
    • Initial plugin release.