Активность
| Последнее обновление | Стабильный релиз | Кандидат на релиз | Бета-версия | Альфа-релиз |
|---|---|---|---|---|
| 5 ноября 2025 г. | 1.11.0 | 1.12.0-rc01 | - | - |
Объявление зависимостей
Чтобы добавить зависимость от Activity, необходимо добавить репозиторий Google Maven в свой проект. Подробнее см. в репозитории Google Maven .
Добавьте зависимости для необходимых артефактов в файл build.gradle вашего приложения или модуля:
классный
dependencies { def activity_version = "1.11.0" // Java language implementation implementation "androidx.activity:activity:$activity_version" // Kotlin implementation "androidx.activity:activity-ktx:$activity_version" }
Котлин
dependencies { val activity_version = "1.11.0" // Java language implementation implementation("androidx.activity:activity:$activity_version") // Kotlin implementation("androidx.activity:activity-ktx:$activity_version") }
Дополнительные сведения о зависимостях см. в разделе Добавление зависимостей сборки .
Обратная связь
Ваши отзывы помогают улучшить Jetpack. Сообщите нам, если вы обнаружите новые проблемы или у вас есть идеи по улучшению этой библиотеки. Пожалуйста, ознакомьтесь с уже существующими проблемами в этой библиотеке, прежде чем создавать новую. Вы можете проголосовать за существующую проблему, нажав на кнопку со звёздочкой.
Более подробную информацию см . в документации по системе отслеживания проблем .
Версия 1.12
Версия 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-альфа09
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 содержит эти коммиты .
Изменения зависимости
- Активность теперь зависит от Navigation Event 1.0.0-alpha08 .
Версия 1.12.0-альфа08
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 содержит эти коммиты .
Обновление зависимостей
- Активность теперь зависит от Navigation Event 1.0.0-alpha08 .
Версия 1.12.0-альфа07
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 )
Обновление зависимостей
- Активность теперь зависит от Navigation Event
1.0.0-alpha07.
Версия 1.12.0-альфа06
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
-
minSdkпо умолчанию для AndroidX был перенесен из API 21 в API 23 ( Ibdfca , b/380448311 , b/435705964 , b/435705223 )
Обновления документации
- Обновлены KDocs для
PredictiveBackHandlerс целью выявления известной проблемы синхронизации, при которой он может обрабатывать жест в том же кадре, в котором он отключен. ( I5be5c , b/431534103 ) - Обновлены KDocs для
BackHandlerиPredictiveBackHandler, чтобы явно указать поведение «последний составленный выигрывает», а также рекомендовать безусловное составление сenabledфлагом. ( I7ab94 )
Обновление зависимости
- Активность теперь зависит от Navigation Event
1.0.0-alpha06.
Версия 1.12.0-альфа05
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 содержит эти коммиты .
Обновление зависимостей
- Активность теперь зависит от Navigation Event
1.0.0-alpha05.
Версия 1.12.0-альфа04
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 содержит эти коммиты .
Изменения зависимости
- Активность теперь зависит от NavigationEvent Alpha04
Версия 1.12.0-альфа03
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-альфа02
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-альфа01
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интегрированы с NavigationEvent1.0.0-alpha01через APINavigationEventDispatcherOwner. Теперь вы можете получить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:
- Добавлен API
MediaCapabilitiesвPickVisualMediaRequest, позволяющий приложениям указывать свои медиа-возможности, такие как поддерживаемые типы HDR. - Activity теперь скомпилирован с 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-альфа02
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.
Обновления зависимостей
- Activity теперь скомпилирован с API 36. ( I510e8 , b/301910674 )
Версия 1.11.0-альфа01
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 содержит эти коммиты .
Исправления ошибок
-
ViewTreeOnBackPressedDispatcherOwnersи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иPickMultipleVisualMediaActivity 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-альфа03
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 )
Исправления ошибок
- Начиная с Activity
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-альфа02
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иPickMultipleVisualMediaActivity 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 Activity ComposePredictiveBackHandlerпродолжал обрабатывать системный жест «назад» на кадре, в котором он был отключен. Это могло привести к тому, что библиотеки, такие как Navigation Compose, обрабатывали жест «назад» даже при пустом стеке «назад», выдавая исключениеIndexOutOfBoundsException. ( Ie3301 , b/340202286 ) - Из Activity
1.9.1: Исправлена проблема сPredictiveBackHandler, из-за которой после выполнения системного возврата попытка выполнитьonBackPressedизOnBackPressedDispatcherприводила к ошибке. ( I5f1f8 )
Версия 1.10.0-альфа01
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 Activity Compose
PredictiveBackHandlerпродолжал обрабатывать системный жест «Назад» на кадре, в котором он был отключен. Это могло привести к тому, что библиотеки, такие как 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 содержит эти коммиты .
Обновление зависимости
- Активность теперь зависит от Profile Installer 1.3.1 .
Версия 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-альфа03
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 содержит эти коммиты.
Предупреждение о ворсе
- API
OnBackPressedCallback,BackHandlerиPredictiveBackHandlerтеперь выдают предупреждения при вызовеonBackPressedDispatcher.onBackPressed()при обработке обратных событий, поскольку это всегда приводит к прерыванию предиктивной анимации обратных событий . Подробнее см. в руководстве по лучшим практикам . ( 1e4222 , 2c950d , b/287505200 )
Исправления ошибок
- Если событие «назад» отправляется из системы, запущенной во время уже выполняющегося прогнозируемого жеста «назад», то текущий выполняющийся прогнозируемый жест «назад» отменяется, а новое событие «назад» вступает во владение, чтобы начать новый прогнозируемый жест «назад». ( I3482e )
- Исправлен сбой при первом обращении
onBackPressedDispatcherизComponentActivityиз фонового потока. Теперь доступ кonBackPressedDispatcherбезопасен в любом потоке. ( I79955 )
Версия 1.9.0-альфа02
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. РасширенияActivityResultKotlin, поддерживающие деструктуризацию в поля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, теперь оно корректно передает ключEXTRA_SYSTEM_FALLBACK_PICK_IMAGES_MAXвместо использования дополнительного значения с ключом"com.google.android.gms.provider.extra.PICK_IMAGES_MAX". Если вы являетесь OEM-производителем, реализующим системный резервный режим выбора фотографий, настоятельно рекомендуется поддерживать оба дополнительных значения для обеспечения максимальной совместимости. ( I96a00 )
Версия 1.9.0-альфа01
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, что и контрактPickVisualMediaActivity Result. ( Id6e21 )
Обновление зависимостей
- Активность теперь зависит от Core
1.13.0-alpha01. ( I14f31 )
Версия 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
- Предиктивный возврат —
OnBackPressedCallbackтеперь предлагает новые предиктивные обратные вызовы для обработки начала жеста «назад», хода выполнения жеста и его отмены, в дополнение к ранее существовавшему обратному вызовуhandleOnBackPressed()действовавшему при завершении жеста «назад». Это также входит в составной объектPredictiveBackHandlerдля обработки событий предиктивного возврата в 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-альфа07
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 } }Он также поставляется с предупреждением времени компиляции через правило lint, чтобы гарантировать, что
Flowвызываетcollect(). ( Id2773 , b/294884345 )onBackPressedDispatcherвComponentActivityтеперь инициализируется лениво, поэтому он создается только при необходимости. ( I0bf8e )
Исправления ошибок
-
ComponentActivityбольше не будет отображать NPE на Android 13, если он получает обратный вызовonBackPressed(), а Activity уже былаDESTROYED. ( Idb055 , b/291869278 ) - Удалены случаи использования экспериментального API
isAtLeastU()( Ie9117 , b/289269026 )
Версия 1.8.0-альфа06
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в APIenableEdgeToEdgeтеперь можно переопределить лямбда-параметрdetectDarkMode, чтобы предоставить пользовательскую логику для обнаружения ночного режима. ( aosp/2546393 , b/278263793 )
Версия 1.8.0-альфа05
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-альфа04
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-альфа03
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теперь содержат открытый APIinitViewTreeOwners()который можно использовать для инициализации всех владельцев дерева представлений перед настройкой представления содержимого. ( Ibdce0 , b/261314581 )
Исправления ошибок
- Исправлена ошибка, из-за которой фрагменты некорректно делали MenuHosts недействительными, что приводило к неожиданному поведению других меню в Activity. ( I9404e , b/244336571 )
Другие изменения
-
ActivityResultRegisterтеперь использует KotlinRandomвместо Java. ( I4d98f , b/272096025 )
Версия 1.8.0-альфа02
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 . Разработаны во внутренней ветке.
Обновление зависимости
- Начиная с Activity
1.7.0-rc01: Activity теперь зависит отLifecycle 2.6.0.
Версия 1.8.0-альфа01
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 . Эта версия была собрана из внутренней ветки.
Новые функции
- Класс
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
- Контракты действий Photo Picker в
PickVisualMediaиPickMultipleVisualMediaобновлены и теперь содержат дополнительный резервный вариант на случай недоступностиMediaStore.ACTION_PICK_IMAGES. Это позволяет OEM-производителям и системным приложениям, таким как сервисы Google Play, обеспечивать единообразие работы Photo Picker на более широком спектре устройств Android и уровней API, реализуя действие fallback . Photo Picker будет использовать этот резервный вариант, если он доступен, прежде чем переходить к использованиюIntent.ACTION_OPEN_DOCUMENT, который по-прежнему поддерживает все устройства API 19 и более поздних версий. -
ComponentDialogтеперь реализуетSavedStateRegistryOwnerи имеет доступ к своемуSavedStateRegistry, а также устанавливаетSavedStateRegistryOwnerдля своегоViewTree. Теперь можно использовать Jetpack Compose вComponentDialogпоскольку он соответствует требованиям какLifecycleOwnerтак иSavedStateRegistryOwnerприкреплённых к окну через APIViewTree. -
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 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.
Three Activity Compose APIs have been added to make it more convenient to use the FullyDrawnReporter from individual composables:
-
ReportDrawnindicates that your composable is immediately ready for interaction. -
ReportDrawnWhentakes a predicate (ie,list.count > 0) to indicate when your composable is ready for interaction. -
ReportDrawnAftertakes a suspending method that, when it completes, indicates that you are ready for interaction.
Dependency Updates
- Activity now depends on Lifecycle
2.6.1. ( 8fc31d ) - Activity now depends on ProfileInstaller
1.3.0. ( 83d3b1 )
Version 1.7.0-rc01
March 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
- Activity now depends on
Lifecycle 2.6.0.
Version 1.7.0-beta02
February 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 Changes
- The action and extra used by the
PickVisualMediaandPickMultipleVisualMediacontracts as a fallback for whenMediaStore.ACTION_PICK_IMAGESis 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
February 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 fromIntent, rather than only a single flag. ( Iac04c )
Bug Fixes
- The fallback for
PickVisualMediafor when the framework Photo Picker is unavailable now correctly limits the handling to apps installed in the device's system image. ( If8ae6 )
Kotlin Conversions
-
ActivityResultRegistryOwneris now written in Kotlin. This is a source incompatible change for those classes written in Kotlin - you must now override theactivityResultRegistryproperty rather than implementing the previousgetActivityResultRegistry()function. ( I0b00e ) -
OnBackPressedDispatcherOwneris now written in Kotlin. This is a source incompatible change for those classes written in Kotlin - you must now override theonBackPressedDispatcherproperty rather than implementing the previousgetOnBackPressedDispatcherfunction. ( Ia277d ) -
ContextAware,ContextAwareHelper,OnContextAvailableListener,IntentSenderRequestandOnBackPressedDispatcherare now written in Kotlin. ( I1a73e , Iada92 , aosp/2410754 , I18ac7 , b/257291701 )
Version 1.7.0-alpha04
January 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
PickVisualMediaandPickMultipleVisualMediaActivity 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. TheisPhotoPickerAvailable()API that only detects the Android system provided Photo Picker has been deprecated. It is recommended to use the newisPhotoPickerAvailable(Context)API, which will return if either Photo Picker is available. ( I55be6 )
Version 1.7.0-alpha03
January 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.
Новые функции
-
ComponentDialognow implementsSavedStateRegistryOwnerand has access to its ownSavedStateRegistryand sets theSavedStateRegistryOwnerfor its ViewTree. It is now possible to use Jetpack Compose within aComponentDialogas it meets both theLifecycleOwnerandSavedStateRegistryOwnerattached to the Window via the ViewTree APIs requirements. ( Idca17 , I73468 b/261162296 )
API Changes
- Added a
ReportDrawncomposable that immediately marks the activity as ready to callreportFullyDrawn. ( Ic5b14 , b/259687964 )
Kotlin Conversions
- The
ActvitiyResultCallbackandOnBackPressedCallbackclasses have both been converted to Kotlin while maintaining source and binary compatibility. ( Ifc5e5 , Ide1b0 , b/257291701 )
Version 1.7.0-alpha02
October 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.
Bug Fixes
- From Activity
1.6.1: Fixed an issue with thePickMultipleVisualMediaActivity Result contract not launching on Android R devices when using the default value formaxItems. ( 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:
-
ReportDrawnWhentakes a predicate (ie,list.count > 0) to indicate when your composable is ready for interaction. -
ReportDrawnAftertakes a suspending method that, when it completes, indicates that you are ready for interaction.
Version 1.6.1
Version 1.6.1
October 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.
Bug Fixes
- Fixed an issue with the
PickMultipleVisualMediaActivity Result contract not launching on Android R devices when using the default value formaxItems. ( Ie2776 , b/249182130 )
Version 1.6.0
Version 1.6.0
September 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.PickVisualMediaandActivityResultContracts.PickMultipleVisualMediafor providing a backward compatible contract that usesMediaStore.ACTION_PICK_IMAGESwhen the Photo Picker is available andIntent.ACTION_OPEN_DOCUMENTwhen it is not available. - Integrated the
OnBackInvokedCallbackin Android 13 into theOnBackPressedDispatchersprovided byComponentActivityandComponentDialog. This ensures that all APIs built onOnBackPressedDispatcherwork 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.
Bug Fixes
-
OnBackPressedDispatchernow registers theOnBackInvokedCallbackwith thePRIORITY_DEFAULTinstead ofPRIORITY_OVERLAY. ( I3901f ) - Classes that extend
ComponentActivitywill now always have both of theironMultiWindowModeChanged()callbacks dispatched. ( Ic4d85 ) - The
ActivityResultRegistrywill no longer return a result to theActivityResultCallbackwhen thelaunchcall throws anyExceptionand the callback was registered without aLifecycleOwner. ( Ia7ff7 , b/238350794 ) -
ComponentActivitywill now properly dispatch menu calls without the need to call the super function in your activity. ( Ie33c5 , b/238057118 )
Dependency Update
- The
Activitylibrary now depends on Lifecycle2.5.1. ( If6697 )
Version 1.6.0-rc01
August 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.
Bug Fixes
- Initializing an
OnBackPressedDispatcherwill no longer causeClassVerificationErrors when using SDK versions prior to 33. ( Ic32e1 ) - Classes that override
ComponentActivity'sonPictureInPictureModeChanged()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 Changes
- Marked the deprecated
startActivityForResultandstartIntentSenderForResultmethods onComponentActivitywith@NonNullbecause passingnullhas always resulted in a crash. ( Id2a25 , b/231476082 )
Bug Fixes
- From Activity
1.5.1: TheActivityResultRegistrywill no longer return a result to theActivityResultCallbackwhen thelaunchcall throws anyExceptionand the callback was registered without aLifecycleOwner. ( Ia7ff7 , b/238350794 ) - From Activity
1.5.1:ComponentActivitywill now properly dispatch menu calls toonPrepareOptionMenu(),onCreateOptionsMenu()andonOptionsItemSelected()overrides without the need to call the super function. ( Ie33c5 , b/238057118 )
Dependency Update
- From Activity
1.5.1: TheActivitylibrary now depends on theLifecycleversion2.5.1. ( If6697 )
Version 1.6.0-alpha05
June 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 Changes
-
minCompileSdkis now 33 to align with Tiramisu Beta 3 SDK
Bug Fixes
- Fixed crash on older devices when doing SDK extension check for the
PickVisualMediaActivityResultContractso that it should now work withACTION_OPEN_DOCUMENTon devices running Android 10 and lower.
Version 1.6.0-alpha04
May 18, 2022
androidx.activity:activity:1.6.0-alpha04 and androidx.activity:activity-ktx:1.6.0-alpha04 are released.
Bug Fixes
- Fixed an error in
PickVisualMediaRequestwhere attempting to create a request, either via the Builder or the top level Kotlin function, would result in a stack overflow. - Integrated the
OnBackInvokedCallbackin Android 13 Dev Beta 2 into theOnBackPressedDispatcherprovided byComponentDialog. This ensures that all APIs built onOnBackPressedDispatcherwork when enabling a predictive back gesture .
Version 1.6.0-alpha03
April 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.PickVisualMediaandActivityResultContracts.PickMultipleVisualMediafor providing a backward compatible contract that usesMediaStore.ACTION_PICK_IMAGESwhen the Photo Picker is available andIntent.ACTION_OPEN_DOCUMENTwhen it is not available. - Integrated the
OnBackInvokedCallbackin Android 13 Dev Beta 1 into theOnBackPressedDispatcherprovided byComponentActivity. This ensures that all APIs built onOnBackPressedDispatcherwork when enabling a predictive back gesture .
Version 1.6.0-alpha01
March 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.
Version 1.5.1
Version 1.5.1
July 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.
Bug Fixes
The
ActivityResultRegistrywill no longer return a result to theActivityResultCallbackwhen thelaunch()call throws anyExceptionand the callback was registered without aLifecycleOwner. ( Ia7ff7 , b/238350794 )ComponentActivitywill now properly dispatch menu calls toonPrepareOptionMenu(),onCreateOptionsMenu()andonOptionsItemSelected()overrides without the need to call the super function. ( Ie33c5 , b/238057118 )
Dependency update
- The
Activitylibrary now depends on the Lifecycle2.5.1. ( If6697 )
Version 1.5.0
Version 1.5.0
June 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.
Important changes since 1.4.0
- ComponentDialog -
ComponentDialogis a subclass ofDialogthat includes anOnBackPressedDispatcherthat will be called when the system back button is pressed and the dialog is visible. Importantly, this subclass also sets theViewTreeOnBackPressedDispatcherOwner, allowing views a generic way to retrieve the correct dispatcher whether it exists in aComponentActivityor aComponentDialog. - Callback Interfaces -
ComponentActivitynow implements a set of modular callback interfaces that can be used instead of theActivitycallbacks. These interfaces include the following:OnNewIntentProvider,OnConfigurationChangedProvider,OnTrimMemoryProvider,OnPictureInPictureModeChangedProvider,OnMultiWindowModeChangedProvider - CreationExtras Integration -
ComponentActivitynow has the ability to provide a statelessViewModelProvider.Factoryvia Lifecycle2.5.0'sCreationExtras.
Other changes
- The no parameter constructor for
ActivityResultContracts.CreateDocumenthas been deprecated and replaced with a new constructor that takes a concrete mime type (eg, "image/png") as is required byIntent.ACTION_CREATE_DOCUMENT.
Version 1.5.0-rc01
May 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.
Version 1.5.0-beta01
April 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
- Activity now depends on Lifecycle
2.4.0-beta01.
Version 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.
Bug Fixes
-
ComponentActivity'sonPanelClosed()now calls the superonPanelClosed()as well, fixing an issue where theonContextMenuClosedmethod would not be called. ( Ib6f77 )
Version 1.5.0-alpha04
March 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.
Bug Fixes
-
SavedStateViewFactorynow supports usingCreationExtraseven when it was initialized with aSavedStateRegistryOwner. If extras are provided, the initialized arguments are ignored. ( I6c43b , b/224844583 )
Version 1.5.0-alpha03
February 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 Changes
- You can now pass
CreationExtrasto the activityby viewModels()function ( I6a3e6 , b/217600303 )
Version 1.5.0-alpha02
February 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.
Новые функции
-
ComponentActivitynow implements theOnPictureInPictureModeChangedProviderinterface to allow any component to receive picture-in-picture mode change events. ( I9f567 ) -
ComponentActivitynow implements theOnMultiWindowModeChangedProviderinterface to allow any component to receive multi-window mode change events. ( I62d91 )
Version 1.5.0-alpha01
January 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.
Новые функции
-
ComponentActivitynow integrates with ViewModel CreationExtras, introduced as part of Lifecycle2.5.0-alpha01. ( Ie7e00 , b/207012584 ) - Added
ComponentDialog, a subclass ofDialogthat includes anOnBackPressedDispatcherthat will be called when the system back button is pressed when the dialog is visible. Importantly, this subclass also sets theViewTreeOnBackPressedDispatcherOwner, allowing views a generic way to retrieve the correct dispatcher whether it exists in aComponentActivityor aComponentDialog. ( I8a1bc ) -
ComponentActivitynow implements the newOnNewIntentProviderinterface to allow any component to receive these events. ( If1f8b ) -
ComponentActivitynow implements the newOnConfigurationChangedProviderinterface to allow any component to receive these events. ( If623b ) -
ComponentActivitynow implements the newOnTrimMemoryProviderinterface to allow any component to receive these events. ( Ia9295 )
API Changes
- The no parameter constructor for
ActivityResultContracts.CreateDocumenthas been deprecated and replaced with a new constructor that takes a concrete mime type (eg,"image/png") as is required byIntent.ACTION_CREATE_DOCUMENT. ( I2bec6 ) - The
OnBackPressedDispatcherOwnerassociated with a View can now be retrieved via theViewTreeOnBackPressedDispatcherOwner, rather than relying on casting theContext. ( I74685 )
Bug Fixes
- Fixed a crash when accessing a
ViewModelfor the very first time from aregisterForActivityResult()callback or the callbacks to aLifecycleObserveradded as part ofinitof aComponentActivity. ( Ife83f )
Version 1.4.0
Version 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.
Important changes since 1.3.0
- AndroidX
ComponentActivitynow implements theMenuHostinterface. This allows any component to add menu items to theActionBarby adding aMenuProviderinstance to the activity. EachMenuProvidercan optionally be added with aLifecyclethat will automatically control the visibility of those menu items based on theLifecyclestate and handle the removal of theMenuProviderwhen theLifecycleis destroyed. - The
ActivityResultContractclass 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
ActivityResultContractsclass and its contracts have been rewritten in Kotlin to ensure the proper nullability.
Version 1.4.0-rc01
October 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.
Bug Fixes
- The
ActivityResultRegistrywill no longer return a result to theActivityResultCallbackwhen thelaunchcall throws anyException. ( If4f91 , b/200845664 )
Version 1.4.0-beta01
September 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 Changes
- Fixed the type for the
ActivityResultContracts.OpenMultipleDocumentsandActivityResultContracts.GetMultipleContentsthat caused then to use an output type ofList<? extends Uri>when using the code from the Java programming language. ( If71de ) - Public constants within the
ActivityResultContracts.StartActivityForResult,ActivityResultContracts.StartIntentSenderForResult, andActivityResultContracts.RequestMultiplePermissionsclasses are now accessible when using Kotlin via their now publicCompanionobjects. ( aosp/1832555 )
Documentation Updates
- The deprecation message for APIs now handled by the Activity Result APIs , namely
startActivityForResult,startIntentSenderForResult,onActivityResult,requestPermissions, andonRequestPermissionsResult, have all been expanded with more details. ( cce80f )
Version 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-composeartifact now contains aLaunchDuringCompositionlint error that prevents you from calling thelaunchmethod ofActivityResultLauncheras part of composition as composition should be side-effect free. Use the APIs for handling side-effects . ( 7c2bbe , b/191347220 )
API Changes
- The
ActivityResultContractclass 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
ActivityResultContractsclass and its contracts have been rewritten in Kotlin to ensure the proper nullability. ( I69802 )
Version 1.4.0-alpha01
September 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
ComponentActivitynow implements theMenuHostinterface.. This allows any component to add menu items to theActionBarby adding aMenuProviderinstance to the activity. EachMenuProvidercan optionally be added with aLifecyclethat will automatically control the visibility of those menu items based on theLifecyclestate and handle the removal of theMenuProviderwhen theLifecycleis 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
ActivityResultRegistrywill now throw anIllegalStateExceptionwhen attempting to calllaunch()on anActivityResultLauncherthat has not be registered or that has been unregistered. ( Ida75d , b/192567522 )
External Contribution
Version 1.3.1
Version 1.3.1
August 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.
Version 1.3.0
Version 1.3.0
July 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.
Important changes since 1.2.0
- Activity Compose artifact - The
activity-composeartifact provides thesetContentextension method for hosting your Jetpack Compose UI in an activity and Compose specific wrappers for interacting with theComponentActivityAPIs for handling the system back button and the Activity Result APIs. See the documentation for more details. - CaptureVideo contract - The
CaptureVideoActivityResultContractreplaces the now deprecatedTakeVideocontract and returns a boolean denoting success that works across many camera apps. - Picture-In-Picture Hint View Tracking - Users of
activity-ktxcan now use thetrackPipAnimationHintViewextension method onActivityto automatically rebuild thePictureInPictureParamswith the new position of the view as it changes position relative to the window.
Version 1.3.0-rc02
July 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.
Bug Fixes
- The
ActivityResultRegistrycallbacks are now properly saved and restored so callbacks are not duplicated in the savedState. ( I97816 , b/191893160 )
Version 1.3.0-rc01
July 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.
Version 1.3.0-beta02
June 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 .
Version 1.3.0-beta01
June 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 Changes
- The previously deprecated
@Composable registerForActivityResult()method has been removed. Please userememberLauncherForActivityResult(). ( Ic39d3 )
Version 1.3.0-alpha08
May 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
CaptureVideoActivityResultContractreturns a boolean to yourActivityResultCallbackindicating if your video was successfully saved to the given URI. This replaces the now deprecatedTakeVideocontract as camera apps very rarely supported returning a thumbnail bitmap, making the result unhelpful. ( Ie21f2 , b/185938070 ) - Added new API
Activity#setPipAnimationHintViewto update the PipParams' source rect hint whenever the view moves. ( I9063d )
API Changes
- The
rememberLauncherForActivityResultfunction now returns a launcher that deprecates theunregister()function - registration and unregistering the launcher is handled automatically byrememberLauncherForActivityResult. ( I2443e )
Compose Compatibility
-
androidx.activity:activity-compose:1.3.0-alpha08is only compatible with Compose version1.0.0-beta07and above.
Version 1.3.0-alpha07
April 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.
Bug Fixes
-
rememberLauncherForActivityResultnow returns a stable reference to the sameActivityResultLauncherinstance even if the contract changes due to recompositions. ( Id2d6d ) - Using unstable versions of Fragments above
1.3.0will no longer throw a false positive lint error telling you to use1.3.0. ( aosp/1670206 , b/184847092 )
Version 1.3.0-alpha06
April 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 Changes
- The
registerForActivityResult()API has been renamed torememberLauncherForActivityResult()to better indicate that the returnedActivityResultLauncheris a managed object that is remembered on your behalf. Attempting to callunregisterthe returnedActivityResultLauncherwill now throw an error. ( I2bb6d ) -
LocalOnBackPressedDispatcherOwner.currentandLocalActivityResultRegistryOwner.currentnow return a nullable value to better determine whether it is available in the current composition. APIs that requires those APIs, such asBackHandlerandrememberLauncherForActivityResult(), respectively, will now throw a more descriptive error if the underlying owner is not found.NavHostnow works even when anOnBackPressedDispatcherOwneris not found, such is the case when previewing theNavHost. ( I7d8b4 )
Bug Fixes
- The
BackHandlerwill now properly intercept back presses in the event that the Activity isSTOPPED, thenSTARTEDagain, and other callbacks were added with a LifecycleOwner. ( I71de6 , b/182284739 ) - Using the
launch()method extension with a customActivityResultContractthat has aUnitinput will no longer cause aNullPointerException( I76282 , b/183837954 )
Version 1.3.0-alpha05
March 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.
Bug Fixes
- From Activity 1.2.2 : Fixed an issue in the
InvalidFragmentVersionForActivityResultlint check that led to a false positive when using Fragment 1.3.1 or higher. ( I54da1 , b/182388985 ) - From Activity 1.2.2 :
ComponentActivitynow avoids aClassNotFoundExceptionwhen launching anIntentfrom anActivityResultContractthat was previously held as an extra in anotherIntent. ( Ieff05 , b/182906230 )
Dependency Updates
- From Activity 1.2.2 : Activity now depends on Lifecycle
2.3.1.
Version 1.3.0-alpha04
March 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.
Bug Fixes
- From Activity
1.2.1:RequestMultiplePermissionsnow always returns results for all requested permissions instead of only permissions that weren't previously granted. ( I50bc3 , b/180884668 ) - From Activity
1.2.1:ActivityResultRegistrynow ensures that in progresslaunch()requests will return their results even if youunregister(), thenregister()again with the same key. ( I9ef34 , b/181267562 ) - Activity Compose no longer adds test dependencies to the runtime classpath. ( Ifd8b3 )
- Fixed an issue with
BackHandlerwhere the previously setonBacklambda was still being used after recomposition. ( 8eb5eb )
Version 1.3.0-alpha03
February 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
registerForActivityResultfunction for getting results from activities within composables. ( Ia7851 , b/172690553 )
API Changes
-
LocalOnBackPressedDispatcherOwnernow has aprovidesfunctions that can be used withCompositionLocalProvider, replacing theasProvidableCompositionLocal()API. ( I45d24 )
Version 1.3.0-alpha02
February 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.
Bug Fixes
- Fixed an issue in Activity Compose
1.3.0-alpha01that causes aNoSuchMethodError: No static method setContentexception when using Compose1.0.0-alpha12. All Compose users should depend on1.3.0-alpha02and above. ( b/179911234 )
API Changes
- The
BackHandlerAPI can be used to allow a Composable to intercept the system back button. ( I58ed5 , b/172154006 )
Version 1.3.0-alpha01
February 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-composeartifact provides Jetpack Compose specific helpers forandroidx.activityspecific APIs.-
ComponentActivity.setContenthas moved fromandroidx.compose.ui.platform.setContenttoandroidx.activity.compose.setContent. ( Icf416 )
-
Известные проблемы
- Using Activity Compose
1.3.0-alpha01and libraries that depend on it, such asandroidx.compose.ui:ui-test-junit4:1.0.0-alpha12, will result in aNoSuchMethodError: No static method setContentexception. ( b/179911234 )
Version 1.2.4
Version 1.2.4
July 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.
Bug Fixes
- From Activity
1.3.0-rc02: The ActivityResultRegistry callbacks are now properly saved and restored so callbacks are not duplicated in the savedState. ( I97816 , b/191893160 )
Version 1.2.3
Version 1.2.3
May 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.
Bug Fixes
- Using the
launch()method extension with a customActivityResultContractthat has aUnitinput will no longer cause aNullPointerException( I76282 , b/183837954 ) - Fixed a false positive lint error telling you to use Fragment
1.3.0when using an snapshot, alpha, beta, or RC build of a newer version of Fragments. ( f4a57e , b/184847092 )
Version 1.2.2
Version 1.2.2
March 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.
Bug Fixes
- Fixed an issue in the
InvalidFragmentVersionForActivityResultlint check that led to a false positive when using Fragment 1.3.1 or higher. ( I54da1 , b/182388985 ) -
ComponentActivitynow avoids aClassNotFoundExceptionwhen launching anIntentfrom anActivityResultContractthat was previously held as an extra in anotherIntent. ( Ieff05 , b/182906230 )
Dependency Updates
- Activity now depends on Lifecycle
2.3.1.
Version 1.2.1
Version 1.2.1
March 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.
Bug Fixes
-
RequestMultiplePermissionsnow always returns results for all requested permissions instead of only permissions that weren't previously granted. ( I50bc3 , b/180884668 ) -
ActivityResultRegistrynow ensures that in progresslaunch()requests will return their results even if youunregister(), thenregister()again with the same key. ( I9ef34 , b/181267562 )
Version 1.2.0
Version 1.2.0
February 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 :
ComponentActivitynow provides anActivityResultRegistrythat lets you handlestartActivityForResult()+onActivityResult()as well asrequestPermissions()+onRequestPermissionsResult()flows without overriding methods in your Activity or Fragment, brings increased type safety viaActivityResultContract, and provides hooks for testing these flows. See the updated Getting a Result from an Activity .
ContextAware:ComponentActivitynow implementsContextAware, allowing you to add one or moreOnContextAvailableListenerinstances which will receive a callback before the baseActivity.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
FragmentActivityin Fragment 1.3.0 to restore the state of theFragmentManager. Any listeners added to subclasses ofFragmentActivitywill run after that listener. - This API is used by
AppCompatActivityin AppCompat 1.3.0-alpha02 or higher. Any listeners added to subclasses ofAppCompatActivitywill run after that listener.
- A suspending Kotlin extension
ViewTreeSupport :ComponentActivitynow supports theViewTreeLifecycleOwner.get(View),ViewTreeViewModelStoreOwner.get(View), andViewTreeSavedStateRegistryOwnerAPIs added in Lifecycle2.3.0and SavedState1.1.0such that it will return the Activity as theLifecycleOwner,ViewModelStoreOwner, andSavedStateRegistryOwnerfor any Views directly added to theComponentActivity.
- reportFullyDrawn() backport - The
Activitymethod ofreportFullyDrawn()has been backported inComponentActivityto work on all API levels, fixing a crash on API 19 and adding tracing for this method for all API levels.
Version 1.2.0-rc01
December 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.
Bug Fixes
- The
ActivityResultRegistrynow always restores the exact state that was saved. ( Idd56b ) - Add tracing to
ComponentActivity.reportFullyDrawn( Ic7632 )
External Contribution
-
ComponentActivitynow overridesreportFullyDrawn(), 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
December 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.
Bug Fixes
- Fixed an issue where the Activity Result API would not wait for the Lifecycle to be
STARTEDbefore delivering results when registered with aLifecycle. ( I109ea )
External Contribution
- Updated the documentation for
launch()to explicitly call out that it can throw anActivityNotFoundException. Thanks Michał Zieliński! ( aosp/1493580 )
Version 1.2.0-beta01
October 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.
Bug Fixes
The
ActivityResultRegistrynow randomly generates integers until it finds one that is unallocated to use as a request coderegister(), thus preventing the possible integer overflow caused by incrementing request codes. ( b/168779518 )Lifecycleobservers are properly removed when callingunregister()on anActivityResultLauncher. ( b/165608393 )
Изменения поведения
- The
ActivityResultRegistrynow throws anIllegalStateExceptionwhen attempting to callregister()with aLifecycleOwnerwhoseLifecyclehas already reachedSTARTED. ( b/165435866 )
Documentation Updated
-
ContextAwaredocumentation links toLifecycleOwnerto highlightLifecyclecallbacks as the appropriate place for creation and destruction events. ( aosp/1414152 )
Version 1.2.0-alpha08
August 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.
Новые функции
-
ComponentActivitynow implementsContextAware, allowing you to add one or moreOnContextAvailableListenerinstances which will receive a callback before the baseActivity.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
FragmentActivityin Fragment 1.3.0-alpha08 to restore the state of theFragmentManager. Any listeners added to subclasses ofFragmentActivitywill run after that listener. ( I513da ) - This API is used by
AppCompatActivityin AppCompat 1.3.0-alpha02 . Any listeners added to subclasses ofAppCompatActivitywill run after that listener. ( I513da )
- A suspending Kotlin extension
Bug Fixes
- Fixed an issue with the
ActivityResultFragmentVersionDetectorLint check that caused it to break when using Lint 27.1.0 or higher. ( b/162155191 )
Version 1.2.0-alpha07
July 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
InvalidFragmentVersionForActivityResultlint check that verifies that you are using Fragment1.3.0-alpha07when 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 )
External Contribution
- Fixed an
ArrayIndexOutOfBoundsExceptionwhen parsing the results for theRequestPermissionActivity Result contract. ( I8f9e3 , b/161057605 )
Version 1.2.0-alpha06
June 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
ActivityResultclass in kotlin to directly access therequestCodeandintent. ( b/157212935 ) -
ActivityResultLaunchernow allows you to get theActivityResultContractthat was used to register the launcher. ( b/156875743 )
API Changes
- Breaking change : The
invoke()method onActivityResultRegistryhas been renamed toonLaunch(). ( b/157496491 ) - The
OpenMultipleDocumentscontract now returns an empty list instead ofnullto the registered callback if no result is returned. ( b/157348014 )
Version 1.2.0-alpha05
May 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.
Новые функции
- Added support for
ViewTreeViewModelStoreOwnerfrom Lifecycle2.3.0-alpha03, andViewTreeSavedStateRegistryOwnerfrom SavedState1.1.0-alpha01when using aViewwithin aComponentActivity. ( aosp/1297993 , aosp/1300264 )
API Changes
- The
TakePicturecontract now returns abooleanindicating success rather than a thumbnailBitmapas this was very rarely supported by camera apps when writing the image to the providedUri. ( b/154302879 ) - The
invoke()extensions onActivityResultLauncherhave been removed in favor of explicitly usinglaunch()to better indicate that these are asynchronous operations. Kotlin extensions forlaunchhave been added to theandroidx.activity.resultpackage forActivityResultLauncher<Void>andActivityResultLauncher<Unit>that remove the need to pass innullorUnit, respectively, mirroring that behavior from the previouslyinvoke()extensions. ( aosp/1304674 , aosp/1304675 ) - The
IntentSenderRequest.Buildermethods forsetFlagsMask()andsetFlagsValues()has been combined into a singlesetFlags()method. ( aosp/1302111 )
Bug Fixes
- When registering an
ActivityResultCallbackwith aLifecycleOwner, fixed an issue where the callback would be triggered before the state reachesSTARTED. ( aosp/1309744 )
Изменения поведения
- The
ActivityResultRegistrynow generates request codes starting at0xFFFFrather than at0, preventing overlap when usingstartActivityForResult()orrequestPermissions()in an activity. ( aosp/1302324 )
Version 1.2.0-alpha04
April 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 Changes
- The
prepareCall()method has been renamed toregisterForActivityResult(), both onComponentActivityhere and in Fragment1.3.0-alpha04. ( aosp/1278717 ) - The
GetContents,OpenDocuments, andRequestPermissionscontracts have been renamed toGetMultipleContents,OpenMultipleDocuments, andRequestMultiplePermissions, respectively. ( aosp/1280161 ) -
ComponentActivitynow implements theActivityResultRegisteryOwnerinterface. ( aosp/1290888 ) - - The
startActivityForResult()/onActivityResult()andonRequestPermissionsResult()APIs onComponentActivityhave been deprecated. Please use the Activity Result APIs . ( b/154751887 )
Bug Fixes
- When using the
GetMultipleContentsandOpenMultipleDocumentscontracts and selecting a single item, it is now correctly returned to your callback. ( b/152941153 )
Version 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, andCreateDocumentcontracts to the set of pre-built contracts provided byActivityResultContracts. ( aosp/1262482 , aosp/1266916 , aosp/1268960 ) - The Activity Result APIs now support launching an activity for result with an optional
ActivityOptionsCompat. ( b/151860054 )
API Changes
- The
TakePicturecontract now takes aUriinput for where the image should be stored. The previous contract that does not take any input has been renamed toTakePicturePreview. ( aosp/1262482 ) - The
registerActivityResultCallback()method onActivityResultRegistryhas been renamed toregister(). ( aosp/1267621 ) - The
dispose()method onActivityResultLauncherhas been renamed tounregister()and theunregisterResultCallback()onActivityResultRegistryhas been removed. ( aosp/1267621 ) - The
createIntent()method ofActivityResultContactnow takes aContextin addition to the input to make it possible to create explicit Intents. ( aosp/1238800 ) - An
ActivityResultContractcan now overridegetSynchronousResult()to deliver a result without callingstartActivityForResult. This is used by theRequestPermissionandRequestPermissionscontracts to correctly deliver a 'granted' status if the requested permissions are already granted. ( b/151110799 ) - The previously available
Dialcontract has been removed as thatIntentis not meant to be used withstartActivityForResult(). ( aosp/1266916 ) - Many of the Activity Result APIs not meant to be extended are now
final. This includesgetActivityResultRegistry(), theprepareCall()methods, all methods ofActivityResultRegistryexceptinvoke(), and a number of the default contracts that do not support optional extras. ( b/152439361 )
Bug Fixes
- Fixed a
NullPointerExceptioninActivityResultRegistrywhen attempting to deliver results to a callback that has not yet been re-registered after a configuration change;ActivityResultRegistrynow holds onto these pending results and delivers them when the callback is re-registered. ( b/152137004 )
Version 1.2.0-alpha02
March 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 :
ComponentActivitynow provides anActivityResultRegistrythat lets you handle thestartActivityForResult()+onActivityResult()as well asrequestPermissions()+onRequestPermissionsResult()flows without overriding methods in your Activity or Fragment, brings increased type safety viaActivityResultContract, and provides hooks for testing these flows. See the updated Getting a Result from an Activity . ( b/125158199 )
Version 1.2.0-alpha01
March 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 Lifecycle2.3.0-alpha01such that it will return the Activity as theLifecycleOwnerfor any Views directly added to the Activity. ( aosp/1182955 )
Bug Fixes
- Fixed a regression introduced in Activity
1.1.0when running on older versions of the platform whereonBackPressed()would cause anIllegalStateExceptiondue to a bug in theandroid.app.FragmentManager. ( b/146290338 )
Version 1.1.0
Version 1.1.0
January 22, 2020
androidx.activity:activity:1.1.0 is released. Version 1.1.0 contains these commits .
Important changes since 1.0.0
- Lifecycle ViewModel SavedState Integration :
SavedStateViewModelFactoryis now the default factory used when usingby viewModels(), theViewModelProviderconstructor, orViewModelProviders.of()with aComponentActivityor its subclasses.
Version 1.1.0-rc03
December 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-rc03and Lifecycle ViewModel SavedState1.0.0-rc03.
Version 1.1.0-rc02
November 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.
Version 1.1.0-rc01
October 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 .
Version 1.1.0-beta01
October 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.
Version 1.1.0-alpha03
September 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.
Исправления ошибок
- Activity now depends on Lifecycle
2.2.0-alpha04.
Version 1.1.0-alpha02
August 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 .
Новые функции
-
SavedStateViewModelFactoryis now the default factory used when usingby viewModels(), theViewModelProviderconstructor, orViewModelProviders.of()with aComponentActivity( b/135716331 )
Version 1.1.0-alpha01
July 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 .
Новые функции
-
activitynow depends on Lifecycle2.2.0-alpha02. ( aosp/1007817 ) -
activity-ktxadded a dependency onlifecycle-runtime-ktx; you no longer need to explicitly add it to your dependencies when usingactivity-ktxor libraries that depend onactivity-ktx(such asfragment-ktx). ( aosp/987162 )
Version 1.0.0
Version 1.0.0
September 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 :
ComponentActivityserves as the new base class forFragmentActivityin Fragment1.1.0and, by extension,AppCompatActivityin AppCompat1.1.0. - activity-ktx : The
activity-ktxmodule includes aby viewModelsKotlin property extension for accessing ViewModels. This module is automatically included when you includefragment-ktxfrom Fragment1.1.0. - OnBackPressedDispatcher : As a composable alternative to overriding
onBackPressed(), you can now register aOnBackPressedCallbackfrom anyLifecycleOwner(such as a fragment) to intercept system back button events. A lambda with receiver versionaddCallbackhas been added toactivity-ktx. See Provide custom back navigation documentation for more details. - onRetainCustomNonConfigurationInstance deprecation : the
onRetainCustomNonConfigurationInstance()and the relatedgetLastCustomNonConfigurationInstance()APIs have been deprecated. It is strongly recommended to use ViewModels to store non-configuration state as they offer a composable solution suitable for anyViewModelStoreOwnerthat makes the ownership of the retained objects clear and provides anonCleared()callback for cleaning up resources when the activity is finally destroyed.
Version 1.0.0-rc01
July 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 .
Version 1.0.0-beta01
June 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 .
Version 1.0.0-alpha08
May 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
addOnBackPressedCallbackandremoveOnBackPressedCallbackmethods onComponentActivityhave been removed. aosp/953857 - The
setEnabled()andisEnabled()methods ofOnBackPressedCallbackare now final. b/131416833 - The
remove()method ofOnBackPressedCallbackis now final. aosp/952720 -
OnBackPressedDispatchernow has public constructors, allowing you to construct your own instances for testing, etc. aosp/953431 -
onBackPressed()forComponentActivityis now explicitly marked as@MainThreadaosp/952721
Исправления ошибок
- Fixed a
ConcurrentModificationExceptionwhen callingremove()from within thehandleOnBackPressed()method of aOnBackPressedCalbackthat was added with aLifecycleOwner. b/131765095
Version 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
OnBackPressedCallbackandOnBackPressedDispatcherhave been marked as@MainThread. ( aosp/943813 ) - The
handleOnBackPressed()method no longer returns aboolean. Instead,OnBackPressedCallbackis now an abstract class that can be enabled or disabled - only when the newisEnabled()method returns true willhandleOnBackPressed()be called, in which you must handle the back button. ( aosp/944518 ) - The
addCallbackmethods ofOnBackPressedDispatcherno longer return aCancellableinstance.OnBackPressedCallbacknow contain aremove()method that fulfill this functionality, allowing you to callremove()duringhandleOnBackPressed(). ( aosp/944519 ) ( aosp/946316 ) -
activity-ktxnow contains a receiver scoped callback foraddCallbackthat accepts a lamdba that implementshandleOnBackPressed()and has access toisEnabledandremove()( aosp/944520 )
Version 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
OnBackPressedCallbackrelated APIs on ComponentActivity have been deprecated in favor of the newOnBackPressedDispatcher, retrievable viagetOnBackPressedDispatcher(). ( aosp/922523 ) - Methods to add a new
OnBackPressedCallbackto theOnBackPressedDispatchernow return aCancellableobject, allowing removal of the callback without requiring an explicit reference to theOnBackPressedDispatcher. ( aosp/922523 ) - Adding a
OnBackPressedCallbackwith an associatedLifecycleOwnernow results in adding and removing theOnBackPressedCallbackas 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 .
Новые функции
-
@ContentViewannotation lookups are now cached ( b/123709449 )
Version 1.0.0-alpha04
January 30, 2019
androidx.activity:activity 1.0.0-alpha04 and androidx.activity:activity-ktx 1.0.0-alpha04 are released.
Новые функции
- Added support for the
@ContentViewclass annotation that allows you to indicate which layout XML file should be inflated as an alternative to usingsetContentView(). ( 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
activitymodule now depends on version 2.1.0-alpha02 of ViewModel to match theactivity-ktxmodule's dependency.
Version 1.0.0-alpha03
December 17, 2018
androidx.activity 1.0.0-alpha03 is released.
Новые функции
- ComponentActivity now implements
BundleSavedStateRegistryOwnerand 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 ]
Version 1.0.0-alpha02
December 3, 2018
API changes
- Added a note that
getLifecycle()should not be overridden and will be madefinalin a future release. Please file a feature request if you are currently overriding this method. ( aosp/815834 )
Version 1.0.0-alpha01
November 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
OnBackPressedCallbackviaaddOnBackPressedCallbackto receiveonBackPressed()callbacks without needing to override the method in your activity. - Added a new
by viewModels()Kotlin property delegate for retrievingViewModels from aComponentActivity. - Pending input events (such as clicks) are now canceled in
onStop().
API changes
- The implementation of
LifecycleOwnerandViewModelStoreOwnerhave been moved fromFragmentActivitytoComponentActivity. -
onRetainCustomNonConfigurationInstancehas been deprecated. Use aViewModelfor storing objects that need to survive configuration changes.