Активность

Получите доступ к компонуемым API, построенным на основе Activity.
Последнее обновление Стабильный релиз Предварительная версия для выпуска Бета-версия Альфа-версия
17 декабря 2025 г. 1.12.2 - - -

Объявление зависимостей

Чтобы добавить зависимость от Activity, необходимо добавить репозиторий Google Maven в ваш проект. Для получения дополнительной информации ознакомьтесь с информацией в репозитории Google Maven .

Добавьте зависимости для необходимых артефактов в файл build.gradle вашего приложения или модуля:

классный

dependencies {
    def activity_version = "1.12.2"

    // Java language implementation
    implementation "androidx.activity:activity:$activity_version"
    // Kotlin
    implementation "androidx.activity:activity-ktx:$activity_version"
}

Котлин

dependencies {
    val activity_version = "1.12.2"

    // Java language implementation
    implementation("androidx.activity:activity:$activity_version")
    // Kotlin
    implementation("androidx.activity:activity-ktx:$activity_version")
}

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

Обратная связь

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

Создать новую задачу

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

Версия 1.12

Версия 1.12.2

17 декабря 2025 г.

Выпущены androidx.activity:activity:1.12.2 , androidx.activity:activity-compose:1.12.2 и androidx.activity:activity-ktx:1.12.2 . Версия 1.12.2 содержит следующие коммиты .

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

  • Исправлена ​​ошибка, из-за которой ручная установка параметра isEnabled для обработчика события OnBackPressedCallback учитывающего жизненный цикл, переопределяла состояние жизненного цикла, что потенциально могло привести к сбоям. ( I7d898 , b/461999811 )

Версия 1.12.1

3 декабря 2025 г.

Выпущены androidx.activity:activity:1.12.1 , androidx.activity:activity-compose:1.12.1 и androidx.activity:activity-ktx:1.12.1 . Версия 1.12.1 содержит следующие коммиты .

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

Версия 1.12.0

19 ноября 2025 г.

Выпущены androidx.activity:activity:1.12.0 , androidx.activity:activity-compose:1.12.0 и androidx.activity:activity-ktx:1.12.0 . Версия 1.12.0 содержит следующие коммиты .

Важные изменения по сравнению с версией 1.11.0:

  • Библиотека Androidx Activity теперь зависит от новой библиотеки NavigationEvent . Это включает поддержку NavigationEventDispatcher в ComponentActivity и ComponentDialog . API-интерфейсы OnBackPressed также были переписаны поверх API NavigationEvent , чтобы обеспечить обратную совместимость с предыдущей библиотекой.

Версия 1.12.0-rc01

5 ноября 2025 г.

Выпущены androidx.activity:activity:1.12.0-rc01 , androidx.activity:activity-compose:1.12.0-rc01 и androidx.activity:activity-ktx:1.12.0-rc01 . Версия 1.12.0-rc01 содержит следующие коммиты .

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

  • Исправлены ошибки выполнения для BackHandler и PredictiveBackHandler в приложениях, использующих пользовательские классы Activity. Теперь эти компонуемые объекты безопасно возвращаются к LocalOnBackPressedDispatcherOwner , сохраняя при этом порядок отправки событий в приложениях, поддерживающих NavigationEventDispatcherOwner . ( I43873 )

Версия 1.12.0-beta01

22 октября 2025 г.

Выпущены androidx.activity:activity:1.12.0-beta01 , androidx.activity:activity-compose:1.12.0-beta01 и androidx.activity:activity-ktx:1.12.0-beta01 . Версия 1.12.0-beta01 содержит следующие коммиты .

Изменения в API

  • Представляем экспериментальный API ActivityFlags для управления изменениями поведения во время выполнения и миграциями. Первый флаг обеспечивает стабильный порядок для OnBackPressedCallback , что делает навигацию назад более предсказуемой при изменениях жизненного цикла. Разработчики могут отказаться от этой функции, установив ActivityFlags.isOnBackPressedLifecycleOrderMaintained = false . ( I06bdf , Id08bb , I439aa , b/422730945 , b/450533622 )

Обновление зависимостей

  • Обновите зависимости жизненного цикла до версии 2.9.4 ( Ic9fb2 ).

Версия 1.12.0-alpha09

24 сентября 2025 г.

Выпущены androidx.activity:activity:1.12.0-alpha09 , androidx.activity:activity-compose:1.12.0-alpha09 и androidx.activity:activity-ktx:1.12.0-alpha09 . Версия 1.12.0-alpha09 содержит следующие коммиты .

Изменения зависимостей

Версия 1.12.0-alpha08

10 сентября 2025 г.

Выпущены androidx.activity:activity:1.12.0-alpha08 , androidx.activity:activity-compose:1.12.0-alpha08 и androidx.activity:activity-ktx:1.12.0-alpha08 . Версия 1.12.0-alpha08 содержит следующие коммиты .

Обновление зависимостей

Версия 1.12.0-alpha07

27 августа 2025 г.

Выпущены androidx.activity:activity:1.12.0-alpha07 , androidx.activity:activity-compose:1.12.0-alpha07 и androidx.activity:activity-ktx:1.12.0-alpha07 . Версия 1.12.0-alpha07 содержит следующие коммиты .

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

  • Исправлена ​​ошибка в EdgeToEdge на API 35, из-за которой невидимые представления приводили к неожиданным отступам измерений. ( If49ff )

Обновление зависимостей

Версия 1.12.0-alpha06

13 августа 2025 г.

Выпущены androidx.activity:activity:1.12.0-alpha06 , androidx.activity:activity-compose:1.12.0-alpha06 и androidx.activity:activity-ktx:1.12.0-alpha06 . Версия 1.12.0-alpha06 содержит следующие коммиты .

Обновление MinSdk

Обновления документации

  • Внесены изменения в документацию KDocs для PredictiveBackHandler , чтобы указать на известную проблему синхронизации, из-за которой жест может обрабатываться в том же кадре, в котором функция отключена. ( I5be5c , b/431534103 )
  • Обновлена ​​документация KDocs для BackHandler и PredictiveBackHandler , чтобы явно указать поведение «победа по итогам составления комбинации», а также рекомендовать безусловное составление комбинации с enabled флагом. ( I7ab94 )

Обновление зависимостей

Версия 1.12.0-alpha05

30 июля 2025 г.

Выпущены androidx.activity:activity:1.12.0-alpha05 , androidx.activity:activity-compose:1.12.0-alpha05 и androidx.activity:activity-ktx:1.12.0-alpha05 . Версия 1.12.0-alpha05 содержит следующие коммиты .

Обновление зависимостей

Версия 1.12.0-alpha04

2 июля 2025 г.

Выпущены androidx.activity:activity:1.12.0-alpha04 , androidx.activity:activity-compose:1.12.0-alpha04 и androidx.activity:activity-ktx:1.12.0-alpha04 . Версия 1.12.0-alpha04 содержит следующие коммиты .

Изменения зависимостей

Версия 1.12.0-alpha03

18 июня 2025 г.

Выпущены androidx.activity:activity:1.12.0-alpha03 , androidx.activity:activity-compose:1.12.0-alpha03 и androidx.activity:activity-ktx:1.12.0-alpha03 . Версия 1.12.0-alpha03 содержит следующие коммиты .

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

  • Теперь OnBackPressedDispatcher и NavigationEventDispatcher инициализируются лениво в ComponentActivity . ( I710e6 )

  • Исправлены ошибки в функции OnBackPressedDistpatcher , которые приводили к следующим последствиям:

    • Только последний диспетчер, в который был добавлен OnBackPressedCallback , получает уведомление о своем включенном состоянии ( b/418715930 )
    • OnBackPressedDispatcher удаляет некорректный коллбэк при использовании функции addCallback , которая принимает значение жизненного цикла. ( b/422714753 )
    • OnBackPressedDispatcher.remove() не удаляет все зарегистрированные экземпляры OnBackPressedCallback . ( b/423024414 )

Версия 1.12.0-alpha02

4 июня 2025 г.

Выпущены androidx.activity:activity:1.12.0-alpha02 , androidx.activity:activity-compose:1.12.0-alpha02 и androidx.activity:activity-ktx:1.12.0-alpha02 . Версия 1.12.0-alpha02 содержит следующие коммиты .

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

  • Начиная с NavigationEvent 1.0.0-alpha02 : Исправлена ​​ошибка ConcurrentModificationException , которая могла возникать при вызове NavigationEventCallback.remove() из-за одновременного изменения внутреннего списка закрываемых элементов. ( I63066 )

Версия 1.12.0-alpha01

20 мая 2025 г.

Выпущены androidx.activity:activity:1.12.0-alpha01 , androidx.activity:activity-compose:1.12.0-alpha01 и androidx.activity:activity-ktx:1.12.0-alpha01 . Версия 1.12.0-alpha01 содержит следующие коммиты .

Новые функции

  • ComponentActivity и ComponentDialog интегрированы с NavigationEvent 1.0.0-alpha01 через API NavigationEventDispatcherOwner . Теперь вы можете получить NavigationEventDispatcher из вашего ComponentActivity через поле navigationEventDispatcher . Поскольку OnBackPressedDispatcher был переписан на основе новой библиотеки, все предыдущие варианты использования должны продолжать работать корректно. В дальнейшем следует использовать NavigationEventDispatcher и NavigationEventCallback . ( Ib8eed , I6cc44 , Ib7724 , I9a0f7 , b/412597031 , b/415028038 , b/412596729 , b/412597140 , b/412596012 )

Версия 1.11

Версия 1.11.0

10 сентября 2025 г.

Выпущены androidx.activity:activity:1.11.0 , androidx.activity:activity-compose:1.11.0 и androidx.activity:activity-ktx:1.11.0 . Версия 1.11.0 содержит следующие коммиты .

Важные изменения по сравнению с версией 1.10.0:

  • В метод PickVisualMediaRequest добавлен API MediaCapabilities , позволяющий приложениям указывать свои возможности работы с мультимедиа, например, поддерживаемые типы HDR.
  • Теперь приложение компилируется с использованием API 36.

Версия 1.11.0-rc01

23 апреля 2025 г.

Выпущены androidx.activity:activity:1.11.0-rc01 , androidx.activity:activity-compose:1.11.0-rc01 и androidx.activity:activity-ktx:1.11.0-rc01 . Версия 1.11.0-rc01 содержит следующие коммиты .

Версия 1.11.0-beta01

9 апреля 2025 г.

Выпущены androidx.activity:activity:1.11.0-beta01 , androidx.activity:activity-compose:1.11.0-beta01 и androidx.activity:activity-ktx:1.11.0-beta01 . Версия 1.11.0-beta01 содержит следующие коммиты .

Версия 1.11.0-alpha02

26 марта 2025 г.

Выпущены androidx.activity:activity:1.11.0-alpha02 , androidx.activity:activity-compose:1.11.0-alpha02 и androidx.activity:activity-ktx:1.11.0-alpha02 . Версия 1.11.0-alpha02 содержит следующие коммиты .

Изменения в API

  • Встроены новые параметры EDGE_NONE и frameTimeMillis из Android 16 Beta03 в BackEventCompat предоставляемый функциями handleOnBackStarted и handleOnBackProgressed из OnBackPressedCallback .

Обновления зависимостей

  • Теперь приложение скомпилировано с использованием API 36. ( I510e8 , b/301910674 )

Версия 1.11.0-alpha01

12 марта 2025 г.

Выпущены androidx.activity:activity:1.11.0-alpha01 , androidx.activity:activity-compose:1.11.0-alpha01 и androidx.activity:activity-ktx:1.11.0-alpha01 . Версия 1.11.0-alpha01 содержит следующие коммиты .

Новые функции

  • Добавлен API MediaCapabilities в PickVisualMediaRequest , позволяющий приложениям указывать свои возможности работы с мультимедиа, например, поддерживаемые типы HDR. ( Ic3ee7 )

Версия 1.10

Версия 1.10.1

26 февраля 2025 г.

Выпущены androidx.activity:activity:1.10.1 , androidx.activity:activity-compose:1.10.1 и androidx.activity:activity-ktx:1.10.1 . Версия 1.10.1 содержит следующие коммиты .

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

  • Теперь ViewTree OnBackPressedDispatcherOwners и FullyDrawnReporterOwners могут разрешаться через непересекающиеся родительские элементы представления, такие как ViewOverlay . Дополнительную информацию о непересекающихся родительских элементах представления см. в примечаниях к выпуску ядра или в документации по ViewTree.setViewTreeDisjointParent ( IE7750 )

Версия 1.10.0

15 января 2025 г.

Выпущены androidx.activity:activity:1.10.0 , androidx.activity:activity-compose:1.10.0 и androidx.activity:activity-ktx:1.10.0 . Версия 1.10.0 содержит следующие коммиты .

Важные изменения по сравнению с версией 1.9.0

  • Теперь PhotoPicker позволяет выбирать изображения по порядку и указывать, какая вкладка (альбомы или изображения) должна быть видна изначально.
  • Контракты PickVisualMedia и PickMultipleVisualMedia Activity Result, запускающие средство выбора фотографий, больше не делегируют управление сервисам Google Play, если системное средство выбора фотографий недоступно, а используют общедоступное действие ACTION_SYSTEM_FALLBACK_PICK_IMAGES и связанные с ним дополнительные параметры для обеспечения согласованного взаимодействия со средством выбора фотографий для OEM-производителей и системных приложений в качестве резервного варианта.
  • Новый локальный объект композиции LocalActivity предоставляет Activity для текущей области видимости, устраняя необходимость для разработчиков получать Activity из LocalContext .

Версия 1.10.0-rc01

11 декабря 2024 г.

Выпущены androidx.activity:activity:1.10.0-rc01 , androidx.activity:activity-compose:1.10.0-rc01 и androidx.activity:activity-ktx:1.10.0-rc01 . Версия 1.10.0-rc01 содержит следующие коммиты .

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

  • Исправлена ​​ошибка, из-за которой изменение состояния "включено" во время активности PredictiveBackHandler приводило к немедленному прерыванию обратного вызова. Теперь обратный вызов завершится независимо от изменений состояния "включено". ( Ib8719 )

Версия 1.10.0-beta01

13 ноября 2024 г.

Выпущены androidx.activity:activity:1.10.0-beta01 , androidx.activity:activity-compose:1.10.0-beta01 и androidx.activity:activity-ktx:1.10.0-beta01 без изменений по сравнению с последней альфа-версией. Версия 1.10.0-beta01 содержит следующие коммиты .

Версия 1.10.0-alpha03

30 октября 2024 г.

Выпущены androidx.activity:activity:1.10.0-alpha03 , androidx.activity:activity-compose:1.10.0-alpha03 и androidx.activity:activity-ktx:1.10.0-alpha03 . Версия 1.10.0-alpha03 содержит следующие коммиты .

Изменения в API

  • Добавлен новый локальный объект композиции LocalActivity , который предоставляет Activity для текущей области видимости, устраняя необходимость для разработчиков получать Activity из LocalContext . Он также включает новое правило линтинга, которое проверяет, когда LocalContext некорректно преобразуется в Activity . ( I7746a , b/283009666 )

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

  • В обновлении 1.9.3 : PredictiveBackHandler больше не будет вызывать свою функцию обратного вызова после отключения обработчика. Это исправит проблему, из-за которой NavHost из Navigation Compose выдавал исключение IndexOutOfBoundsException . ( I3f75e , b/365027664 , b/340202286 )

Обновление зависимостей

  • Activity Compose теперь зависит от Compose Runtime 1.7.0 ( I7746a , b/283009666 ).

Версия 1.10.0-alpha02

4 сентября 2024 г.

Выпущены androidx.activity:activity:1.10.0-alpha02 , androidx.activity:activity-compose:1.10.0-alpha02 и androidx.activity:activity-ktx:1.10.0-alpha02 . Версия 1.10.0-alpha02 содержит следующие коммиты .

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

  • Контракты PickVisualMedia и PickMultipleVisualMedia Activity Result, запускающие средство выбора фотографий, больше не делегируют управление сервисам Google Play, если системное средство выбора фотографий недоступно, а используют общедоступное действие ACTION_SYSTEM_FALLBACK_PICK_IMAGES и связанные с ним дополнительные параметры для обеспечения согласованного взаимодействия со средством выбора фотографий для производителей оборудования и системных приложений в качестве резервного варианта. Это не должно повлиять на пользовательский опыт на устройствах с последней версией сервисов Google Play. ( I3513d )

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

  • Удалено ручное описание доступа к новым API платформы, поскольку это происходит автоматически посредством моделирования API при использовании R8 с AGP 7.3 или более поздней версии (например, R8 версии 3.3) и для всех сборок при использовании AGP 8.1 или более поздней версии (например, D8 версии 8.1). Клиентам, не использующим AGP, рекомендуется обновиться до D8 версии 8.1 или более поздней. Подробнее см. в этой статье . ( I9496c , b/345472586 )
  • В Activity 1.9.2 исправлена ​​ошибка, из-за которой API PredictiveBackHandler в Activity Compose продолжал обрабатывать системный жест "назад" в том кадре, где он был отключен, что могло привести к тому, что такие библиотеки, как Navigation Compose, обрабатывали жест "назад" даже при пустом стеке возврата, что приводило к возникновению исключения IndexOutOfBoundsException . ( Ie3301 , b/340202286 )
  • Из Activity 1.9.1 : Исправлена ​​ошибка в PredictiveBackHandler , из-за которой после выполнения системного возврата попытка вызова onBackPressed из OnBackPressedDispatcher завершалась неудачей. ( I5f1f8 )

Версия 1.10.0-alpha01

26 июня 2024 г.

Выпущены androidx.activity:activity:1.10.0-alpha01 , androidx.activity:activity-compose:1.10.0-alpha01 и androidx.activity:activity-ktx:1.10.0-alpha01 . Эта версия разрабатывается во внутренней ветке.

Новые функции

  • Добавлена ​​поддержка новых функций PhotoPicker , представленных в Android V, включая возможность выбора изображений по порядку и выбора того, какая вкладка (альбомы или изображения) должна быть видна изначально.

Версия 1.9

Версия 1.9.3

16 октября 2024 г.

Выпущены androidx.activity:activity:1.9.3 , androidx.activity:activity-compose:1.9.3 и androidx.activity:activity-ktx:1.9.3 . Версия 1.9.3 содержит следующие коммиты .

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

  • PredictiveBackHandler больше не будет вызывать свой обратный вызов после отключения обработчика. Это исправит проблему, из-за которой NavHost из Navigation Compose выдавал исключение IndexOutOfBoundsException . ( I3f75e , b/340202286 )

Версия 1.9.2

4 сентября 2024 г.

Выпущены androidx.activity:activity:1.9.2 , androidx.activity:activity-compose:1.9.2 и androidx.activity:activity-ktx:1.9.2 . Версия 1.9.2 содержит следующие lthcocommits .

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

  • Исправлена ​​ошибка, из-за которой API PredictiveBackHandler в Activity Compose продолжал обрабатывать системный жест "назад" в том кадре, где он был отключен, что могло привести к тому, что такие библиотеки, как Navigation Compose, обрабатывали жест "назад" даже при пустом стеке возврата, что приводило к возникновению исключения IndexOutOfBoundsException . ( Ie3301 , b/340202286 )

Версия 1.9.1

24 июля 2024 г.

Выпущены androidx.activity:activity:1.9.1 , androidx.activity:activity-compose:1.9.1 и androidx.activity:activity-ktx:1.9.1 . Версия 1.9.1 содержит следующие коммиты .

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

  • Исправлена ​​ошибка в PredictiveBackHandler , из-за которой после выполнения системного возврата попытка вызова onBackPressed из OnBackPressedDispatcher завершалась неудачей. ( I5f1f8 )

Версия 1.9.0

17 апреля 2024 г.

Выпущены androidx.activity:activity:1.9.0 , androidx.activity:activity-compose:1.9.0 и androidx.activity:activity-ktx:1.9.0 . Версия 1.9.0 содержит следующие коммиты .

Важные изменения по сравнению с версией 1.8.0

  • Теперь ComponentActivity реализует OnUserLeaveHintProvider , позволяющий компонентам вызывать обратные вызовы для событий onUserLeaveHint .
  • Теперь API-интерфейсы OnBackPressedCallback , BackHandler и PredictiveBackHandler выдают предупреждение при вызове onBackPressedDispatcher.onBackPressed() при обработке нажатия кнопки "Назад", поскольку это всегда будет нарушать анимацию предиктивного нажатия кнопки "Назад" . Более подробную информацию см. в руководстве по лучшим практикам .
  • Остальная часть API Activity была переписана на Kotlin, а все расширения, ранее доступные в activity-ktx были перенесены в activity . Теперь activity-ktx полностью пуст.
    • В рамках преобразования ActivityResultLauncher в Kotlin метод getContract теперь является абстрактным свойством Kotlin. Это бинарно совместимое изменение, но оно нарушит совместимость исходного кода, если ваша реализация ActivityResultLauncher написана на Kotlin.

Версия 1.9.0-rc01

3 апреля 2024 г.

Выпущены androidx.activity:activity:1.9.0-rc01 , androidx.activity:activity-compose:1.9.0-rc01 и androidx.activity:activity-ktx:1.9.0-rc01 . Версия 1.9.0-rc01 содержит следующие коммиты .

Обновление зависимостей

Версия 1.9.0-beta01

20 марта 2024 г.

Выпущены androidx.activity:activity:1.9.0-beta01 , androidx.activity:activity-compose:1.9.0-beta01 и androidx.activity:activity-ktx:1.9.0-beta01 . Версия 1.9.0-beta01 содержит следующие коммиты .

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

  • Исправлена ​​ошибка, приводящая к снижению производительности при запуске Activity, появившаяся в Activity 1.9.0-alpha02 из-за вызова OnBackPressedDispatcher в процессе создания Activity. ( IE75e3 )

Версия 1.9.0-alpha03

7 февраля 2024 г.

Выпущены коммиты androidx.activity:activity:1.9.0-alpha03 , androidx.activity:activity-compose:1.9.0-alpha03 и androidx.activity:activity-ktx:1.9.0-alpha03 . Версия 1.9.0-alpha03 содержит следующие коммиты.

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

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

  • Если система отправляет событие "назад", запущенное во время уже выполняющегося предиктивного жеста "назад", текущий выполняющийся предиктивный жест "назад" отменяется, и новое событие "назад" начинает новый предиктивный жест "назад". ( I3482e )
  • Исправлена ​​ошибка, приводившая к сбою при первом обращении к методу onBackPressedDispatcher из ComponentActivity из фонового потока. Теперь безопасно обращаться к onBackPressedDispatcher из любого потока. ( I79955 )

Версия 1.9.0-alpha02

24 января 2024 г.

Выпущены коммиты androidx.activity:activity:1.9.0-alpha02 , androidx.activity:activity-compose:1.9.0-alpha02 и androidx.activity:activity-ktx:1.9.0-alpha02 . Версия 1.9.0-alpha02 содержит следующие коммиты.

Преобразования в Kotlin

  • ActivityResultRegistry был переписан на Kotlin. Это гарантирует, что возможность значения null в обобщенных типах контракта, передаваемого в register , будет корректно передана в возвращаемый вам класс ActivityResultLauncher . ( I121f0 )
  • ActivityResult был переписан на Kotlin. Расширения ActivityResult на Kotlin, поддерживающие деструктуризацию в поля resultCode и data были перенесены из activity-ktx в activity . ( I0565a )
  • Расширения Kotlin by viewModels() для ComponentActivity и trackPipAnimationHintView были перемещены из activity-ktx в activity . Артефакт activity-ktx теперь полностью пуст. ( I0a444 )

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

  • API enableEdgeToEdge теперь обводит контуры любых вырезов в экране. ( a3644b , b/311173461 )
  • Начиная с Activity 1.8.2 : Исправлена ​​ошибка передачи дополнительного параметра в ACTION_SYSTEM_FALLBACK_PICK_IMAGES контракта Activity выбора фотографий, теперь корректно передается ключ EXTRA_SYSTEM_FALLBACK_PICK_IMAGES_MAX , а не дополнительный параметр с ключом "com.google.android.gms.provider.extra.PICK_IMAGES_MAX" . Настоятельно рекомендуется, если вы являетесь OEM-производителем, внедряющим резервный вариант выбора фотографий в системе, поддерживать оба дополнительных параметра для обеспечения максимально широкой совместимости. ( I96a00 )

Версия 1.9.0-alpha01

29 ноября 2023 г.

Выпущены коммиты androidx.activity:activity:1.9.0-alpha01 , androidx.activity:activity-compose:1.9.0-alpha01 и androidx.activity:activity-ktx:1.9.0-alpha01 . Версия 1.9.0-alpha01 содержит следующие коммиты.

Новые функции

  • Теперь ComponentActivity реализует интерфейс OnUserLeaveHintProvider , позволяющий компонентам вызывать обратные вызовы для событий onUserLeaveHint . ( I54892 )

Изменения в API

  • ComponentActivity был переписан на Kotlin. ( I14f31 )
  • ActivityResultCaller был переписан на Kotlin. ( Ib02e4 )
  • ActivityResultLauncher был переписан на Kotlin. В рамках этого преобразования метод getContract теперь является абстрактным свойством Kotlin. Это бинарно совместимое изменение, но оно нарушит совместимость исходного кода, если ваша реализация ActivityResultLauncher написана на Kotlin. ( Id4615 )
  • Теперь PickVisualMediaRequest установлен тот же минимальный уровень API — 19, что и для контракта PickVisualMedia Activity Result. ( Id6e21 )

Обновление зависимостей

Версия 1.8

Версия 1.8.2

13 декабря 2023 г.

Выпущены androidx.activity:activity:1.8.2 , androidx.activity:activity-compose:1.8.2 и androidx.activity:activity-ktx:1.8.2 . Версия 1.8.2 содержит эти коммиты.

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

  • Исправлена ​​ошибка, допущенная при передаче ACTION_SYSTEM_FALLBACK_PICK_IMAGES в контракте действия выбора фотографий: теперь корректно передается ключ EXTRA_SYSTEM_FALLBACK_PICK_IMAGES_MAX , а не ключ "com.google.android.gms.provider.extra.PICK_IMAGES_MAX" . Настоятельно рекомендуется, если вы являетесь OEM-производителем, внедряющим резервный вариант выбора фотографий в системе, поддерживать оба параметра для обеспечения максимально широкой совместимости. ( I96a00 )

Версия 1.8.1

15 ноября 2023 г.

Выпущены androidx.activity:activity:1.8.1 , androidx.activity:activity-compose:1.8.1 и androidx.activity:activity-ktx:1.8.1 . Версия 1.8.1 содержит эти коммиты.

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

  • Теперь OnBackPressedDispatcher продолжает перенаправлять вызов в правильный OnBackPressedCallback даже после добавления нового OnBackPressedCallback во время обработки жеста "назад". ( Id0ff6 )

Версия 1.8.0

4 октября 2023 г.

Выпущены androidx.activity:activity:1.8.0 , androidx.activity:activity-compose:1.8.0 и androidx.activity:activity-ktx:1.8.0 . Версия 1.8.0 содержит эти коммиты.

Важные изменения по сравнению с версией 1.7.0

  • Функция Predictive BackOnBackPressedCallback теперь предлагает новые функции обратного вызова для обработки начала жеста «назад», прогресса выполнения жеста и отмены жеста «назад» в дополнение к предыдущей функции обратного вызова handleOnBackPressed() которая срабатывала при подтверждении жеста «назад». Также добавлена ​​функция PredictiveBackHandler Composable для обработки событий прогнозируемого жеста «назад» в Activity Compose. Она предоставляет поток объектов BackEventCompat, которые необходимо собрать в приостанавливаемой лямбда-функции, которую вы предоставляете:
  PredictiveBackHandler { progress: Flow<BackEventCompat> ->
    // code for gesture back started
    try {
      progress.collect { backEvent ->
      // code for progress
    }
    // code for completion
    } catch (e: CancellationException) {
      // code for cancellation
    }
  }

ComponentActivity.onBackPressed() теперь устарел в пользу API для обработки возврата. Разработчикам следует использовать OnBackPressedDispatcher , а не переопределять этот метод.

  • Добавлена ​​функция EdgeToEdge - ComponentActivity.enableEdgeToEdge() позволяющая легко настроить отображение от края до края с обеспечением обратной совместимости.

Версия 1.8.0-rc01

20 сентября 2023 г.

Выпущены коммиты androidx.activity:activity:1.8.0-rc01 , androidx.activity:activity-compose:1.8.0-rc01 и androidx.activity:activity-ktx:1.8.0-rc01 . Версия 1.8.0-rc01 содержит эти коммиты.

Версия 1.8.0-beta01

6 сентября 2023 г.

Выпущены коммиты androidx.activity:activity:1.8.0-beta01 , androidx.activity:activity-compose:1.8.0-beta01 и androidx.activity:activity-ktx:1.8.0-beta01 . Версия 1.8.0-beta01 содержит следующие коммиты.

Улучшение документации

  • Улучшена документация BackEventCompat . ( aosp/2722254 )

Версия 1.8.0-alpha07

23 августа 2023 г.

Выпущены коммиты androidx.activity:activity:1.8.0-alpha07 , androidx.activity:activity-compose:1.8.0-alpha07 и androidx.activity:activity-ktx:1.8.0-alpha07 . Версия 1.8.0-alpha07 содержит следующие коммиты.

Новые функции

  • В Activity Compose добавлен новый компонент PredictiveBackHandler для обработки событий прогнозируемого жеста «назад». Он предоставляет Flow объектов BackEventCompat , которые необходимо собрать в приостанавливаемой лямбда-функции, которую вы предоставляете:

    PredictiveBackHandler { progress: Flow<BackEventCompat> ->
      // code for gesture back started
      try {
        progress.collect { backEvent ->
        // code for progress
      }
      // code for completion
      } catch (e: CancellationException) {
        // code for cancellation
      }
    }
    

    Также имеется предупреждение на этапе компиляции, выдаваемое правилом линтинга, чтобы гарантировать, что Flow вызывает collect() . ( Id2773 , b/294884345 )

  • Теперь обработчик onBackPressedDispatcher в ComponentActivity инициализируется лениво, то есть создается только при необходимости. ( I0bf8e )

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

  • В Android 13 ComponentActivity больше не будет отображать ошибку NullPointerException при получении коллбэка onBackPressed() , если Activity уже была DESTROYED . ( Idb055 , b/291869278 )
  • Удалены случаи использования экспериментального API isAtLeastU() ( Ie9117 , b/289269026 )

Версия 1.8.0-alpha06

21 июня 2023 г.

Выпущены коммиты androidx.activity:activity:1.8.0-alpha06 , androidx.activity:activity-compose:1.8.0-alpha06 и androidx.activity:activity-ktx:1.8.0-alpha06 . Версия 1.8.0-alpha06 содержит следующие коммиты.

Новые функции

  • Теперь OnBackPressedDispatcher корректно отменяет любые обратные вызовы, которые удаляются во время предиктивного жеста «Назад». ( I3f90f )

Изменения в API

  • При передаче SystemBarStyle.auto в API enableEdgeToEdge теперь можно переопределить параметр лямбда-функции detectDarkMode , чтобы задать собственную логику для определения ночного режима. ( aosp/2546393 , b/278263793 )

Версия 1.8.0-alpha05

7 июня 2023 г.

Выпущены androidx.activity:activity:1.8.0-alpha05 , androidx.activity:activity-compose:1.8.0-alpha05 и androidx.activity:activity-ktx:1.8.0-alpha05 . Эта версия разрабатывается во внутренней ветке.

Изменения в API

  • В Activity теперь есть класс BackEventCompat , который служит обратно совместимой версией BackEvent , не связанной с классом BackEvent из фреймворка.
  • Критическое изменение: методы handleOnBackStarted и handleOnBackProgressed класса OnBackPressedCallback теперь получают экземпляр androidx.activity.BackEventCompat вместо класса android.window.BackEvent из фреймворка. Эквивалентные API-интерфейсы @VisibleForTesting для OnBackPressedDispatcher также были обновлены.
  • Конструктор OnBackPressedDispatcher теперь принимает необязательный экземпляр Consumer<Boolean> , который позволяет владельцам диспетчера получать обратный вызов всякий раз, когда количество включенных обратных вызовов изменяется с нуля на ненулевое или наоборот.

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

  • Из задания 1.7.2 : Исправлена ​​ошибка, приводящая к сбою ReportDrawn при переходе с экрана до вызова report . ( Ic46f1 , b/260506820 )

Версия 1.8.0-alpha04

10 мая 2023 г.

Выпущены версии androidx.activity:activity:1.8.0-alpha04 , androidx.activity:activity-compose:1.8.0-alpha04 и androidx.activity:activity-ktx:1.8.0-alpha04 . Это было выпущено из внутренней ветки.

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

  • Начиная с Activity 1.7.1 : - ReportFullyDrawExecuter больше не вызывает утечек памяти при использовании ComponentActivity с ActivityScenario . ( Id2ff2 , b/277434271 )

Версия 1.8.0-alpha03

12 апреля 2023 г.

Выпущены androidx.activity:activity:1.8.0-alpha03 , androidx.activity:activity-compose:1.8.0-alpha03 и androidx.activity:activity-ktx:1.8.0-alpha03 . Это было выпущено из внутренней ветки.

Новые функции

  • Добавлена ComponentActivity.setUpEdgeToEdge() для простой настройки отображения от края до края с обеспечением обратной совместимости.

Изменения в API

  • ComponentActivity.onBackPressed() устарел в пользу API для обработки возврата. Разработчикам теперь следует использовать OnBackPressedDispatcher , а не переопределять этот метод. ( Ibce2f , b/271596918 )
  • ComponentDialog и ComponentActivity теперь содержат публичный API initViewTreeOwners() , который используется для инициализации всех владельцев дерева представлений перед установкой представления содержимого. ( Ibdce0 , b/261314581 )

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

  • Исправлена ​​ошибка, из-за которой фрагменты некорректно аннулировали MenuHosts, что приводило к неожиданному поведению других меню в Activity. ( I9404e , b/244336571 )

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

  • В ActivityResultRegister теперь используется Kotlin Random вместо Java. ( I4d98f , b/272096025 )

Версия 1.8.0-alpha02

8 марта 2023 г.

Выпущены androidx.activity:activity:1.8.0-alpha02 , androidx.activity:activity-compose:1.8.0-alpha02 и androidx.activity:activity-ktx:1.8.0-alpha02 . Разработаны на основе внутренней ветки.

Обновление зависимостей

Версия 1.8.0-alpha01

8 февраля 2023 г.

Выпущены androidx.activity:activity:1.8.0-alpha01 , androidx.activity:activity-compose:1.8.0-alpha01 и androidx.activity:activity-ktx:1.8.0-alpha01 . Сборка производилась из внутренней ветки.

Новые функции

  • В дополнение к предыдущему коллбэку handleOnBackPressed(), который использовался при подтверждении жеста "Назад", класс OnBackPressedCallback теперь содержит новые функции обратного вызова для прогнозирования прогресса жеста "Назад", обработки начала жеста, его выполнения и отмены, а также функции обратного вызова handleOnBackPressed() .

Версия 1.7

Версия 1.7.2

24 мая 2023 г.

Выпущены androidx.activity:activity:1.7.2 , androidx.activity:activity-compose:1.7.2 и androidx.activity:activity-ktx:1.7.2 . Версия 1.7.2 содержит эти коммиты.

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

  • Исправлена ​​ошибка, приводящая к сбою функции ReportDrawn при переходе с одного экрана на другой до вызова функции report . ( Ic46f1 , b/260506820 )

Версия 1.7.1

19 апреля 2023 г.

Выпущены androidx.activity:activity:1.7.1 , androidx.activity:activity-compose:1.7.1 и androidx.activity:activity-ktx:1.7.1 . Версия 1.7.1 содержит эти коммиты.

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

  • Функция ReportFullyDrawExecuter больше не вызывает утечек памяти при использовании ComponentActivity с ActivityScenario . ( Id2ff2 , b/277434271 )

Версия 1.7.0

22 марта 2023 г.

Выпущены androidx.activity:activity:1.7.0 , androidx.activity:activity-compose:1.7.0 и androidx.activity:activity-ktx:1.7.0 . Версия 1.7.0 содержит эти коммиты.

Важные изменения по сравнению с версией 1.6.0

  • Контракты действий выбора фотографий в PickVisualMedia и PickMultipleVisualMedia были обновлены и теперь содержат дополнительный резервный вариант на случай недоступности MediaStore.ACTION_PICK_IMAGES . Это позволяет производителям оборудования и системным приложениям, таким как сервисы Google Play, обеспечивать единообразный интерфейс выбора фотографий на более широком спектре устройств Android и уровней API, реализуя резервное действие . Выбор фотографий будет использовать этот резервный вариант, если он доступен, прежде чем перейти к использованию Intent.ACTION_OPEN_DOCUMENT , который по-прежнему поддерживает все устройства с API 19 и выше.
  • Теперь ComponentDialog реализует интерфейс SavedStateRegistryOwner и имеет доступ к собственному SavedStateRegistry , а также устанавливает SavedStateRegistryOwner для своего ViewTree . Теперь можно использовать Jetpack Compose внутри ComponentDialog , поскольку он соответствует требованиям LifecycleOwner и SavedStateRegistryOwner прикрепленных к Window через API ViewTree .
  • Теперь IntentSenderRequest.Builder.setFlags() позволяет устанавливать несколько флагов из Intent , а не только один.

Преобразование в Kotlin

Ряд классов Activity был переведён на Kotlin. Все переведённые классы сохранили свою бинарную совместимость с предыдущими версиями. В следующих классах произошли изменения, несовместимые с исходным кодом классов, написанных на Kotlin: ActivityResultRegistryOwner , OnBackPressedDispatcherOwner .

В таблице ниже представлены результаты преобразования исходных файлов для новой версии Activity:

Задание 1.5 Задание 1.6
override fun getActivityResultRegistry() = activityResultRegistry override val activityResultRegistry = activityResultRegistry
override fun getOnBackPressedDispatcher() = onBackPressedDispatcher override val onBackPressedDispatcher = onBackPressedDispatcher

Эти классы также были переведены на Kotlin, но сохранили совместимость с исходным кодом: ContextAware , ContextAwareHelper , OnContextAvailableListener , IntentSenderRequest и OnBackPressedDispatcher

API FullyDrawnReporter

Теперь ComponentActivity предоставляет экземпляр FullyDrawnReporter , который позволяет нескольким компонентам сообщать о готовности к взаимодействию. ComponentActivity будет ждать завершения работы всех компонентов, прежде чем вызывать reportFullyDrawn() от вашего имени. Эти API-интерфейсы автоматически обеспечивают соблюдение временных требований и не требуют вызова в рамках метода onDraw .

Рекомендуется использовать следующие API для обеспечения следующих возможностей:

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

Для более удобного использования FullyDrawnReporter из отдельных создаваемых объектов были добавлены три API для создания активностей:

  • ReportDrawn указывает, что ваш составной объект немедленно готов к взаимодействию.
  • ReportDrawnWhen takes a predicate (ie, list.count > 0 ) to indicate when your composable is ready for interaction.
  • ReportDrawnAfter takes a suspending method that, when it completes, indicates that you are ready for interaction.

Обновления зависимостей

Version 1.7.0-rc01

8 марта 2023 г.

androidx.activity:activity:1.7.0-rc01 , androidx.activity:activity-compose:1.7.0-rc01 , and androidx.activity:activity-ktx:1.7.0-rc01 are released. Version 1.7.0-rc01 contains these commits.

Dependency update

Version 1.7.0-beta02

22 февраля 2023 г.

androidx.activity:activity:1.7.0-beta02 , androidx.activity:activity-compose:1.7.0-beta02 , and androidx.activity:activity-ktx:1.7.0-beta02 are released. Version 1.7.0-beta02 contains these commits.

Изменения в API

  • The action and extra used by the PickVisualMedia and PickMultipleVisualMedia contracts as a fallback for when MediaStore.ACTION_PICK_IMAGES is unavailable are now public constants that provide API stability to OEMs and system apps that want to provide a consistent Photo Picker experience. The implementation of this fallback is still limited to only system apps. ( Icd320 )

Version 1.7.0-beta01

8 февраля 2023 г.

androidx.activity:activity:1.7.0-beta01 , androidx.activity:activity-compose:1.7.0-beta01 , and androidx.activity:activity-ktx:1.7.0-beta01 are released. Version 1.7.0-beta01 contains these commits.

Новые функции

  • IntentSenderRequest.Builder.setFlags() now allows you to set multiple flags from Intent , rather than only a single flag. ( Iac04c )

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

  • The fallback for PickVisualMedia for when the framework Photo Picker is unavailable now correctly limits the handling to apps installed in the device's system image. ( If8ae6 )

Kotlin Conversions

  • ActivityResultRegistryOwner is now written in Kotlin. This is a source incompatible change for those classes written in Kotlin - you must now override the activityResultRegistry property rather than implementing the previous getActivityResultRegistry() function. ( I0b00e )
  • OnBackPressedDispatcherOwner is now written in Kotlin. This is a source incompatible change for those classes written in Kotlin - you must now override the onBackPressedDispatcher property rather than implementing the previous getOnBackPressedDispatcher function. ( Ia277d )
  • ContextAware , ContextAwareHelper , OnContextAvailableListener , IntentSenderRequest and OnBackPressedDispatcher are now written in Kotlin. ( I1a73e , Iada92 , aosp/2410754 , I18ac7 , b/257291701 )

Version 1.7.0-alpha04

25 января 2023 г.

androidx.activity:activity:1.7.0-alpha04 , androidx.activity:activity-compose:1.7.0-alpha04 , and androidx.activity:activity-ktx:1.7.0-alpha04 are released. Version 1.7.0-alpha04 contains these commits.

Новые функции

  • The PickVisualMedia and PickMultipleVisualMedia Activity Result contracts will now use a Google Play services provided Photo Picker where available in cases where the Android system provided Photo Picker (eg, MediaStore.ACTION_PICK_IMAGES ) is not available. The isPhotoPickerAvailable() API that only detects the Android system provided Photo Picker has been deprecated. It is recommended to use the new isPhotoPickerAvailable(Context) API, which will return if either Photo Picker is available. ( I55be6 )

Version 1.7.0-alpha03

11 января 2023 г.

androidx.activity:activity:1.7.0-alpha03 , androidx.activity:activity-compose:1.7.0-alpha03 , and androidx.activity:activity-ktx:1.7.0-alpha03 are released. Version 1.7.0-alpha03 contains these commits.

Новые функции

  • ComponentDialog now implements SavedStateRegistryOwner and has access to its own SavedStateRegistry and sets the SavedStateRegistryOwner for its ViewTree. It is now possible to use Jetpack Compose within a ComponentDialog as it meets both the LifecycleOwner and SavedStateRegistryOwner attached to the Window via the ViewTree APIs requirements. ( Idca17 , I73468 b/261162296 )

Изменения в API

  • Added a ReportDrawn composable that immediately marks the activity as ready to call reportFullyDrawn . ( Ic5b14 , b/259687964 )

Kotlin Conversions

  • The ActvitiyResultCallback and OnBackPressedCallback classes have both been converted to Kotlin while maintaining source and binary compatibility. ( Ifc5e5 , Ide1b0 , b/257291701 )

Version 1.7.0-alpha02

24 октября 2022 г.

androidx.activity:activity:1.7.0-alpha02 , androidx.activity:activity-compose:1.7.0-alpha02 , and androidx.activity:activity-ktx:1.7.0-alpha02 are released. Version 1.7.0-alpha02 contains these commits.

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

  • From Activity 1.6.1 : Fixed an issue with the PickMultipleVisualMedia Activity Result contract not launching on Android R devices when using the default value for maxItems . ( Ie2776 , b/249182130 )

Version 1.7.0-alpha01

5 октября 2022 г.

androidx.activity:activity:1.7.0-alpha01 , androidx.activity:activity-compose:1.7.0-alpha01 , and androidx.activity:activity-ktx:1.7.0-alpha01 are released. Version 1.7.0-alpha01 contains these commits.

FullyDrawnReporter APIs

ComponentActivity now provides a FullyDrawnReporter instance that allows multiple components to report when they are ready for interaction. ComponentActivity will wait for all components to complete before calling reportFullyDrawn() on your behalf. These APIs take care of the timing requirements for you and do not need to be called as part of an onDraw call.

These APIs are encouraged to enable:

  • Signaling the Android Runtime when startup completes, to ensure all of the code run during a multi-frame startup sequence is included and prioritized for background compilation.
  • Signaling Macrobenchmark and Play Vitals when your application should be considered fully drawn for startup metrics, so you can track performance.

Two Activity Compose APIs have been added to make it more convenient to use the FullyDrawnReporter from individual composables:

  • ReportDrawnWhen takes a predicate (ie, list.count > 0 ) to indicate when your composable is ready for interaction.
  • ReportDrawnAfter takes a suspending method that, when it completes, indicates that you are ready for interaction.

Версия 1.6.1

Версия 1.6.1

24 октября 2022 г.

androidx.activity:activity:1.6.1 , androidx.activity:activity-compose:1.6.1 , and androidx.activity:activity-ktx:1.6.1 are released. Version 1.6.1 contains these commits.

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

  • Fixed an issue with the PickMultipleVisualMedia Activity Result contract not launching on Android R devices when using the default value for maxItems . ( Ie2776 , b/249182130 )

Версия 1.6.0

Версия 1.6.0

21 сентября 2022 г.

androidx.activity:activity:1.6.0 , androidx.activity:activity-compose:1.6.0 , and androidx.activity:activity-ktx:1.6.0 are released. Version 1.6.0 contains these commits.

Important changes since 1.5.0

  • Added ActivityResultContracts.PickVisualMedia and ActivityResultContracts.PickMultipleVisualMedia for providing a backward compatible contract that uses MediaStore.ACTION_PICK_IMAGES when the Photo Picker is available and Intent.ACTION_OPEN_DOCUMENT when it is not available.
  • Integrated the OnBackInvokedCallback in Android 13 into the OnBackPressedDispatchers provided by ComponentActivity and ComponentDialog . This ensures that all APIs built on OnBackPressedDispatcher work when enabling a predictive back gesture .

Version 1.6.0-rc02

7 сентября 2022 г.

androidx.activity:activity:1.6.0-rc02 , androidx.activity:activity-compose:1.6.0-rc02 , and androidx.activity:activity-ktx:1.6.0-rc02 are released. Version 1.6.0-rc02 contains these commits.

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

  • OnBackPressedDispatcher now registers the OnBackInvokedCallback with the PRIORITY_DEFAULT instead of PRIORITY_OVERLAY . ( I3901f )
  • Classes that extend ComponentActivity will now always have both of their onMultiWindowModeChanged() callbacks dispatched. ( Ic4d85 )
  • The ActivityResultRegistry will no longer return a result to the ActivityResultCallback when the launch call throws any Exception and the callback was registered without a LifecycleOwner . ( Ia7ff7 , b/238350794 )
  • ComponentActivity will now properly dispatch menu calls without the need to call the super function in your activity. ( Ie33c5 , b/238057118 )

Dependency Update

Version 1.6.0-rc01

24 августа 2022 г.

androidx.activity:activity:1.6.0-rc01 , androidx.activity:activity-compose:1.6.0-rc01 , and androidx.activity:activity-ktx:1.6.0-rc01 are released. Version 1.6.0-rc01 contains these commits.

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

  • Initializing an OnBackPressedDispatcher will no longer cause ClassVerificationError s when using SDK versions prior to 33. ( Ic32e1 )
  • Classes that override ComponentActivity 's onPictureInPictureModeChanged() callback will now always have their callbacks dispatched. ( Ib7fdb )

Version 1.6.0-beta01

10 августа 2022 г.

androidx.activity:activity:1.6.0-beta01 , androidx.activity:activity-compose:1.6.0-beta01 , and androidx.activity:activity-ktx:1.6.0-beta01 are released. Version 1.6.0-beta01 contains these commits.

Изменения в API

  • Marked the deprecated startActivityForResult and startIntentSenderForResult methods on ComponentActivity with @NonNull because passing null has always resulted in a crash. ( Id2a25 , b/231476082 )

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

  • From Activity 1.5.1 : The ActivityResultRegistry will no longer return a result to the ActivityResultCallback when the launch call throws any Exception and the callback was registered without a LifecycleOwner . ( Ia7ff7 , b/238350794 )
  • From Activity 1.5.1 : ComponentActivity will now properly dispatch menu calls to onPrepareOptionMenu() , onCreateOptionsMenu() and onOptionsItemSelected() overrides without the need to call the super function. ( Ie33c5 , b/238057118 )

Dependency Update

Version 1.6.0-alpha05

15 июня 2022 г.

androidx.activity:activity:1.6.0-alpha05 , androidx.activity:activity-compose:1.6.0-alpha05 , and androidx.activity:activity-ktx:1.6.0-alpha05 are released. Version 1.6.0-alpha05 was developed in a private pre-release branch and has no public commits.

Изменения в API

  • minCompileSdk is now 33 to align with Tiramisu Beta 3 SDK

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

  • Fixed crash on older devices when doing SDK extension check for the PickVisualMedia ActivityResultContract so that it should now work with ACTION_OPEN_DOCUMENT on devices running Android 10 and lower.

Version 1.6.0-alpha04

18 мая 2022 г.

androidx.activity:activity:1.6.0-alpha04 and androidx.activity:activity-ktx:1.6.0-alpha04 are released.

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

  • Fixed an error in PickVisualMediaRequest where attempting to create a request, either via the Builder or the top level Kotlin function, would result in a stack overflow.
  • Integrated the OnBackInvokedCallback in Android 13 Dev Beta 2 into the OnBackPressedDispatcher provided by ComponentDialog . This ensures that all APIs built on OnBackPressedDispatcher work when enabling a predictive back gesture .

Версия 1.6.0-alpha03

27 апреля 2022 г.

androidx.activity:activity:1.6.0-alpha03 , androidx.activity:activity-compose:1.6.0-alpha03 , and androidx.activity:activity-ktx:1.6.0-alpha03 are released.

  • Note: This version will only compile against the Android 13 Developer Beta 1 SDK.

Новые функции

  • Added ActivityResultContracts.PickVisualMedia and ActivityResultContracts.PickMultipleVisualMedia for providing a backward compatible contract that uses MediaStore.ACTION_PICK_IMAGES when the Photo Picker is available and Intent.ACTION_OPEN_DOCUMENT when it is not available.
  • Integrated the OnBackInvokedCallback in Android 13 Dev Beta 1 into the OnBackPressedDispatcher provided by ComponentActivity . This ensures that all APIs built on OnBackPressedDispatcher work when enabling a predictive back gesture .

Версия 1.6.0-alpha01

23 марта 2022 г.

androidx.activity:activity:1.6.0-alpha01 , androidx.activity:activity-compose:1.6.0-alpha01 , and androidx.activity:activity-ktx:1.6.0-alpha01 are released.

  • Note: This version will only compile against the Android 13 Developer Preview 2 SDK.

Новые функции

  • Integrated changes in Android 13 Dev Preview 2 into ComponentActivity .

Версия 1.5.1

Версия 1.5.1

27 июля 2022 г.

androidx.activity:activity:1.5.1 , androidx.activity:activity-compose:1.5.1 , and androidx.activity:activity-ktx:1.5.1 are released. Version 1.5.1 contains these commits.

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

  • The ActivityResultRegistry will no longer return a result to the ActivityResultCallback when the launch() call throws any Exception and the callback was registered without a LifecycleOwner . ( Ia7ff7 , b/238350794 )

  • ComponentActivity will now properly dispatch menu calls to onPrepareOptionMenu() , onCreateOptionsMenu() and onOptionsItemSelected() overrides without the need to call the super function. ( Ie33c5 , b/238057118 )

Dependency update

Версия 1.5.0

Версия 1.5.0

29 июня 2022 г.

androidx.activity:activity:1.5.0 , androidx.activity:activity-compose:1.5.0 , and androidx.activity:activity-ktx:1.5.0 are released. Version 1.5.0 contains these commits.

Важные изменения по сравнению с версией 1.4.0

  • ComponentDialog - ComponentDialog is a subclass of Dialog that includes an OnBackPressedDispatcher that will be called when the system back button is pressed and the dialog is visible. Importantly, this subclass also sets the ViewTreeOnBackPressedDispatcherOwner , allowing views a generic way to retrieve the correct dispatcher whether it exists in a ComponentActivity or a ComponentDialog .
  • Callback Interfaces - ComponentActivity now implements a set of modular callback interfaces that can be used instead of the Activity callbacks. These interfaces include the following: OnNewIntentProvider , OnConfigurationChangedProvider , OnTrimMemoryProvider , OnPictureInPictureModeChangedProvider , OnMultiWindowModeChangedProvider
  • CreationExtras Integration - ComponentActivity now has the ability to provide a stateless ViewModelProvider.Factory via Lifecycle 2.5.0 's CreationExtras .

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

  • The no parameter constructor for ActivityResultContracts.CreateDocument has been deprecated and replaced with a new constructor that takes a concrete mime type (eg, "image/png") as is required by Intent.ACTION_CREATE_DOCUMENT .

Версия 1.5.0-rc01

11 мая 2022 г.

androidx.activity:activity:1.5.0-rc01 , androidx.activity:activity-compose:1.5.0-rc01 , and androidx.activity:activity-ktx:1.5.0-rc01 are released with no changes from 1.5.0-beta01. Version 1.5.0-rc01 contains these commits.

Версия 1.5.0-beta01

20 апреля 2022 г.

androidx.activity:activity:1.5.0-beta01 , androidx.activity:activity-compose:1.5.0-beta01 , and androidx.activity:activity-ktx:1.5.0-beta01 are released. Version 1.5.0-beta01 contains these commits.

Dependency updates

Версия 1.5.0-alpha05

April 6, 2022

androidx.activity:activity:1.5.0-alpha05 , androidx.activity:activity-compose:1.5.0-alpha05 , and androidx.activity:activity-ktx:1.5.0-alpha05 are released. Version 1.5.0-alpha05 contains these commits.

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

  • ComponentActivity 's onPanelClosed() now calls the super onPanelClosed() as well, fixing an issue where the onContextMenuClosed method would not be called. ( Ib6f77 )

Версия 1.5.0-alpha04

23 марта 2022 г.

androidx.activity:activity:1.5.0-alpha04 , androidx.activity:activity-compose:1.5.0-alpha04 , and androidx.activity:activity-ktx:1.5.0-alpha04 are released. Version 1.5.0-alpha04 contains these commits.

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

  • SavedStateViewFactory now supports using CreationExtras even when it was initialized with a SavedStateRegistryOwner . If extras are provided, the initialized arguments are ignored. ( I6c43b , b/224844583 )

Версия 1.5.0-alpha03

23 февраля 2022 г.

androidx.activity:activity:1.5.0-alpha03 , androidx.activity:activity-compose:1.5.0-alpha03 , and androidx.activity:activity-ktx:1.5.0-alpha03 are released. Version 1.5.0-alpha03 contains these commits.

Изменения в API

  • You can now pass CreationExtras to the activity by viewModels() function ( I6a3e6 , b/217600303 )

Версия 1.5.0-alpha02

9 февраля 2022 г.

androidx.activity:activity:1.5.0-alpha02 , androidx.activity:activity-compose:1.5.0-alpha02 , and androidx.activity:activity-ktx:1.5.0-alpha02 are released. Version 1.5.0-alpha02 contains these commits.

Новые функции

  • ComponentActivity now implements the OnPictureInPictureModeChangedProvider interface to allow any component to receive picture-in-picture mode change events. ( I9f567 )
  • ComponentActivity now implements the OnMultiWindowModeChangedProvider interface to allow any component to receive multi-window mode change events. ( I62d91 )

Версия 1.5.0-alpha01

26 января 2022 г.

androidx.activity:activity:1.5.0-alpha01 , androidx.activity:activity-compose:1.5.0-alpha01 , and androidx.activity:activity-ktx:1.5.0-alpha01 are released. Version 1.5.0-alpha01 contains these commits.

Новые функции

  • ComponentActivity now integrates with ViewModel CreationExtras, introduced as part of Lifecycle 2.5.0-alpha01 . ( Ie7e00 , b/207012584 )
  • Added ComponentDialog , a subclass of Dialog that includes an OnBackPressedDispatcher that will be called when the system back button is pressed when the dialog is visible. Importantly, this subclass also sets the ViewTreeOnBackPressedDispatcherOwner , allowing views a generic way to retrieve the correct dispatcher whether it exists in a ComponentActivity or a ComponentDialog . ( I8a1bc )
  • ComponentActivity now implements the new OnNewIntentProvider interface to allow any component to receive these events. ( If1f8b )
  • ComponentActivity now implements the new OnConfigurationChangedProvider interface to allow any component to receive these events. ( If623b )
  • ComponentActivity now implements the new OnTrimMemoryProvider interface to allow any component to receive these events. ( Ia9295 )

Изменения в API

  • The no parameter constructor for ActivityResultContracts.CreateDocument has been deprecated and replaced with a new constructor that takes a concrete mime type (eg, "image/png" ) as is required by Intent.ACTION_CREATE_DOCUMENT . ( I2bec6 )
  • The OnBackPressedDispatcherOwner associated with a View can now be retrieved via the ViewTreeOnBackPressedDispatcherOwner , rather than relying on casting the Context . ( I74685 )

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

  • Fixed a crash when accessing a ViewModel for the very first time from a registerForActivityResult() callback or the callbacks to a LifecycleObserver added as part of init of a ComponentActivity . ( Ife83f )

Версия 1.4.0

Версия 1.4.0

27 октября 2021 г.

androidx.activity:activity:1.4.0 , androidx.activity:activity-compose:1.4.0 , and androidx.activity:activity-ktx:1.4.0 are released. Version 1.4.0 contains these commits.

Важные изменения по сравнению с версией 1.3.0

  • AndroidX ComponentActivity now implements the MenuHost interface. This allows any component to add menu items to the ActionBar by adding a MenuProvider instance to the activity. Each MenuProvider can optionally be added with a Lifecycle that will automatically control the visibility of those menu items based on the Lifecycle state and handle the removal of the MenuProvider when the Lifecycle is destroyed.
  • The ActivityResultContract class has been rewritten in Kotlin to ensure that developers writing custom contracts in Kotlin can define the correct nullability for their input and output classes.
  • The ActivityResultContracts class and its contracts have been rewritten in Kotlin to ensure the proper nullability.

Версия 1.4.0-rc01

13 октября 2021 г.

androidx.activity:activity:1.4.0-rc01 , androidx.activity:activity-compose:1.4.0-rc01 , and androidx.activity:activity-ktx:1.4.0-rc01 are released. Version 1.4.0-rc01 contains these commits.

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

  • The ActivityResultRegistry will no longer return a result to the ActivityResultCallback when the launch call throws any Exception . ( If4f91 , b/200845664 )

Версия 1.4.0-beta01

29 сентября 2021 г.

androidx.activity:activity:1.4.0-beta01 , androidx.activity:activity-compose:1.4.0-beta01 , and androidx.activity:activity-ktx:1.4.0-beta01 are released. Version 1.4.0-beta01 contains these commits.

Изменения в API

  • Fixed the type for the ActivityResultContracts.OpenMultipleDocuments and ActivityResultContracts.GetMultipleContents that caused then to use an output type of List<? extends Uri> when using the code from the Java programming language. ( If71de )
  • Public constants within the ActivityResultContracts.StartActivityForResult , ActivityResultContracts.StartIntentSenderForResult , and ActivityResultContracts.RequestMultiplePermissions classes are now accessible when using Kotlin via their now public Companion objects. ( aosp/1832555 )

Documentation Updates

  • The deprecation message for APIs now handled by the Activity Result APIs , namely startActivityForResult , startIntentSenderForResult , onActivityResult , requestPermissions , and onRequestPermissionsResult , have all been expanded with more details. ( cce80f )

Версия 1.4.0-alpha02

15 сентября 2021 г.

androidx.activity:activity:1.4.0-alpha02 , androidx.activity:activity-compose:1.4.0-alpha02 , and androidx.activity:activity-ktx:1.4.0-alpha02 are released. Version 1.4.0-alpha02 contains these commits.

Новые функции

  • The activity-compose artifact now contains a LaunchDuringComposition lint error that prevents you from calling the launch method of ActivityResultLauncher as part of composition as composition should be side-effect free. Use the APIs for handling side-effects . ( 7c2bbe , b/191347220 )

Изменения в API

  • The ActivityResultContract class has been rewritten in Kotlin to ensure that developers writing custom contracts in Kotlin can define the correct nullability for their input and output classes. ( I8a8f5 )
  • The ActivityResultContracts class and its contracts have been rewritten in Kotlin to ensure the proper nullability. ( I69802 )

Версия 1.4.0-alpha01

1 сентября 2021 г.

androidx.activity:activity:1.4.0-alpha01 , androidx.activity:activity-compose:1.4.0-alpha01 , and androidx.activity:activity-ktx:1.4.0-alpha01 are released. Version 1.4.0-alpha01 contains these commits.

Новые функции

  • AndroidX ComponentActivity now implements the MenuHost interface.. This allows any component to add menu items to the ActionBar by adding a MenuProvider instance to the activity. Each MenuProvider can optionally be added with a Lifecycle that will automatically control the visibility of those menu items based on the Lifecycle state and handle the removal of the MenuProvider when the Lifecycle is destroyed. ( I3b608 ):
/**
  * Using the addMenuProvider() API directly in your Activity
  **/
class ExampleActivity : ComponentActivity(R.layout.activity_example) {

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    // Add menu items without overriding methods in the Activity
   addMenuProvider(object : MenuProvider {
      override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
        // Add menu items here
        menuInflater.inflate(R.menu.example_menu, menu)
      }

      override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
        // Handle the menu selection
        return true
      }
    })
  }
}

/**
  * Using the addMenuProvider() API in a Fragment
  **/
class ExampleFragment : Fragment(R.layout.fragment_example) {

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    // The usage of an interface lets you inject your own implementation
    val menuHost: MenuHost = requireActivity()
  
    // Add menu items without using the Fragment Menu APIs
    // Note how we can tie the MenuProvider to the viewLifecycleOwner
    // and an optional Lifecycle.State (here, RESUMED) to indicate when
    // the menu should be visible
    menuHost.addMenuProvider(object : MenuProvider {
      override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
        // Add menu items here
        menuInflater.inflate(R.menu.example_menu, menu)
      }

      override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
        // Handle the menu selection
        return true
      }
    }, viewLifecycleOwner, Lifecycle.State.RESUMED)
  }

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

  • The ActivityResultRegistry will now throw an IllegalStateException when attempting to call launch() on an ActivityResultLauncher that has not be registered or that has been unregistered. ( Ida75d , b/192567522 )

Внешний вклад

  • Thanks dmitrilc for fixing a typo in the ActivityResult documentation. ( #221 )

Версия 1.3.1

Версия 1.3.1

4 августа 2021 г.

androidx.activity:activity:1.3.1 , androidx.activity:activity-compose:1.3.1 , and androidx.activity:activity-ktx:1.3.1 are released. Version 1.3.1 contains these commits.

Dependency updates

  • Activity now depends on Kotlin 1.5.21 .
  • Activity Compose now depends on Compose 1.0.1 .

Версия 1.3.0

Версия 1.3.0

28 июля 2021 г.

androidx.activity:activity:1.3.0 , androidx.activity:activity-compose:1.3.0 , and androidx.activity:activity-ktx:1.3.0 are released. Version 1.3.0 contains these commits.

Важные изменения по сравнению с версией 1.2.0

  • Activity Compose artifact - The activity-compose artifact provides the setContent extension method for hosting your Jetpack Compose UI in an activity and Compose specific wrappers for interacting with the ComponentActivity APIs for handling the system back button and the Activity Result APIs. See the documentation for more details.
  • CaptureVideo contract - The CaptureVideo ActivityResultContract replaces the now deprecated TakeVideo contract and returns a boolean denoting success that works across many camera apps.
  • Picture-In-Picture Hint View Tracking - Users of activity-ktx can now use the trackPipAnimationHintView extension method on Activity to automatically rebuild the PictureInPictureParams with the new position of the view as it changes position relative to the window.

Version 1.3.0-rc02

14 июля 2021 г.

androidx.activity:activity:1.3.0-rc02 , androidx.activity:activity-compose:1.3.0-rc02 , and androidx.activity:activity-ktx:1.3.0-rc02 are released. Version 1.3.0-rc02 contains these commits.

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

  • The ActivityResultRegistry callbacks are now properly saved and restored so callbacks are not duplicated in the savedState. ( I97816 , b/191893160 )

Версия 1.3.0-rc01

1 июля 2021 г.

androidx.activity:activity:1.3.0-rc01 , androidx.activity:activity-compose:1.3.0-rc01 , and androidx.activity:activity-ktx:1.3.0-rc01 are released with no changes from 1.3.0-beta02 . Version 1.3.0-rc01 contains these commits.

Версия 1.3.0-beta02

16 июня 2021 г.

androidx.activity:activity:1.3.0-beta02 , androidx.activity:activity-compose:1.3.0-beta02 , and androidx.activity:activity-ktx:1.3.0-beta02 are released. Version 1.3.0-beta02 contains these commits.

Updated activity-compose to depend on Compose 1.0.0-beta09 . androidx.compose.ui:ui-test-junit4 now has a compile time dependency on activity-compose .

Версия 1.3.0-beta01

2 июня 2021 г.

androidx.activity:activity:1.3.0-beta01 , androidx.activity:activity-compose:1.3.0-beta01 , and androidx.activity:activity-ktx:1.3.0-beta01 are released. Version 1.3.0-beta01 contains these commits.

Изменения в API

  • The previously deprecated @Composable registerForActivityResult() method has been removed. Please use rememberLauncherForActivityResult() . ( Ic39d3 )

Version 1.3.0-alpha08

18 мая 2021 г.

androidx.activity:activity:1.3.0-alpha08 , androidx.activity:activity-compose:1.3.0-alpha08 , and androidx.activity:activity-ktx:1.3.0-alpha08 are released. Version 1.3.0-alpha08 contains these commits.

Новые функции

  • The new CaptureVideo ActivityResultContract returns a boolean to your ActivityResultCallback indicating if your video was successfully saved to the given URI. This replaces the now deprecated TakeVideo contract as camera apps very rarely supported returning a thumbnail bitmap, making the result unhelpful. ( Ie21f2 , b/185938070 )
  • Added new API Activity#setPipAnimationHintView to update the PipParams' source rect hint whenever the view moves. ( I9063d )

Изменения в API

  • The rememberLauncherForActivityResult function now returns a launcher that deprecates the unregister() function - registration and unregistering the launcher is handled automatically by rememberLauncherForActivityResult . ( I2443e )

Compose Compatibility

  • androidx.activity:activity-compose:1.3.0-alpha08 is only compatible with Compose version 1.0.0-beta07 and above.

Version 1.3.0-alpha07

21 апреля 2021 г.

androidx.activity:activity:1.3.0-alpha07 , androidx.activity:activity-compose:1.3.0-alpha07 , and androidx.activity:activity-ktx:1.3.0-alpha07 are released. Version 1.3.0-alpha07 contains these commits.

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

  • rememberLauncherForActivityResult now returns a stable reference to the same ActivityResultLauncher instance even if the contract changes due to recompositions. ( Id2d6d )
  • Using unstable versions of Fragments above 1.3.0 will no longer throw a false positive lint error telling you to use 1.3.0 . ( aosp/1670206 , b/184847092 )

Version 1.3.0-alpha06

7 апреля 2021 г.

androidx.activity:activity:1.3.0-alpha06 , androidx.activity:activity-compose:1.3.0-alpha06 , and androidx.activity:activity-ktx:1.3.0-alpha06 are released. Version 1.3.0-alpha06 contains these commits.

Изменения в API

  • The registerForActivityResult() API has been renamed to rememberLauncherForActivityResult() to better indicate that the returned ActivityResultLauncher is a managed object that is remembered on your behalf. Attempting to call unregister the returned ActivityResultLauncher will now throw an error. ( I2bb6d )
  • LocalOnBackPressedDispatcherOwner.current and LocalActivityResultRegistryOwner.current now return a nullable value to better determine whether it is available in the current composition. APIs that requires those APIs, such as BackHandler and rememberLauncherForActivityResult() , respectively, will now throw a more descriptive error if the underlying owner is not found. NavHost now works even when an OnBackPressedDispatcherOwner is not found, such is the case when previewing the NavHost . ( I7d8b4 )

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

  • The BackHandler will now properly intercept back presses in the event that the Activity is STOPPED , then STARTED again, and other callbacks were added with a LifecycleOwner. ( I71de6 , b/182284739 )
  • Using the launch() method extension with a custom ActivityResultContract that has a Unit input will no longer cause a NullPointerException ( I76282 , b/183837954 )

Version 1.3.0-alpha05

24 марта 2021 г.

androidx.activity:activity:1.3.0-alpha05 , androidx.activity:activity-compose:1.3.0-alpha05 , and androidx.activity:activity-ktx:1.3.0-alpha05 are released. Version 1.3.0-alpha05 contains these commits.

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

  • From Activity 1.2.2 : Fixed an issue in the InvalidFragmentVersionForActivityResult lint check that led to a false positive when using Fragment 1.3.1 or higher. ( I54da1 , b/182388985 )
  • From Activity 1.2.2 : ComponentActivity now avoids a ClassNotFoundException when launching an Intent from an ActivityResultContract that was previously held as an extra in another Intent . ( Ieff05 , b/182906230 )

Обновления зависимостей

Версия 1.3.0-alpha04

10 марта 2021 г.

androidx.activity:activity:1.3.0-alpha04 , androidx.activity:activity-compose:1.3.0-alpha04 , and androidx.activity:activity-ktx:1.3.0-alpha04 are released. Version 1.3.0-alpha04 contains these commits.

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

  • From Activity 1.2.1 : RequestMultiplePermissions now always returns results for all requested permissions instead of only permissions that weren't previously granted. ( I50bc3 , b/180884668 )
  • From Activity 1.2.1 : ActivityResultRegistry now ensures that in progress launch() requests will return their results even if you unregister() , then register() again with the same key. ( I9ef34 , b/181267562 )
  • Activity Compose no longer adds test dependencies to the runtime classpath. ( Ifd8b3 )
  • Fixed an issue with BackHandler where the previously set onBack lambda was still being used after recomposition. ( 8eb5eb )

Версия 1.3.0-alpha03

24 февраля 2021 г.

androidx.activity:activity:1.3.0-alpha03 , androidx.activity:activity-compose:1.3.0-alpha03 , and androidx.activity:activity-ktx:1.3.0-alpha03 are released. Version 1.3.0-alpha03 contains these commits.

Новые функции

  • There is a now a Composable registerForActivityResult function for getting results from activities within composables. ( Ia7851 , b/172690553 )

Изменения в API

  • LocalOnBackPressedDispatcherOwner now has a provides functions that can be used with CompositionLocalProvider , replacing the asProvidableCompositionLocal() API. ( I45d24 )

Версия 1.3.0-alpha02

10 февраля 2021 г.

androidx.activity:activity:1.3.0-alpha02 , androidx.activity:activity-compose:1.3.0-alpha02 , and androidx.activity:activity-ktx:1.3.0-alpha02 are released. Version 1.3.0-alpha02 contains these commits.

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

  • Fixed an issue in Activity Compose 1.3.0-alpha01 that causes a NoSuchMethodError: No static method setContent exception when using Compose 1.0.0-alpha12 . All Compose users should depend on 1.3.0-alpha02 and above. ( b/179911234 )

Изменения в API

  • The BackHandler API can be used to allow a Composable to intercept the system back button. ( I58ed5 , b/172154006 )

Версия 1.3.0-alpha01

10 февраля 2021 г.

androidx.activity:activity:1.3.0-alpha01 , androidx.activity:activity-compose:1.3.0-alpha01 , and androidx.activity:activity-ktx:1.3.0-alpha01 are released. Version 1.3.0-alpha01 contains these commits.

Новые функции

  • The new activity-compose artifact provides Jetpack Compose specific helpers for androidx.activity specific APIs.
    • ComponentActivity.setContent has moved from androidx.compose.ui.platform.setContent to androidx.activity.compose.setContent . ( Icf416 )

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

  • Using Activity Compose 1.3.0-alpha01 and libraries that depend on it, such as androidx.compose.ui:ui-test-junit4:1.0.0-alpha12 , will result in a NoSuchMethodError: No static method setContent exception. ( b/179911234 )

Версия 1.2.4

Версия 1.2.4

21 июля 2021 г.

androidx.activity:activity:1.2.4 and androidx.activity:activity-ktx:1.2.4 are released. Version 1.2.4 contains these commits.

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

Версия 1.2.3

Версия 1.2.3

5 мая 2021 г.

androidx.activity:activity:1.2.3 and androidx.activity:activity-ktx:1.2.3 are released. Version 1.2.3 contains these commits.

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

  • Using the launch() method extension with a custom ActivityResultContract that has a Unit input will no longer cause a NullPointerException ( I76282 , b/183837954 )
  • Fixed a false positive lint error telling you to use Fragment 1.3.0 when using an snapshot, alpha, beta, or RC build of a newer version of Fragments. ( f4a57e , b/184847092 )

Версия 1.2.2

Версия 1.2.2

24 марта 2021 г.

androidx.activity:activity:1.2.2 and androidx.activity:activity-ktx:1.2.2 are released. Version 1.2.2 contains these commits.

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

  • Fixed an issue in the InvalidFragmentVersionForActivityResult lint check that led to a false positive when using Fragment 1.3.1 or higher. ( I54da1 , b/182388985 )
  • ComponentActivity now avoids a ClassNotFoundException when launching an Intent from an ActivityResultContract that was previously held as an extra in another Intent . ( Ieff05 , b/182906230 )

Обновления зависимостей

Версия 1.2.1

Версия 1.2.1

10 марта 2021 г.

androidx.activity:activity:1.2.1 and androidx.activity:activity-ktx:1.2.1 are released. Version 1.2.1 contains these commits.

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

  • RequestMultiplePermissions now always returns results for all requested permissions instead of only permissions that weren't previously granted. ( I50bc3 , b/180884668 )
  • ActivityResultRegistry now ensures that in progress launch() requests will return their results even if you unregister() , then register() again with the same key. ( I9ef34 , b/181267562 )

Версия 1.2.0

Версия 1.2.0

10 февраля 2021 г.

androidx.activity:activity:1.2.0 and androidx.activity:activity-ktx:1.2.0 are released. Version 1.2.0 contains these commits.

Major changes since 1.1.0

  • Activity Result APIs : ComponentActivity now provides an ActivityResultRegistry that lets you handle startActivityForResult() + onActivityResult() as well as requestPermissions() + onRequestPermissionsResult() flows without overriding methods in your Activity or Fragment, brings increased type safety via ActivityResultContract , and provides hooks for testing these flows. See the updated Getting a Result from an Activity .
  • ContextAware : ComponentActivity now implements ContextAware , allowing you to add one or more OnContextAvailableListener instances which will receive a callback before the base Activity.onCreate() .

    • A suspending Kotlin extension withContextAvailable() allows you to run a non-suspending block when the Context becomes available and return a result.
    • This API is used by FragmentActivity in Fragment 1.3.0 to restore the state of the FragmentManager . Any listeners added to subclasses of FragmentActivity will run after that listener.
    • This API is used by AppCompatActivity in AppCompat 1.3.0-alpha02 or higher. Any listeners added to subclasses of AppCompatActivity will run after that listener.
  • ViewTree Support : ComponentActivity now supports the ViewTreeLifecycleOwner.get(View) , ViewTreeViewModelStoreOwner.get(View) , and ViewTreeSavedStateRegistryOwner APIs added in Lifecycle 2.3.0 and SavedState 1.1.0 such that it will return the Activity as the LifecycleOwner , ViewModelStoreOwner , and SavedStateRegistryOwner for any Views directly added to the ComponentActivity .

  • reportFullyDrawn() backport - The Activity method of reportFullyDrawn() has been backported in ComponentActivity to work on all API levels, fixing a crash on API 19 and adding tracing for this method for all API levels.

Версия 1.2.0-rc01

16 декабря 2020 г.

androidx.activity:activity:1.2.0-rc01 and androidx.activity:activity-ktx:1.2.0-rc01 are released. Version 1.2.0-rc01 contains these commits.

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

  • The ActivityResultRegistry now always restores the exact state that was saved. ( Idd56b )
  • Add tracing to ComponentActivity.reportFullyDrawn ( Ic7632 )

Внешний вклад

  • ComponentActivity now overrides reportFullyDrawn() , allowing it to be called on all API levels and fixing a crash when calling this method without the appropriate system permission on API 19 devices. Thanks Simon Schiller! ( b/163239764 , #103 )

Version 1.2.0-beta02

2 декабря 2020 г.

androidx.activity:activity:1.2.0-beta02 and androidx.activity:activity-ktx:1.2.0-beta02 are released. Version 1.2.0-beta02 contains these commits.

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

  • Fixed an issue where the Activity Result API would not wait for the Lifecycle to be STARTED before delivering results when registered with a Lifecycle . ( I109ea )

Внешний вклад

  • Updated the documentation for launch() to explicitly call out that it can throw an ActivityNotFoundException . Thanks Michał Zieliński! ( aosp/1493580 )

Версия 1.2.0-beta01

1 октября 2020 г.

androidx.activity:activity:1.2.0-beta01 and androidx.activity:activity-ktx:1.2.0-beta01 are released. Version 1.2.0-beta01 contains these commits.

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

  • The ActivityResultRegistry now randomly generates integers until it finds one that is unallocated to use as a request code register() , thus preventing the possible integer overflow caused by incrementing request codes. ( b/168779518 )

  • Lifecycle observers are properly removed when calling unregister() on an ActivityResultLauncher . ( b/165608393 )

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

  • The ActivityResultRegistry now throws an IllegalStateException when attempting to call register() with a LifecycleOwner whose Lifecycle has already reached STARTED . ( b/165435866 )

Documentation Updated

  • ContextAware documentation links to LifecycleOwner to highlight Lifecycle callbacks as the appropriate place for creation and destruction events. ( aosp/1414152 )

Version 1.2.0-alpha08

19 августа 2020 г.

androidx.activity:activity:1.2.0-alpha08 and androidx.activity:activity-ktx:1.2.0-alpha08 are released. Version 1.2.0-alpha08 contains these commits.

Новые функции

  • ComponentActivity now implements ContextAware , allowing you to add one or more OnContextAvailableListener instances which will receive a callback before the base Activity.onCreate() . ( b/161390636 )
    • A suspending Kotlin extension withContextAvailable() allows you to run a non-suspending block when the Context becomes available and return a result. ( I8290c )
    • This API is used by FragmentActivity in Fragment 1.3.0-alpha08 to restore the state of the FragmentManager . Any listeners added to subclasses of FragmentActivity will run after that listener. ( I513da )
    • This API is used by AppCompatActivity in AppCompat 1.3.0-alpha02 . Any listeners added to subclasses of AppCompatActivity will run after that listener. ( I513da )

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

  • Fixed an issue with the ActivityResultFragmentVersionDetector Lint check that caused it to break when using Lint 27.1.0 or higher. ( b/162155191 )

Версия 1.2.0-alpha07

22 июля 2020 г.

androidx.activity:activity:1.2.0-alpha07 and androidx.activity:activity-ktx:1.2.0-alpha07 are released. Version 1.2.0-alpha07 contains these commits.

Новые функции

  • Added a new InvalidFragmentVersionForActivityResult lint check that verifies that you are using Fragment 1.3.0-alpha07 when using the Activity Result API , avoiding runtime crashes due to “invalid request code” issues and non-functioning permission requests caused by using older versions of Fragments. ( b/152554847 )

Внешний вклад

  • Fixed an ArrayIndexOutOfBoundsException when parsing the results for the RequestPermission Activity Result contract. ( I8f9e3 , b/161057605 )

Версия 1.2.0-alpha06

10 июня 2020 г.

androidx.activity:activity:1.2.0-alpha06 and androidx.activity:activity-ktx:1.2.0-alpha06 are released. Version 1.2.0-alpha06 contains these commits.

Новые функции

  • You can now destructure the ActivityResult class in kotlin to directly access the requestCode and intent . ( b/157212935 )
  • ActivityResultLauncher now allows you to get the ActivityResultContract that was used to register the launcher. ( b/156875743 )

Изменения в API

  • Breaking change : The invoke() method on ActivityResultRegistry has been renamed to onLaunch() . ( b/157496491 )
  • The OpenMultipleDocuments contract now returns an empty list instead of null to the registered callback if no result is returned. ( b/157348014 )

Версия 1.2.0-alpha05

20 мая 2020 г.

androidx.activity:activity:1.2.0-alpha05 and androidx.activity:activity-ktx:1.2.0-alpha05 are released. Version 1.2.0-alpha05 contains these commits.

Новые функции

Изменения в API

  • The TakePicture contract now returns a boolean indicating success rather than a thumbnail Bitmap as this was very rarely supported by camera apps when writing the image to the provided Uri . ( b/154302879 )
  • The invoke() extensions on ActivityResultLauncher have been removed in favor of explicitly using launch() to better indicate that these are asynchronous operations. Kotlin extensions for launch have been added to the androidx.activity.result package for ActivityResultLauncher<Void> and ActivityResultLauncher<Unit> that remove the need to pass in null or Unit , respectively, mirroring that behavior from the previously invoke() extensions. ( aosp/1304674 , aosp/1304675 )
  • The IntentSenderRequest.Builder methods for setFlagsMask() and setFlagsValues() has been combined into a single setFlags() method. ( aosp/1302111 )

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

  • When registering an ActivityResultCallback with a LifecycleOwner , fixed an issue where the callback would be triggered before the state reaches STARTED . ( aosp/1309744 )

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

  • The ActivityResultRegistry now generates request codes starting at 0xFFFF rather than at 0 , preventing overlap when using startActivityForResult() or requestPermissions() in an activity. ( aosp/1302324 )

Версия 1.2.0-alpha04

29 апреля 2020 г.

androidx.activity:activity:1.2.0-alpha04 and androidx.activity:activity-ktx:1.2.0-alpha04 are released. Version 1.2.0-alpha04 contains these commits.

Новые функции

  • Added a contract that can call startIntentSenderForResult to the ActivityResult APIs. ( b/153007517 )

Изменения в API

  • The prepareCall() method has been renamed to registerForActivityResult() , both on ComponentActivity here and in Fragment 1.3.0-alpha04 . ( aosp/1278717 )
  • The GetContents , OpenDocuments , and RequestPermissions contracts have been renamed to GetMultipleContents , OpenMultipleDocuments , and RequestMultiplePermissions , respectively. ( aosp/1280161 )
  • ComponentActivity now implements the ActivityResultRegisteryOwner interface. ( aosp/1290888 )
  • - The startActivityForResult() / onActivityResult() and onRequestPermissionsResult() APIs on ComponentActivity have been deprecated. Please use the Activity Result APIs . ( b/154751887 )

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

  • When using the GetMultipleContents and OpenMultipleDocuments contracts and selecting a single item, it is now correctly returned to your callback. ( b/152941153 )

Версия 1.2.0-alpha03

1 апреля 2020 г.

androidx.activity:activity:1.2.0-alpha03 and androidx.activity:activity-ktx:1.2.0-alpha03 are released. Version 1.2.0-alpha03 contains these commits.

Новые функции

  • Added the TakeVideo , PickContact , GetContent , GetContents , OpenDocument , OpenDocuments , OpenDocumentTree , and CreateDocument contracts to the set of pre-built contracts provided by ActivityResultContracts . ( aosp/1262482 , aosp/1266916 , aosp/1268960 )
  • The Activity Result APIs now support launching an activity for result with an optional ActivityOptionsCompat . ( b/151860054 )

Изменения в API

  • The TakePicture contract now takes a Uri input for where the image should be stored. The previous contract that does not take any input has been renamed to TakePicturePreview . ( aosp/1262482 )
  • The registerActivityResultCallback() method on ActivityResultRegistry has been renamed to register() . ( aosp/1267621 )
  • The dispose() method on ActivityResultLauncher has been renamed to unregister() and the unregisterResultCallback() on ActivityResultRegistry has been removed. ( aosp/1267621 )
  • The createIntent() method of ActivityResultContact now takes a Context in addition to the input to make it possible to create explicit Intents. ( aosp/1238800 )
  • An ActivityResultContract can now override getSynchronousResult() to deliver a result without calling startActivityForResult . This is used by the RequestPermission and RequestPermissions contracts to correctly deliver a 'granted' status if the requested permissions are already granted. ( b/151110799 )
  • The previously available Dial contract has been removed as that Intent is not meant to be used with startActivityForResult() . ( aosp/1266916 )
  • Many of the Activity Result APIs not meant to be extended are now final . This includes getActivityResultRegistry() , the prepareCall() methods, all methods of ActivityResultRegistry except invoke() , and a number of the default contracts that do not support optional extras. ( b/152439361 )

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

  • Fixed a NullPointerException in ActivityResultRegistry when attempting to deliver results to a callback that has not yet been re-registered after a configuration change; ActivityResultRegistry now holds onto these pending results and delivers them when the callback is re-registered. ( b/152137004 )

Версия 1.2.0-alpha02

18 марта 2020 г.

androidx.activity:activity:1.2.0-alpha02 and androidx.activity:activity-ktx:1.2.0-alpha02 are released. Version 1.2.0-alpha02 contains these commits.

Новые функции

  • ActivityResultRegistry : ComponentActivity now provides an ActivityResultRegistry that lets you handle the startActivityForResult() + onActivityResult() as well as requestPermissions() + onRequestPermissionsResult() flows without overriding methods in your Activity or Fragment, brings increased type safety via ActivityResultContract , and provides hooks for testing these flows. See the updated Getting a Result from an Activity . ( b/125158199 )

Версия 1.2.0-alpha01

4 марта 2020 г.

androidx.activity:activity:1.2.0-alpha01 and androidx.activity:activity-ktx:1.2.0-alpha01 are released. Version 1.2.0-alpha01 contains these commits.

Новые функции

  • Added support for the ViewTreeLifecycleOwner.get(View) API added in Lifecycle 2.3.0-alpha01 such that it will return the Activity as the LifecycleOwner for any Views directly added to the Activity. ( aosp/1182955 )

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

  • Fixed a regression introduced in Activity 1.1.0 when running on older versions of the platform where onBackPressed() would cause an IllegalStateException due to a bug in the android.app.FragmentManager . ( b/146290338 )

Версия 1.1.0

Версия 1.1.0

22 января 2020 г.

androidx.activity:activity:1.1.0 is released. Version 1.1.0 contains these commits .

Важные изменения с версии 1.0.0

  • Lifecycle ViewModel SavedState Integration : SavedStateViewModelFactory is now the default factory used when using by viewModels() , the ViewModelProvider constructor, or ViewModelProviders.of() with a ComponentActivity or its subclasses.

Version 1.1.0-rc03

4 декабря 2019 г.

androidx.activity:activity:1.1.0-rc03 and androidx.activity:activity-ktx:1.1.0-rc03 are released. Version 1.1.0-rc03 contains these commits .

Dependency changes

  • Activity now depends on Lifecycle 2.2.0-rc03 and Lifecycle ViewModel SavedState 1.0.0-rc03 .

Version 1.1.0-rc02

7 ноября 2019 г.

androidx.activity:activity:1.1.0-rc02 and androidx.activity:activity-ktx:1.1.0-rc02 are released. Version 1.1.0-rc02 contains these commits .

Dependency changes

  • Activity now depends on lifecycle 2.2.0-rc02 .

Версия 1.1.0-rc01

23 октября 2019 г.

androidx.activity:activity:1.1.0-rc01 and androidx.activity:activity-ktx:1.1.0-rc01 are released with no changes from 1.1.0-beta01 . Version 1.1.0-rc01 contains these commits .

Версия 1.1.0-beta01

9 октября 2019 г.

androidx.activity:activity:1.1.0-beta01 and androidx.activity:activity-ktx:1.1.0-beta01 are released. Version 1.1.0-beta01 contains these commits .

Dependency changes

  • Activity now depends on SavedState 1.0.0 stable.

Версия 1.1.0-alpha03

5 сентября 2019 г.

androidx.activity:activity:1.1.0-alpha03 and androidx.activity:activity-ktx:1.1.0-alpha03 are released. The commits included in this version can be found here .

Новые функции

  • Activity now depends on Core 1.1.0 stable.

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

Версия 1.1.0-alpha02

7 августа 2019 г.

androidx.activity:activity:1.1.0-alpha02 and androidx.activity:activity-ktx:1.1.0-alpha02 are released. The commits included in this version can be found here .

Новые функции

  • SavedStateViewModelFactory is now the default factory used when using by viewModels() , the ViewModelProvider constructor, or ViewModelProviders.of() with a ComponentActivity ( b/135716331 )

Версия 1.1.0-alpha01

2 июля 2019 г.

androidx.activity:activity:1.1.0-alpha01 and androidx.activity:activity-ktx:1.1.0-alpha01 are released. The commits included in this version can be found here .

Новые функции

  • activity now depends on Lifecycle 2.2.0-alpha02 . ( aosp/1007817 )
  • activity-ktx added a dependency on lifecycle-runtime-ktx ; you no longer need to explicitly add it to your dependencies when using activity-ktx or libraries that depend on activity-ktx (such as fragment-ktx ). ( aosp/987162 )

Версия 1.0.0

Версия 1.0.0

5 сентября 2019 г.

androidx.activity:activity:1.0.0 and androidx.activity:activity-ktx:1.0.0 are released. The commits included in this version can be found here .

Major Features of 1.0.0

  • ComponentActivity : ComponentActivity serves as the new base class for FragmentActivity in Fragment 1.1.0 and, by extension, AppCompatActivity in AppCompat 1.1.0 .
  • activity-ktx : The activity-ktx module includes a by viewModels Kotlin property extension for accessing ViewModels. This module is automatically included when you include fragment-ktx from Fragment 1.1.0 .
  • OnBackPressedDispatcher : As a composable alternative to overriding onBackPressed() , you can now register a OnBackPressedCallback from any LifecycleOwner (such as a fragment) to intercept system back button events. A lambda with receiver version addCallback has been added to activity-ktx . See Provide custom back navigation documentation for more details.
  • onRetainCustomNonConfigurationInstance deprecation : the onRetainCustomNonConfigurationInstance() and the related getLastCustomNonConfigurationInstance() APIs have been deprecated. It is strongly recommended to use ViewModels to store non-configuration state as they offer a composable solution suitable for any ViewModelStoreOwner that makes the ownership of the retained objects clear and provides an onCleared() callback for cleaning up resources when the activity is finally destroyed.

Версия 1.0.0-rc01

2 июля 2019 г.

androidx.activity:activity:1.0.0-rc01 and androidx.activity:activity-ktx:1.0.0-rc01 are released with no changes from 1.0.0-beta01 . The commits included in this version can be found here .

Версия 1.0.0-beta01

5 июня 2019 г.

androidx.activity::activity:1.0.0-beta01 and androidx.activity:activity-ktx:1.0.0-beta01 are released with no changes from 1.0.0-alpha08 . The commits included in this version can be found here .

Версия 1.0.0-alpha08

7 мая 2019 г.

androidx.activity:activity:1.0.0-alpha08 and androidx.activity:activity-ktx:1.0.0-alpha08 are released. The commits included in this version can be found here .

API changes

  • Breaking change: The previously deprecated addOnBackPressedCallback and removeOnBackPressedCallback methods on ComponentActivity have been removed. aosp/953857
  • The setEnabled() and isEnabled() methods of OnBackPressedCallback are now final. b/131416833
  • The remove() method of OnBackPressedCallback is now final. aosp/952720
  • OnBackPressedDispatcher now has public constructors, allowing you to construct your own instances for testing, etc. aosp/953431
  • onBackPressed() for ComponentActivity is now explicitly marked as @MainThread aosp/952721

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

  • Fixed a ConcurrentModificationException when calling remove() from within the handleOnBackPressed() method of a OnBackPressedCalback that was added with a LifecycleOwner . b/131765095

Версия 1.0.0-alpha07

April 25th, 2019

androidx.activity:activity:1.0.0-alpha07 and androidx.activity:activity-ktx:1.0.0-alpha07 are released. The commits included in this version can be found here .

API changes

This release makes significant changes to the handling of the onBackPressed() . See the updated custom back documentation for more details.

  • The methods for OnBackPressedCallback and OnBackPressedDispatcher have been marked as @MainThread . ( aosp/943813 )
  • The handleOnBackPressed() method no longer returns a boolean . Instead, OnBackPressedCallback is now an abstract class that can be enabled or disabled - only when the new isEnabled() method returns true will handleOnBackPressed() be called, in which you must handle the back button. ( aosp/944518 )
  • The addCallback methods of OnBackPressedDispatcher no longer return a Cancellable instance. OnBackPressedCallback now contain a remove() method that fulfill this functionality, allowing you to call remove() during handleOnBackPressed() . ( aosp/944519 ) ( aosp/946316 )
  • activity-ktx now contains a receiver scoped callback for addCallback that accepts a lamdba that implements handleOnBackPressed() and has access to isEnabled and remove() ( aosp/944520 )

Версия 1.0.0-alpha06

April 3rd, 2019

androidx.activity:activity:1.0.0-alpha06 and androidx.activity:activity-ktx:1.0.0-alpha06 are released. The commits included in this version can be found here .

API changes

  • ComponentActivity now contain a second constructor that takes a @LayoutRes int , which replaces the previous behavior of annotating your AppCompatActivity class with @ContentView . This approach works in both app and library modules. ( b/128352521 )
  • The OnBackPressedCallback related APIs on ComponentActivity have been deprecated in favor of the new OnBackPressedDispatcher , retrievable via getOnBackPressedDispatcher() . ( aosp/922523 )
  • Methods to add a new OnBackPressedCallback to the OnBackPressedDispatcher now return a Cancellable object, allowing removal of the callback without requiring an explicit reference to the OnBackPressedDispatcher . ( aosp/922523 )
  • Adding a OnBackPressedCallback with an associated LifecycleOwner now results in adding and removing the OnBackPressedCallback as the Lifecycle is started and stopped, respectively. ( aosp/922523 )

Version 1.0.0-alpha05

March 13th, 2019

androidx.activity:activity:1.0.0-alpha05 and androidx.activity:activity-ktx:1.0.0-alpha05 are released. The full list of commits included in this release can be found here .

Новые функции

  • @ContentView annotation lookups are now cached ( b/123709449 )

Version 1.0.0-alpha04

30 января 2019 г.

androidx.activity:activity 1.0.0-alpha04 and androidx.activity:activity-ktx 1.0.0-alpha04 are released.

Новые функции

  • Added support for the @ContentView class annotation that allows you to indicate which layout XML file should be inflated as an alternative to using setContentView() . ( aosp/837619 )

API changes

  • Added a note that getViewModelStore() should not be overridden and will be made final in a future release. Please file a feature request if you are currently overriding this method. ( aosp/837619 )

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

  • The activity module now depends on version 2.1.0-alpha02 of ViewModel to match the activity-ktx module's dependency.

Версия 1.0.0-alpha03

17 декабря 2018 г.

androidx.activity 1.0.0-alpha03 is released.

Новые функции

  • ComponentActivity now implements BundleSavedStateRegistryOwner and depends on the newly released SavedState library [ aosp/815133 ]
  • ComponentActivity now works around an Android framework bug that would cause InputMethodManager to leak the last focused view [ b/37122102 ]

Версия 1.0.0-alpha02

3 декабря 2018 г.

API changes

  • Added a note that getLifecycle() should not be overridden and will be made final in a future release. Please file a feature request if you are currently overriding this method. ( aosp/815834 )

Версия 1.0.0-alpha01

5 ноября 2018 г.

androidx.activity 1.0.0-alpha01 introduces ComponentActivity , a new base class of the existing FragmentActivity and AppCompatActivity .

Новые функции

  • You can now register an OnBackPressedCallback via addOnBackPressedCallback to receive onBackPressed() callbacks without needing to override the method in your activity.
  • Added a new by viewModels() Kotlin property delegate for retrieving ViewModel s from a ComponentActivity .
  • Pending input events (such as clicks) are now canceled in onStop() .

API changes

  • The implementation of LifecycleOwner and ViewModelStoreOwner have been moved from FragmentActivity to ComponentActivity .
  • onRetainCustomNonConfigurationInstance has been deprecated. Use a ViewModel for storing objects that need to survive configuration changes.