Активность
Последнее обновление | Стабильный выпуск | Кандидат на выпуск | Бета-версия | Альфа-релиз |
---|---|---|---|---|
9 апреля 2025 г. | 1.10.1 | - | 1.11.0-бета01 | - |
Объявление зависимостей
Чтобы добавить зависимость от Activity, вам необходимо добавить в свой проект репозиторий Google Maven. Для получения дополнительной информации прочтите репозиторий Google Maven .
Добавьте зависимости для нужных вам артефактов в файл build.gradle
для вашего приложения или модуля:
классный
dependencies { def activity_version = "1.10.1" // Java language implementation implementation "androidx.activity:activity:$activity_version" // Kotlin implementation "androidx.activity:activity-ktx:$activity_version" }
Котлин
dependencies { val activity_version = "1.10.1" // Java language implementation implementation("androidx.activity:activity:$activity_version") // Kotlin implementation("androidx.activity:activity-ktx:$activity_version") }
Дополнительные сведения о зависимостях см. в разделе Добавление зависимостей сборки .
Обратная связь
Ваши отзывы помогают сделать Jetpack лучше. Дайте нам знать, если вы обнаружите новые проблемы или у вас есть идеи по улучшению этой библиотеки. Пожалуйста, ознакомьтесь с существующими проблемами в этой библиотеке, прежде чем создавать новую. Вы можете добавить свой голос к существующей проблеме, нажав кнопку со звездочкой.
Дополнительную информацию см. в документации по системе отслеживания проблем .
Версия 1.11
Версия 1.11.0-бета01
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
, предоставляемый функциямиOnBackPressedCallback
handleOnBackStarted
иhandleOnBackProgressed
.
Обновления зависимостей
- Активность теперь компилируется с использованием 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 содержит эти коммиты .
Новые возможности
- В
PickVisualMediaRequest
добавлен APIMediaCapabilities
, позволяющий приложениям указывать свои мультимедийные возможности, например поддерживаемые типы HDR. ( Ic3ee7 )
Версия 1.10
Версия 1.10.1
26 февраля 2025 г.
androidx.activity:activity:1.10.1
, androidx.activity:activity-compose:1.10.1
и androidx.activity:activity-ktx:1.10.1
выпущены. Версия 1.10.1 содержит эти коммиты .
Исправления ошибок
-
ViewTree
OnBackPressedDispatcherOwners
иFullyDrawnReporterOwners
теперь можно разрешить через непересекающиеся родительские элементы представления, такие какViewOverlay
. Дополнительные сведения о родителях непересекающихся представлений см. в примечаниях к выпуску ядра или документации вViewTree.setViewTreeDisjointParent
( Ie7750 )
Версия 1.10.0
15 января 2025 г.
androidx.activity:activity:1.10.0
, androidx.activity:activity-compose:1.10.0
и androidx.activity:activity-ktx:1.10.0
выпущены. Версия 1.10.0 содержит эти коммиты .
Важные изменения с версии 1.9.0
-
PhotoPicker
теперь позволяет выбирать изображения по порядку и выбирать, какая вкладка (альбомы или изображения) должна быть изначально видна. - Контракты
PickVisualMedia
иPickMultipleVisualMedia
Activity Result, которые запускают средство выбора фотографий, больше не делегируют напрямую службам Google Play, если системное средство выбора фотографий недоступно, но используют общедоступное действиеACTION_SYSTEM_FALLBACK_PICK_IMAGES
и связанные дополнительные функции, чтобы обеспечить единообразную работу средства выбора фотографий для OEM-производителей и системных приложений в качестве запасного варианта. - Новая локальная композиция
LocalActivity
, которая предоставляетActivity
для текущей области, устраняя необходимость для разработчиков получатьActivity
изLocalContext
.
Версия 1.10.0-rc01
11 декабря 2024 г.
androidx.activity:activity:1.10.0-rc01
, androidx.activity:activity-compose:1.10.0-rc01
и androidx.activity:activity-ktx:1.10.0-rc01
выпущены. Версия 1.10.0-rc01 содержит эти коммиты .
Исправления ошибок
- Исправлена проблема, из-за которой изменение включенного состояния, когда
PredictiveBackHandler
в данный момент активен, немедленно приводило к короткому замыканию обратного вызова. Теперь он завершит текущий обратный вызов независимо от изменений включенного статуса. ( Ib8719 )
Версия 1.10.0-бета01
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 , б / 283009666 )
Исправления ошибок
- Из действия
1.9.3
:PredictiveBackHandler
больше не будет запускать обратный вызов после отключения обработчика. Это устранит проблему, из-за которойNavHost
из Navigation Compose вызывал исключениеIndexOutOfBoundsException
. ( I3f75e , б / 365027664 , б / 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
иPickMultipleVisualMedia
Activity Result, которые запускают средство выбора фотографий, больше не делегируют напрямую службам Google Play, если системное средство выбора фотографий недоступно, но используют общедоступное действиеACTION_SYSTEM_FALLBACK_PICK_IMAGES
и связанные дополнительные функции, чтобы обеспечить единообразную работу средства выбора фотографий для OEM-производителей и системных приложений в качестве запасного варианта. Это не должно влиять на взаимодействие с пользователем на устройствах, на которых установлена последняя версия сервисов Google Play. ( I3513d )
Исправления ошибок
- Убрано ручное определение доступа к API новой платформы, поскольку это происходит автоматически посредством моделирования API при использовании R8 с AGP 7.3 или новее (например, R8 версии 3.3) и для всех сборок при использовании AGP 8.1 или новее (например, D8 версии 8.1). Клиентам, не использующим AGP, рекомендуется обновить D8 до версии 8.1 или более поздней. Более подробную информацию можно найти в этой статье . ( I9496c , б/345472586 )
- Из действия
1.9.2
: исправлена проблема, из-за которой API Activity ComposePredictiveBackHandler
продолжал обрабатывать жест возврата системы в кадре, в котором он был отключен, что могло привести к тому, что библиотеки, такие как Navigation Compose, обрабатывали обратную обработку даже с пустым обратным стеком, что приводило к выдачеIndexOutOfBoundsException
. ( Ие3301 , б/340202286 ) - Из действия
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 , б/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
. ( Ие3301 , б/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()
при обработке обратного вызова, так как это всегда будет нарушать Predictive Back Animation . Более подробную информацию можно найти в руководстве по передовому опыту . - Остальные API активности были переписаны на 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-бета01
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 содержит эти коммиты .
Исправления ошибок
- Исправлено снижение производительности при запуске действия, появившееся в действии
1.9.0-alpha02
, вызванное вызовомOnBackPressedDispatcher
в рамках создания действия. ( 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()
при обработке обратного вызова, так как это всегда будет нарушать Predictive Back Animation . Более подробную информацию можно найти в руководстве по передовому опыту . ( 1e4222 , 2c950d , б/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 содержит эти коммиты.
Котлин-преобразования
-
ActivityResultRegistry
переписан на Kotlin. Это гарантирует, что обнуляемость дженериков в контракте, переданном вregister
будет правильно передана в возвращаемый вамActivityResultLauncher
. ( I121f0 ) -
ActivityResult
переписан на Kotlin. Расширения KotlinActivityResult
, которые поддерживают деструктуризацию вresultCode
и поляхdata
, были перенесены изactivity-ktx
вactivity
. ( I0565a ) - Расширения Kotlin
by viewModels()
дляComponentActivity
иtrackPipAnimationHintView
были перенесены изactivity-ktx
вactivity
. Артефактactivity-ktx
теперь совершенно пуст. ( I0a444 )
Исправления ошибок
- API
enableEdgeToEdge
теперь рисует вокруг любых вырезов дисплея. ( а3644b , б/311173461 ) - Из действия
1.8.2
: исправлено дополнение, передаваемое вACTION_SYSTEM_FALLBACK_PICK_IMAGES
контракта действия по выбору фотографий, чтобы правильно передать ему ключEXTRA_SYSTEM_FALLBACK_PICK_IMAGES_MAX
вместо использования дополнения с ключом"com.google.android.gms.provider.extra.PICK_IMAGES_MAX"
. Если вы являетесь OEM-производителем и внедрили резервную систему Photo Picker, настоятельно рекомендуется поддерживать обе дополнительные функции для обеспечения максимально широкой совместимости. ( 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. ( Ид4615 ) -
PickVisualMediaRequest
теперь имеет тот же минимальный уровень API 19, что и контракт результата действияPickVisualMedia
. ( 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-производителем и внедрили резервную систему Photo Picker, настоятельно рекомендуется поддерживать обе дополнительные функции для обеспечения максимально широкой совместимости. ( I96a00 )
Версия 1.8.1
15 ноября 2023 г.
androidx.activity:activity:1.8.1
, androidx.activity:activity-compose:1.8.1
и androidx.activity:activity-ktx:1.8.1
выпущены. Версия 1.8.1 содержит эти коммиты.
Исправления ошибок
-
OnBackPressedDispatcher
теперь продолжает отправлять правильныйOnBackPressedCallback
даже после добавления новогоOnBackPressedCallback
во время обработки жеста возврата. ( Id0ff6 )
Версия 1.8.0
4 октября 2023 г.
androidx.activity:activity:1.8.0
, androidx.activity:activity-compose:1.8.0
и androidx.activity:activity-ktx:1.8.0
выпущены. Версия 1.8.0 содержит эти коммиты.
Важные изменения с версии 1.7.0
- Predictive Back —
OnBackPressedCallback
теперь предлагает новые обратные вызовы Predictive Back для обработки запуска жеста назад, продвижения на протяжении всего жеста и отмены жеста назад в дополнение к предыдущему обратному вызовуhandleOnBackPressed()
, когда фиксируется жест назад. Сюда также входитPredictiveBackHandler
Composable для обработки событий прогнозируемых жестов назад в Activity Compose. Он предоставляет поток объектов BackEventCompat, которые необходимо собрать в предоставленной вами приостанавливающей ламбе:
PredictiveBackHandler { progress: Flow<BackEventCompat> ->
// code for gesture back started
try {
progress.collect { backEvent ->
// code for progress
}
// code for completion
} catch (e: CancellationException) {
// code for cancellation
}
}
ComponentActivity.onBackPressed()
устарел в пользу API для обратной обработки. Теперь разработчикам следует использовать OnBackPressedDispatcher
, а не переопределять этот метод.
- EdgeToEdge —
ComponentActivity.enableEdgeToEdge()
был добавлен для простой настройки отображения от края до края с обратной совместимостью.
Версия 1.8.0-rc01
20 сентября 2023 г.
androidx.activity:activity:1.8.0-rc01
, androidx.activity:activity-compose:1.8.0-rc01
и androidx.activity:activity-ktx:1.8.0-rc01
выпущены. Версия 1.8.0-rc01 содержит эти коммиты.
Версия 1.8.0-бета01
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
. ( аосп/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
Composable для обработки событий прогнозируемых жестов назад. Он предоставляет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 , б/294884345 )onBackPressedDispatcher
вComponentActivity
теперь инициализируется лениво, поэтому он создается только при необходимости. ( I0bf8e )
Исправления ошибок
-
ComponentActivity
больше не будет отображать NPE на Android 13, когда он получает обратный вызовonBackPressed()
, а Activity ужеDESTROYED
. ( Idb055 , б/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
, чтобы предоставить собственную логику для обнаружения ночного режима. ( аосп/2546393 , б/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 , б/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
. Это было выпущено из внутренней ветки.
Исправления ошибок
- Из действия 1.7.1 : —
ReportFullyDrawExecuter
больше не протекает при использованииComponentActivity
сActivityScenario
. ( Id2ff2 , б/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 , б/271596918 ) -
ComponentDialog
иComponentActivity
теперь содержат общедоступный APIinitViewTreeOwners()
который будет использоваться для инициализации всех владельцев дерева представлений перед настройкой представления содержимого. ( Ibdce0 , б/261314581 )
Исправления ошибок
- Исправлена проблема, из-за которой фрагменты неправильно признавали недействительными MenuHosts и приводили к неожиданному поведению других меню в действии. ( I9404e , б/244336571 )
Другие изменения
-
ActivityResultRegister
теперь использует KotlinRandom
вместо Java. ( I4d98f , б/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
. Разработан из внутренней ветки.
Обновление зависимостей
- Из действия
1.7.0-rc01
: действие теперь зависит от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
теперь содержит новые обратные вызовы прогресса Predictive Back для обработки запуска жеста назад, выполнения на протяжении всего жеста и отмены жеста назад в дополнение к предыдущему обратному вызову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 , б/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 , б/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, реализуя резервное действие . Средство выбора фотографий будет использовать этот резервный вариант, если он доступен, прежде чем вернуться к использованиюIntent.ACTION_OPEN_DOCUMENT
, который продолжает поддерживать все устройства API 19 и более поздних версий. -
ComponentDialog
теперь реализуетSavedStateRegistryOwner
и имеет доступ к своему собственномуSavedStateRegistry
и устанавливаетSavedStateRegistryOwner
для своегоViewTree
. Теперь можно использовать Jetpack Compose внутриComponentDialog
, поскольку он соответствует какLifecycleOwner
, так иSavedStateRegistryOwner
прикрепленным к окну через требования APIViewTree
. -
IntentSenderRequest.Builder.setFlags()
теперь позволяет вам устанавливать несколько флагов изIntent
, а не только один флаг.
Котлин-конвертация
Ряд классов Activity был преобразован в Kotlin. Все преобразованные классы по-прежнему сохраняют двоичную совместимость с предыдущими версиями. Следующие классы имеют изменения , несовместимые с исходным кодом для классов, написанных на Kotlin: ActivityResultRegistryOwner
, OnBackPressedDispatcherOwner
.
В таблице ниже представлены исходные преобразования для новой версии Activity:
Мероприятие 1.5 | Мероприятие 1.6 |
---|---|
override fun getActivityResultRegistry() = activityResultRegistry | override val activityResultRegistry = activityResultRegistry |
override fun getOnBackPressedDispatcher() = onBackPressedDispatcher | override val onBackPressedDispatcher = onBackPressedDispatcher |
Эти классы также были преобразованы в Kotlin, но остались совместимыми с исходным кодом: ContextAware
, ContextAwareHelper
, OnContextAvailableListener
, IntentSenderRequest
и OnBackPressedDispatcher
API FullyDrawnReporter
ComponentActivity
теперь предоставляет экземпляр FullyDrawnReporter
, который позволяет нескольким компонентам сообщать, когда они готовы к взаимодействию. ComponentActivity
будет ждать завершения работы всех компонентов, прежде чем вызывать reportFullyDrawn()
от вашего имени. Эти API отвечают за требования к времени, и их не нужно вызывать как часть вызова onDraw
.
Эти API рекомендуется включать:
- Сигнализация среды выполнения Android после завершения запуска, чтобы гарантировать, что весь код, выполняемый во время многокадровой последовательности запуска, включен и имеет приоритет для фоновой компиляции.
- Сигнализация Macrobenchmark и Play Vitals, когда ваше приложение следует считать полностью прорисованным для показателей запуска, чтобы вы могли отслеживать производительность.
Были добавлены три API-интерфейса Activity Compose, чтобы сделать более удобным использование FullyDrawnReporter
из отдельных компонуемых объектов:
-
ReportDrawn
указывает, что ваш составной объект немедленно готов к взаимодействию. -
ReportDrawnWhen
принимает предикат (т. е.list.count > 0
), чтобы указать, когда ваш составной объект готов к взаимодействию. -
ReportDrawnAfter
принимает метод приостановки, который по завершении указывает, что вы готовы к взаимодействию.
Обновления зависимостей
- Активность теперь зависит от жизненного цикла
2.6.1
. ( 8fc31d ) - Активность теперь зависит от ProfileInstaller
1.3.0
. ( 83d3b1 )
Версия 1.7.0-rc01
8 марта 2023 г.
androidx.activity:activity:1.7.0-rc01
, androidx.activity:activity-compose:1.7.0-rc01
и androidx.activity:activity-ktx:1.7.0-rc01
выпущены. Версия 1.7.0-rc01 содержит эти коммиты.
Обновление зависимостей
- Активность теперь зависит от
Lifecycle 2.6.0
.
Версия 1.7.0-бета02
22 февраля 2023 г.
Выпущены androidx.activity:activity:1.7.0-beta02
, androidx.activity:activity-compose:1.7.0-beta02
и androidx.activity:activity-ktx:1.7.0-beta02
. Версия 1.7.0-beta02 содержит эти коммиты.
Изменения API
- Действия и дополнительные функции, используемые контрактами
PickVisualMedia
иPickMultipleVisualMedia
в качестве запасного варианта на случай, еслиMediaStore.ACTION_PICK_IMAGES
недоступен, теперь являются общедоступными константами, которые обеспечивают стабильность API для OEM-производителей и системных приложений, которые хотят обеспечить единообразную работу средства выбора фотографий. Реализация этого резервного варианта по-прежнему ограничена только системными приложениями. ( Icd320 )
Версия 1.7.0-бета01
8 февраля 2023 г.
Выпущены androidx.activity:activity:1.7.0-beta01
, androidx.activity:activity-compose:1.7.0-beta01
и androidx.activity:activity-ktx:1.7.0-beta01
. Версия 1.7.0-beta01 содержит эти коммиты.
Новые возможности
-
IntentSenderRequest.Builder.setFlags()
теперь позволяет вам устанавливать несколько флагов изIntent
, а не только один флаг. ( Iac04c )
Исправления ошибок
- Альтернативный вариант
PickVisualMedia
на случай, если платформа Photo Picker недоступна, теперь корректно ограничивает обработку приложениями, установленными в системном образе устройства. ( Если8ае6 )
Котлин-преобразования
-
ActivityResultRegistryOwner
теперь написан на Kotlin. Это изменение, несовместимое с исходным кодом для классов, написанных на Kotlin — теперь вам необходимо переопределить свойствоactivityResultRegistry
, а не реализовывать предыдущую функциюgetActivityResultRegistry()
. ( I0b00e ) -
OnBackPressedDispatcherOwner
теперь написан на Kotlin. Это изменение, несовместимое с исходным кодом для классов, написанных на Kotlin — теперь вам необходимо переопределить свойствоonBackPressedDispatcher
, а не реализовывать предыдущую функциюgetOnBackPressedDispatcher
. ( Ia277d ) -
ContextAware
,ContextAwareHelper
,OnContextAvailableListener
,IntentSenderRequest
иOnBackPressedDispatcher
теперь написаны на Kotlin. ( I1a73e , Iada92 , aosp/2410754 , I18ac7 , b/257291701 )
Версия 1.7.0-альфа04
25 января 2023 г.
Выпущены androidx.activity:activity:1.7.0-alpha04
, androidx.activity:activity-compose:1.7.0-alpha04
и androidx.activity:activity-ktx:1.7.0-alpha04
. Версия 1.7.0-alpha04 содержит эти коммиты.
Новые возможности
- Контракты
PickVisualMedia
иPickMultipleVisualMedia
Activity Result теперь будут использовать средство выбора фотографий, предоставляемое службами Google Play, если оно доступно, в тех случаях, когда средство выбора фотографий, предоставленное системой Android (например,MediaStore.ACTION_PICK_IMAGES
), недоступно. APIisPhotoPickerAvailable()
, который определяет только систему Android, предоставляемую Photo Picker, устарел. Рекомендуется использовать новый APIisPhotoPickerAvailable(Context)
, который возвращает значение, если доступен любой из средств выбора фотографий. ( I55be6 )
Версия 1.7.0-альфа03
11 января 2023 г.
Выпущены androidx.activity:activity:1.7.0-alpha03
, androidx.activity:activity-compose:1.7.0-alpha03
и androidx.activity:activity-ktx:1.7.0-alpha03
. Версия 1.7.0-alpha03 содержит эти коммиты.
Новые возможности
-
ComponentDialog
теперь реализуетSavedStateRegistryOwner
и имеет доступ к своему собственномуSavedStateRegistry
и устанавливаетSavedStateRegistryOwner
для своего ViewTree. Теперь можно использовать Jetpack Compose внутриComponentDialog
, поскольку он соответствует какLifecycleOwner
, так иSavedStateRegistryOwner
прикрепленным к окну через требования API ViewTree. ( Idca17 , I73468 б/261162296 )
Изменения API
- Добавлен составной элемент
ReportDrawn
, который немедленно помечает активность как готовую к вызовуreportFullyDrawn
. ( Ic5b14 , б/259687964 )
Котлин-преобразования
- Классы
ActvitiyResultCallback
иOnBackPressedCallback
были преобразованы в Kotlin с сохранением совместимости исходного кода и двоичного кода. ( Ifc5e5 , Ide1b0 , b/257291701 )
Версия 1.7.0-альфа02
24 октября 2022 г.
Выпущены androidx.activity:activity:1.7.0-alpha02
, androidx.activity:activity-compose:1.7.0-alpha02
и androidx.activity:activity-ktx:1.7.0-alpha02
. Версия 1.7.0-alpha02 содержит эти коммиты.
Исправления ошибок
- Из действия
1.6.1
: исправлена проблема, из-за которой контракт результата действияPickMultipleVisualMedia
не запускался на устройствах Android R при использовании значения по умолчанию дляmaxItems
. ( Ие2776 , б/249182130 )
Версия 1.7.0-альфа01
5 октября 2022 г.
Выпущены androidx.activity:activity:1.7.0-alpha01
, androidx.activity:activity-compose:1.7.0-alpha01
и androidx.activity:activity-ktx:1.7.0-alpha01
. Версия 1.7.0-alpha01 содержит эти коммиты.
API FullyDrawnReporter
ComponentActivity
теперь предоставляет экземпляр FullyDrawnReporter
, который позволяет нескольким компонентам сообщать, когда они готовы к взаимодействию. ComponentActivity
будет ждать завершения работы всех компонентов, прежде чем вызывать reportFullyDrawn()
от вашего имени. Эти API отвечают за требования к времени, и их не нужно вызывать как часть вызова onDraw
.
Эти API рекомендуется включать:
- Сигнализация среды выполнения Android после завершения запуска, чтобы гарантировать, что весь код, выполняемый во время многокадровой последовательности запуска, включен и имеет приоритет для фоновой компиляции.
- Сигнализация Macrobenchmark и Play Vitals, когда ваше приложение следует считать полностью прорисованным для показателей запуска, чтобы вы могли отслеживать производительность.
Были добавлены два API-интерфейса Activity Compose, чтобы сделать более удобным использование FullyDrawnReporter
из отдельных компонуемых объектов:
-
ReportDrawnWhen
принимает предикат (т. е.list.count > 0
), чтобы указать, когда ваш составной объект готов к взаимодействию. -
ReportDrawnAfter
принимает метод приостановки, который по завершении указывает, что вы готовы к взаимодействию.
Версия 1.6.1
Версия 1.6.1
24 октября 2022 г.
androidx.activity:activity:1.6.1
, androidx.activity:activity-compose:1.6.1
и androidx.activity:activity-ktx:1.6.1
выпущены. Версия 1.6.1 содержит эти коммиты.
Исправления ошибок
- Исправлена проблема, из-за которой контракт результата активности
PickMultipleVisualMedia
не запускался на устройствах Android R при использовании значения по умолчанию дляmaxItems
. ( Ие2776 , б/249182130 )
Версия 1.6.0
Версия 1.6.0
21 сентября 2022 г.
androidx.activity:activity:1.6.0
, androidx.activity:activity-compose:1.6.0
и androidx.activity:activity-ktx:1.6.0
выпущены. Версия 1.6.0 содержит эти коммиты.
Важные изменения с версии 1.5.0
- Добавлены
ActivityResultContracts.PickVisualMedia
иActivityResultContracts.PickMultipleVisualMedia
для предоставления обратно совместимого контракта, который используетMediaStore.ACTION_PICK_IMAGES
, когда средство выбора фотографий доступно, иIntent.ACTION_OPEN_DOCUMENT
когда оно недоступно. -
OnBackInvokedCallback
в Android 13 интегрирован вOnBackPressedDispatchers
, предоставляемыйComponentActivity
иComponentDialog
. Это гарантирует, что все API, созданные наOnBackPressedDispatcher
будут работать при включении прогнозируемого жеста назад .
Версия 1.6.0-rc02
7 сентября 2022 г.
androidx.activity:activity:1.6.0-rc02
, androidx.activity:activity-compose:1.6.0-rc02
и androidx.activity:activity-ktx:1.6.0-rc02
выпущены. Версия 1.6.0-rc02 содержит эти коммиты.
Исправления ошибок
-
OnBackPressedDispatcher
теперь регистрируетOnBackInvokedCallback
с помощьюPRIORITY_DEFAULT
вместоPRIORITY_OVERLAY
. ( I3901f ) - Классы, расширяющие
ComponentActivity
теперь всегда будут отправлять оба своих обратных вызоваonMultiWindowModeChanged()
. ( Ic4d85 ) -
ActivityResultRegistry
больше не вернет результат вActivityResultCallback
, когдаlaunch
вызовов бросает любоеException
, а обратный вызов был зарегистрирован безLifecycleOwner
. ( IA7FF7 , B/238350794 ) -
ComponentActivity
теперь будет правильно отправлять вызовы меню без необходимости вызов супер функции в вашей деятельности. ( IE33C5 , B/238057118 )
Обновление зависимости
- Библиотека
Activity
теперь зависит от жизненного цикла2.5.1
. ( IF6697 )
Версия 1.6.0-rc01
24 августа 2022 года
androidx.activity:activity:1.6.0-rc01
, androidx.activity:activity-compose:1.6.0-rc01
и androidx.activity:activity-ktx:1.6.0-rc01
выпускаются. Версия 1.6.0-rc01 содержит эти коммиты.
Исправления ошибок
- Инициализация
OnBackPressedDispatcher
больше не будет вызыватьClassVerificationError
и при использовании версий SDK до 33. ( IC32E1 ) - Классы, которые переопределяют
ComponentActivity
onPictureInPictureModeChanged()
обратный вызов, теперь всегда будут отправлены их обратные вызовы. ( Ib7fdb )
Версия 1.6.0-бета01
10 августа 2022 года
androidx.activity:activity:1.6.0-beta01
, androidx.activity:activity-compose:1.6.0-beta01
и androidx.activity:activity-ktx:1.6.0-beta01
. Версия 1.6.0-beta01 содержит эти коммиты.
Изменения API
- Оценка устарела методы
startActivityForResult
иstartIntentSenderForResult
наComponentActivity
с@NonNull
, потому что прохождениеnull
всегда привело к аварии. ( ID2A25 , B/231476082 )
Исправления ошибок
- Из деятельности
1.5.1
:ActivityResultRegistry
больше не вернет результат вActivityResultCallback
, когдаlaunch
вызовов бросает любоеException
, а обратный вызов был зарегистрирован безLifecycleOwner
. ( IA7FF7 , B/238350794 ) - Из деятельности
1.5.1
:ComponentActivity
теперь будет должным образом отправлять вызовы меню вonPrepareOptionMenu()
,onCreateOptionsMenu()
иonOptionsItemSelected()
переопределяется без необходимости вызовать супер функции. ( IE33C5 , B/238057118 )
Обновление зависимости
- От действия
1.5.1
: БиблиотекаActivity
теперь зависит отLifecycle
версии2.5.1
. ( IF6697 )
Версия 1.6.0-альфа05
15 июня 2022 года
androidx.activity:activity:1.6.0-alpha05
, androidx.activity:activity-compose:1.6.0-alpha05
и androidx.activity:activity-ktx:1.6.0-alpha05
. Версия 1.6.0-Alpha05 была разработана в частном филиале перед выпуском и не имеет общественных коммитов.
Изменения API
-
minCompileSdk
сейчас 33, чтобы соответствовать TIRAMISU BETA 3 SDK
Исправления ошибок
- Фиксированный сбой на более старых устройствах при прохождении проверки расширения SDK для
PickVisualMedia
ActivityResultContract
, чтобы теперь он должен работать сACTION_OPEN_DOCUMENT
на устройствах под управлением Android 10 и ниже.
Версия 1.6.0-альфа04
18 мая 2022 года
androidx.activity:activity:1.6.0-alpha04
и androidx.activity:activity-ktx:1.6.0-alpha04
выпускаются.
Исправления ошибок
- Исправлена ошибка в
PickVisualMediaRequest
, где попытка создать запрос, либо через строитель, так и функцию Kotlin верхнего уровня, приведет к переполнению стека. - Интегрировал
OnBackInvokedCallback
в Android 13 Dev Beta 2 вOnBackPressedDispatcher
, предоставленныйComponentDialog
. Это гарантирует, что все API, основанные наOnBackPressedDispatcher
, работая при включении прогнозирующего жеста .
Версия 1.6.0-альфа03
27 апреля 2022 года
androidx.activity:activity:1.6.0-alpha03
, androidx.activity:activity-compose:1.6.0-alpha03
и androidx.activity:activity-ktx:1.6.0-alpha03
выпускаются.
- Примечание. Эта версия будет компилироваться только против разработчика Android 13 Beta 1 SDK.
Новые возможности
- Добавлены
ActivityResultContracts.PickVisualMedia
иActivityResultContracts.PickMultipleVisualMedia
для предоставления обратного совместимого договора, который используетMediaStore.ACTION_PICK_IMAGES
, когда доступен сборщик фото иIntent.ACTION_OPEN_DOCUMENT
когда он недоступен. - Интегрировал
OnBackInvokedCallback
в Android 13 Dev Beta 1 вOnBackPressedDispatcher
, предоставленныйComponentActivity
. Это гарантирует, что все API, основанные наOnBackPressedDispatcher
, работая при включении прогнозирующего жеста .
Версия 1.6.0-альфа01
23 марта 2022 года
androidx.activity:activity:1.6.0-alpha01
, androidx.activity:activity-compose:1.6.0-alpha01
и androidx.activity:activity-ktx:1.6.0-alpha01
высвобождаются.
- Примечание. Эта версия будет компилироваться только против разработчика Android 13 Preview 2 SDK.
Новые возможности
- Интегрированные изменения в Android 13 Dev Preview 2 в
ComponentActivity
.
Версия 1.5.1
Версия 1.5.1
27 июля 2022 года
androidx.activity:activity:1.5.1
, androidx.activity:activity-compose:1.5.1
, и androidx.activity:activity-ktx:1.5.1
выпускаются. Версия 1.5.1 содержит эти коммиты.
Исправления ошибок
ActivityResultRegistry
больше не вернет результат вActivityResultCallback
, когда вызовlaunch()
вызовет любоеException
, а обратный вызов был зарегистрирован безLifecycleOwner
. ( IA7FF7 , B/238350794 )ComponentActivity
теперь будет правильно отправлять вызовы меню вonPrepareOptionMenu()
,onCreateOptionsMenu()
иonOptionsItemSelected()
переопределения без необходимости вызовать супер функцию. ( IE33C5 , B/238057118 )
Обновление зависимости
- Библиотека
Activity
теперь зависит от жизненного цикла2.5.1
. ( IF6697 )
Версия 1.5.0
Версия 1.5.0
29 июня 2022 года
androidx.activity:activity:1.5.0
, androidx.activity:activity-compose:1.5.0
, и androidx.activity:activity-ktx:1.5.0
выпускаются. Версия 1.5.0 содержит эти коммиты.
Важные изменения с 1.4.0
- ComponentDialog -
ComponentDialog
- это подклассDialog
, который включает в себяOnBackPressedDispatcher
, который будет вызван при нажатии кнопки «Система» и диалоговое окно. Важно отметить, что этот подкласс также устанавливаетViewTreeOnBackPressedDispatcherOwner
, позволяя представлениям общий способ получить правильный диспетчер, независимо от того, существует ли он вComponentActivity
илиComponentDialog
. - Интерфейсы обратного вызова -
ComponentActivity
теперь реализует набор модульных интерфейсов обратного вызова, которые можно использовать вместоActivity
вызовов. Эти интерфейсы включают в себя следующее:OnNewIntentProvider
,OnConfigurationChangedProvider
,OnTrimMemoryProvider
,OnPictureInPictureModeChangedProvider
,OnMultiWindowModeChangedProvider
- CreationExtras Integration -
ComponentActivity
теперь имеет возможность обеспечить бездействиеViewModelProvider.Factory
через LifeCycle2.5.0
'CreationExtras
.
Другие изменения
- Конструктор без параметров для
ActivityResultContracts.CreateDocument
был устарел и заменен новым конструктором, который принимает конкретный тип MIME (например, «Image/png»), как требуетсяIntent.ACTION_CREATE_DOCUMENT
.
Версия 1.5.0-rc01
11 мая 2022 года
androidx.activity:activity:1.5.0-rc01
, androidx.activity:activity-compose:1.5.0-rc01
и androidx.activity:activity-ktx:1.5.0-rc01
высвобождаются без изменений из 1.5.0-бита01. Версия 1.5.0-rc01 содержит эти коммиты.
Версия 1.5.0-бета01
20 апреля 2022 года
androidx.activity:activity:1.5.0-beta01
, androidx.activity:activity-compose:1.5.0-beta01
и androidx.activity:activity-ktx:1.5.0-beta01
выпускаются. Версия 1.5.0-beta01 содержит эти коммиты.
Обновления зависимости
- Активность теперь зависит от жизненного цикла
2.4.0-beta01
.
Версия 1.5.0-Alpha05
6 апреля 2022 года
androidx.activity:activity:1.5.0-alpha05
, androidx.activity:activity-compose:1.5.0-alpha05
и androidx.activity:activity-ktx:1.5.0-alpha05
. Версия 1.5.0-Alpha05 содержит эти коммиты.
Исправления ошибок
-
ComponentActivity
onPanelClosed()
теперь также вызывает SuperonPanelClosed()
, решает проблему, при которой методonContextMenuClosed
не будет вызван. ( IB6F77 )
Версия 1.5.0-альфа04
23 марта 2022 года
androidx.activity:activity:1.5.0-alpha04
, androidx.activity:activity-compose:1.5.0-alpha04
и androidx.activity:activity-ktx:1.5.0-alpha04
. Версия 1.5.0-alpha04 содержит эти коммиты.
Исправления ошибок
-
SavedStateViewFactory
теперь поддерживает использованиеCreationExtras
даже если он был инициализирован с помощьюSavedStateRegistryOwner
. Если предоставляются дополнения, инициализированные аргументы игнорируются. ( I6c43b , b/224844583 )
Версия 1.5.0-Alpha03
23 февраля 2022 года
androidx.activity:activity:1.5.0-alpha03
, androidx.activity:activity-compose:1.5.0-alpha03
и androidx.activity:activity-ktx:1.5.0-alpha03
. Версия 1.5.0-Alpha03 содержит эти коммиты.
Изменения API
- Теперь вы можете перенести
CreationExtras
в действиеby viewModels()
( i6a3e6 , b/217600303 )
Версия 1.5.0-Alpha02
9 февраля 2022 года
androidx.activity:activity:1.5.0-alpha02
, androidx.activity:activity-compose:1.5.0-alpha02
и androidx.activity:activity-ktx:1.5.0-alpha02
. Версия 1.5.0-Alpha02 содержит эти коммиты.
Новые возможности
-
ComponentActivity
теперь реализует интерфейсOnPictureInPictureModeChangedProvider
, позволяющий любому компоненту получать события изменения в картинке в картине. ( I9f567 ) -
ComponentActivity
теперь реализует интерфейсOnMultiWindowModeChangedProvider
, чтобы позволить любому компоненту принимать события изменения режима с несколькими окнами. ( I62d91 )
Версия 1.5.0-Alpha01
26 января 2022 года
androidx.activity:activity:1.5.0-alpha01
, androidx.activity:activity-compose:1.5.0-alpha01
и androidx.activity:activity-ktx:1.5.0-alpha01
. Версия 1.5.0-Alpha01 содержит эти коммиты.
Новые возможности
-
ComponentActivity
теперь интегрируется с ViewModel CreationExtras, введенным в рамках жизненного цикла2.5.0-alpha01
. ( IE7E00 , B/207012584 ) - Добавлен
ComponentDialog
, подклассDialog
, который включает в себяOnBackPressedDispatcher
, который будет вызван, когда кнопка «Окна» нажатится, когда диалог виден. Важно отметить, что этот подкласс также устанавливаетViewTreeOnBackPressedDispatcherOwner
, позволяя представлениям общий способ получить правильный диспетчер, независимо от того, существует ли он вComponentActivity
илиComponentDialog
. ( I8a1bc ) -
ComponentActivity
теперь реализует новый интерфейсOnNewIntentProvider
, чтобы позволить любому компоненту получать эти события. ( If1f8b ) -
ComponentActivity
теперь реализует новый интерфейсOnConfigurationChangedProvider
, чтобы позволить любому компоненту получать эти события. ( If623b ) -
ComponentActivity
теперь реализует новый интерфейсOnTrimMemoryProvider
, чтобы позволить любому компоненту получать эти события. ( IA9295 )
Изменения API
- Конструктор без параметров для
ActivityResultContracts.CreateDocument
был устарел и заменен новым конструктором, который принимает конкретный тип MIME (например,"image/png"
), как требуетсяIntent.ACTION_CREATE_DOCUMENT
. ( I2bec6 ) -
OnBackPressedDispatcherOwner
связанный с представлением, теперь может быть получен черезViewTreeOnBackPressedDispatcherOwner
, а не полагаться на составContext
. ( I74685 )
Исправления ошибок
- Исправлена сбоем при доступе к
ViewModel
в первый раз из обратного вызововregisterForActivityResult()
или обратных вызовов вLifecycleObserver
, добавленную в рамкахinit
ComponentActivity
. ( IFE83F )
Версия 1.4.0
Версия 1.4.0
27 октября 2021 года
androidx.activity:activity:1.4.0
, androidx.activity:activity-compose:1.4.0
, и androidx.activity:activity-ktx:1.4.0
выпускаются. Версия 1.4.0 содержит эти коммиты.
Важные изменения с 1.3.0
- Androidx
ComponentActivity
теперь реализует интерфейсMenuHost
. Это позволяет любому компоненту добавлять элементы меню вActionBar
, добавив в действие экземплярMenuProvider
. КаждоеMenuProvider
можно добавить с помощьюLifecycle
, который автоматически контролирует видимость этих пунктов меню на основе состоянияLifecycle
и обрабатывать удалениеMenuProvider
, когдаLifecycle
уничтожен. - Класс
ActivityResultContract
был переписан в Kotlin, чтобы гарантировать, что разработчики, пишущие пользовательские контракты в Kotlin, могут определить правильную нулясь для их классов ввода и вывода. - Класс
ActivityResultContracts
и его контракты были переписаны в Котлине, чтобы обеспечить надлежащую нуль.
Версия 1.4.0-RC01
13 октября 2021 года
androidx.activity:activity:1.4.0-rc01
, androidx.activity:activity-compose:1.4.0-rc01
и androidx.activity:activity-ktx:1.4.0-rc01
высвобождаются. Версия 1.4.0-RC01 содержит эти коммиты.
Исправления ошибок
-
ActivityResultRegistry
больше не вернет результат вActivityResultCallback
, когдаlaunch
вызовов бросает любоеException
. ( IF4F91 , B/200845664 )
Версия 1.4.0-бета01
29 сентября 2021 года
androidx.activity:activity:1.4.0-beta01
, androidx.activity:activity-compose:1.4.0-beta01
и androidx.activity:activity-ktx:1.4.0-beta01
выпускаются. Версия 1.4.0-бета01 содержит эти коммиты.
Изменения API
- Исправлена тип для
ActivityResultContracts.OpenMultipleDocuments
иActivityResultContracts.GetMultipleContents
, которые заставили затем использовать выходной типList<? extends Uri>
при использовании кода из языка программирования Java. ( If71de ) - Общественные константы в рамках
ActivityResultContracts.StartActivityForResult
,ActivityResultContracts.StartIntentSenderForResult
иActivityResultContracts.RequestMultiplePermissions
теперь доступны при использовании Kotlin через свои нынеCompanion
объекты. ( AOSP/1832555 )
Обновления документации
- Сообщение об испаке для API, которые теперь обрабатывают API -интерфейсы результатов деятельности , а именно
startActivityForResult
,startIntentSenderForResult
,onActivityResult
,requestPermissions
иonRequestPermissionsResult
, все были расширены с более подробной информацией. ( CCE80F )
Версия 1.4.0-Alpha02
15 сентября 2021 года
androidx.activity:activity:1.4.0-alpha02
, androidx.activity:activity-compose:1.4.0-alpha02
и androidx.activity:activity-ktx:1.4.0-alpha02
. Версия 1.4.0-Alpha02 содержит эти коммиты.
Новые возможности
- Артефакт
activity-compose
в настоящее время содержит ошибку LintLaunchDuringComposition
, которая мешает вам вызвать методlaunch
ActivityResultLauncher
как часть композиции, поскольку композиция должна быть свободна от побочного эффекта. Используйте API для обработки побочных эффектов . ( 7C2BBE , B/191347220 )
Изменения API
- Класс
ActivityResultContract
был переписан в Kotlin, чтобы гарантировать, что разработчики, пишущие пользовательские контракты в Kotlin, могут определить правильную нулясь для их классов ввода и вывода. ( I8a8f5 ) - Класс
ActivityResultContracts
и его контракты были переписаны в Котлине, чтобы обеспечить надлежащую нуль. ( I69802 )
Версия 1.4.0-Alpha01
1 сентября 2021 года
androidx.activity:activity:1.4.0-alpha01
, androidx.activity:activity-compose:1.4.0-alpha01
и androidx.activity:activity-ktx:1.4.0-alpha01
. Версия 1.4.0-Alpha01 содержит эти коммиты.
Новые возможности
- Androidx
ComponentActivity
теперь реализует интерфейсMenuHost
. Это позволяет любому компоненту добавлять элементы меню вActionBar
, добавив экземплярMenuProvider
в действие. КаждоеMenuProvider
можно добавить с помощьюLifecycle
, который автоматически контролирует видимость этих пунктов меню на основе состоянияLifecycle
и обрабатывать удалениеMenuProvider
, когдаLifecycle
уничтожен. ( 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)
}
Поведение изменяется
-
ActivityResultRegistry
теперь будет выброситьIllegalStateException
при попытке позвонитьlaunch()
наActivityResultLauncher
, который не зарегистрирован или который не был зарегистрирован. ( IDA75D , B/192567522 )
Внешний вклад
Версия 1.3.1
Версия 1.3.1
4 августа 2021 года
androidx.activity:activity:1.3.1
, androidx.activity:activity-compose:1.3.1
, и androidx.activity:activity-ktx:1.3.1
выпускаются. Версия 1.3.1 содержит эти коммиты.
Обновления зависимости
- Деятельность теперь зависит от котлина
1.5.21
. - СООБЩЕНИЕ СОЗДАНИЯ В настоящее время зависит от составления
1.0.1
.
Версия 1.3.0
Версия 1.3.0
28 июля 2021 года
androidx.activity:activity:1.3.0
, androidx.activity:activity-compose:1.3.0
, и androidx.activity:activity-ktx:1.3.0
выпускаются. Версия 1.3.0 содержит эти коммиты.
Важные изменения с 1.2.0
- Активное сочинение артефакт - Артефакт
activity-compose
обеспечивает метод расширенияsetContent
для размещения вашего JetPack Compose UI в действии и сочинять конкретные обертки для взаимодействия с APIComponentActivity
для обработки кнопки «Система» и API -интерфейсы результатов активности. Смотрите документацию для более подробной информации. - CaptureVideo Contract -
CaptureVideo
ActivityResultContract
заменяет теперь устаревший контрактTakeVideo
и возвращает логический обозначение успеха, который работает во многих приложениях для камеры. - Отслеживание подсказки для изображения в картине -Пользователи
activity-ktx
теперь могут использовать методActivity
trackPipAnimationHintView
для автоматического восстановленияPictureInPictureParams
с новой позицией представления, поскольку он меняет положение относительно окна.
Версия 1.3.0-RC02
14 июля 2021 года
androidx.activity:activity:1.3.0-rc02
, androidx.activity:activity-compose:1.3.0-rc02
и androidx.activity:activity-ktx:1.3.0-rc02
высвобождаются. Версия 1.3.0-RC02 содержит эти коммиты.
Исправления ошибок
- Обратные вызовы
ActivityResultRegistry
теперь должным образом сохраняются и восстанавливаются, поэтому обратные вызовы не дублируются в сохранении. ( I97816 , B/191893160 )
Версия 1.3.0-RC01
1 июля 2021 года
androidx.activity:activity:1.3.0-rc01
, androidx.activity:activity-compose:1.3.0-rc01
и androidx.activity:activity-ktx:1.3.0-rc01
высвобождаются без изменений из 1.3.0-beta02
. Версия 1.3.0-RC01 содержит эти коммиты.
Версия 1.3.0-бета02
16 июня 2021 года
androidx.activity:activity:1.3.0-beta02
, androidx.activity:activity-compose:1.3.0-beta02
и androidx.activity:activity-ktx:1.3.0-beta02
выпускаются. Версия 1.3.0-бета02 содержит эти коммиты.
Обновленная activity-compose
, чтобы зависеть от составления 1.0.0-beta09
. androidx.compose.ui:ui-test-junit4
теперь имеет зависимость от времени компиляции от activity-compose
.
Версия 1.3.0-бета01
2 июня 2021 года
androidx.activity:activity:1.3.0-beta01
, androidx.activity:activity-compose:1.3.0-beta01
и androidx.activity:activity-ktx:1.3.0-beta01
выпускаются. Версия 1.3.0-бета01 содержит эти коммиты.
Изменения API
- Ранее устаревший метод
@Composable registerForActivityResult()
был удален. Пожалуйста, используйтеrememberLauncherForActivityResult()
. ( IC39D3 )
Версия 1.3.0-Alpha08
18 мая 2021 года
androidx.activity:activity:1.3.0-alpha08
, androidx.activity:activity-compose:1.3.0-alpha08
и androidx.activity:activity-ktx:1.3.0-alpha08
. Версия 1.3.0-Alpha08 содержит эти коммиты.
Новые возможности
- Новый
CaptureVideo
ActivityResultContract
возвращает логическое значение для вашейActivityResultCallback
, что указывает, было ли ваше видео успешно сохранено в данном URI. Это заменяет устаревший контрактTakeVideo
, поскольку приложения камеры очень редко поддерживают возвращение растровой карты миниатюры, что делает результат бесполезным. ( IE21F2 , B/185938070 ) - Добавлен новый API
Activity#setPipAnimationHintView
, чтобы обновить подсказку источника Pipparams, когда перемещается представление. ( I9063d )
Изменения API
- Функция
rememberLauncherForActivityResult
теперь возвращает пусковую установку, которая осуждает функциюunregister()
- регистрация и нерегистрирование пусковой установки автоматически обрабатываетсяrememberLauncherForActivityResult
. ( I2443e )
Составьте совместимость
-
androidx.activity:activity-compose:1.3.0-alpha08
совместим только с Compose Version1.0.0-beta07
и выше.
Версия 1.3.0-Alpha07
21 апреля 2021 года
androidx.activity:activity:1.3.0-alpha07
, androidx.activity:activity-compose:1.3.0-alpha07
и androidx.activity:activity-ktx:1.3.0-alpha07
. Версия 1.3.0-Alpha07 содержит эти коммиты.
Исправления ошибок
-
rememberLauncherForActivityResult
теперь возвращает стабильную ссылку на тот же экземплярActivityResultLauncher
, даже если контракт изменяется из -за переоборудования. ( Id2d6d ) - Использование нестабильных версий фрагментов выше
1.3.0
больше не будет бросить ложную положительную ошибку ворса, говорящая вам на1.3.0
. ( AOSP/1670206 , B/184847092 )
Версия 1.3.0-Alpha06
7 апреля 2021 года
androidx.activity:activity:1.3.0-alpha06
, androidx.activity:activity-compose:1.3.0-alpha06
и androidx.activity:activity-ktx:1.3.0-alpha06
. Версия 1.3.0-Alpha06 содержит эти коммиты.
Изменения API
- API
registerForActivityResult()
был переименован, чтобыrememberLauncherForActivityResult()
чтобы лучше указать, что возвращаемыйActivityResultLauncher
- это управляемый объект, который запоминается от вашего имени. Попытка назватьunregister
возвращаемойActivityResultLauncher
теперь вынесет ошибку. ( I2bb6d ) -
LocalOnBackPressedDispatcherOwner.current
иLocalActivityResultRegistryOwner.current
теперь возвращает нулевое значение, чтобы лучше определить, доступно ли оно в текущей композиции. API, которые требуют тех API, таких какBackHandler
иrememberLauncherForActivityResult()
, соответственно, теперь принесут более описательную ошибку, если базовый владелец не найден.NavHost
теперь работает, даже когдаOnBackPressedDispatcherOwner
не найден, в этом случае при предварительном просмотреNavHost
. ( I7d8b4 )
Исправления ошибок
-
BackHandler
теперь будет правильно перехватывать задними прессами в случаеSTOPPED
деятельности, затемSTARTED
снова, а другие обратные вызовы были добавлены с жизненным циклом. ( I71de6 , b/182284739 ) - Использование расширения метода
launch()
с помощью пользовательскогоActivityResultContract
, которое имеетUnit
ввода, больше не будет вызыватьNullPointerException
( I76282 , B/183837954 )
Версия 1.3.0-Alpha05
24 марта 2021 года
androidx.activity:activity:1.3.0-alpha05
, androidx.activity:activity-compose:1.3.0-alpha05
и androidx.activity:activity-ktx:1.3.0-alpha05
. Версия 1.3.0-Alpha05 содержит эти коммиты.
Исправления ошибок
- Из действия 1.2.2 : Исправлена проблема в
InvalidFragmentVersionForActivityResult
Lint Проверка, которая привела к ложноположительному положительному при использованию фрагмента 1.3.1 или выше. ( I54da1 , b/182388985 ) - Из деятельности 1.2.2 :
ComponentActivity
теперь позволяет избежатьClassNotFoundException
при запускеIntent
отActivityResultContract
, который ранее считался дополнительным в другомIntent
. ( IEFF05 , B/182906230 )
Обновления зависимости
- От деятельности 1.2.2 : активность теперь зависит от жизненного цикла
2.3.1
.
Версия 1.3.0-Alpha04
10 марта 2021 года
androidx.activity:activity:1.3.0-alpha04
, androidx.activity:activity-compose:1.3.0-alpha04
и androidx.activity:activity-ktx:1.3.0-alpha04
. Версия 1.3.0-Alpha04 содержит эти коммиты.
Исправления ошибок
- Из деятельности
1.2.1
:RequestMultiplePermissions
теперь всегда возвращает результаты для всех запрошенных разрешений вместо только разрешений, которые ранее не были предоставлены. ( I50bc3 , b/180884668 ) - Из деятельности
1.2.1
:ActivityResultRegistry
теперь гарантирует, что запросы в процессеlaunch()
будут возвращать свои результаты, даже если выunregister()
сноваregister()
с тем же ключом. ( I9ef34 , b/181267562 ) - Activity Compose больше не добавляет тестовых зависимостей к классовой дороге. ( IFD8B3 )
- Исправлена проблема с
BackHandler
, в которой ранееonBack
Lambda все еще использовалась после переоборудования. ( 8EB5EB )
Версия 1.3.0-Alpha03
24 февраля 2021 года
androidx.activity:activity:1.3.0-alpha03
, androidx.activity:activity-compose:1.3.0-alpha03
и androidx.activity:activity-ktx:1.3.0-alpha03
. Версия 1.3.0-Alpha03 содержит эти коммиты.
Новые возможности
- В настоящее время существует композиционная функция
registerForActivityResult
для получения результатов деятельности в рамках композибельных продуктов. ( IA7851 , B/172690553 )
Изменения API
-
LocalOnBackPressedDispatcherOwner
теперь имеетprovides
функции, которые можно использовать сCompositionLocalProvider
, заменив APIasProvidableCompositionLocal()
. ( I45d24 )
Версия 1.3.0-Alpha02
10 февраля 2021 года
androidx.activity:activity:1.3.0-alpha02
, androidx.activity:activity-compose:1.3.0-alpha02
и androidx.activity:activity-ktx:1.3.0-alpha02
высвобождаются. Версия 1.3.0-Alpha02 содержит эти коммиты.
Исправления ошибок
- Исправлена проблема в активности составьте
1.3.0-alpha01
, которая вызываетNoSuchMethodError: No static method setContent
Excontent при использовании Compose1.0.0-alpha12
. Все пользователи композиции должны зависеть от1.3.0-alpha02
и выше. ( B/179911234 )
Изменения API
- API
BackHandler
может использоваться для того, чтобы позволить композиции для перехвата системы обратной связи. ( I58ed5 , b/172154006 )
Версия 1.3.0-Alpha01
10 февраля 2021 года
androidx.activity:activity:1.3.0-alpha01
, androidx.activity:activity-compose:1.3.0-alpha01
и androidx.activity:activity-ktx:1.3.0-alpha01
. Версия 1.3.0-Alpha01 содержит эти коммиты.
Новые возможности
- Новый артефакт
activity-compose
обеспечивает JetPack сочинять конкретных помощников для API-интерфейсовandroidx.activity
.-
ComponentActivity.setContent
перешел отandroidx.compose.ui.platform.setContent
вandroidx.activity.compose.setContent
. ( ICF416 )
-
Известные проблемы
- Использование Activity Compose
1.3.0-alpha01
и библиотеки, которые зависят от этого, таких какandroidx.compose.ui:ui-test-junit4:1.0.0-alpha12
, приведет к исключениюNoSuchMethodError: No static method setContent
. ( B/179911234 )
Версия 1.2.4
Версия 1.2.4
21 июля 2021 года
androidx.activity:activity:1.2.4
и androidx.activity:activity-ktx:1.2.4
выпускаются. Версия 1.2.4 содержит эти коммиты.
Исправления ошибок
- Из деятельности
1.3.0-rc02
: обратные вызовы ActivityResultregistry теперь должным образом сохраняются и восстанавливаются, поэтому обратные вызовы не дублируются в сохранении. ( I97816 , B/191893160 )
Версия 1.2.3
Версия 1.2.3
5 мая 2021 года
androidx.activity:activity:1.2.3
и androidx.activity:activity-ktx:1.2.3
выпускаются. Версия 1.2.3 содержит эти коммиты.
Исправления ошибок
- Использование расширения метода
launch()
с помощью пользовательскогоActivityResultContract
, которое имеетUnit
ввода, больше не будет вызыватьNullPointerException
( I76282 , B/183837954 ) - Исправлена ложная ошибка положительного ворса, в котором говорилось, что вы используете фрагмент
1.3.0
при использовании моментального снимка, альфа, бета -версии или RC строительства более новой версии фрагментов. ( F4A57E , B/184847092 )
Версия 1.2.2
Версия 1.2.2
24 марта 2021 года
androidx.activity:activity:1.2.2
и androidx.activity:activity-ktx:1.2.2
выпускаются. Версия 1.2.2 содержит эти коммиты.
Исправления ошибок
- Исправлена проблема в
InvalidFragmentVersionForActivityResult
Lint Проверка, которая привела к ложному положительному при использованию фрагмента 1.3.1 или выше. ( I54da1 , b/182388985 ) -
ComponentActivity
теперь избегаетClassNotFoundException
при запускеIntent
отActivityResultContract
, который ранее считался дополнительным в другомIntent
. ( IEFF05 , B/182906230 )
Обновления зависимости
- Активность теперь зависит от жизненного цикла
2.3.1
.
Версия 1.2.1
Версия 1.2.1
10 марта 2021 года
androidx.activity:activity:1.2.1
и androidx.activity:activity-ktx:1.2.1
выпускаются. Версия 1.2.1 содержит эти коммиты.
Исправления ошибок
-
RequestMultiplePermissions
теперь всегда возвращает результаты для всех запрошенных разрешений, а не только разрешения, которые ранее не были предоставлены. ( I50bc3 , b/180884668 ) -
ActivityResultRegistry
теперь гарантирует, что в процессеlaunch()
запросы запуска () будут возвращать свои результаты, даже если выunregister()
, то сноваregister()
с тем же ключом. ( I9ef34 , b/181267562 )
Версия 1.2.0
Версия 1.2.0
10 февраля 2021 года
androidx.activity:activity:1.2.0
и androidx.activity:activity-ktx:1.2.0
выпускаются. Версия 1.2.0 содержит эти коммиты.
Основные изменения с 1.1.0
- API -интерфейс результатов деятельности :
ComponentActivity
в настоящее время обеспечиваетActivityResultRegistry
, которая позволяет вам обрабатыватьstartActivityForResult()
+onActivityResult()
, а такжеrequestPermissions()
+onRequestPermissionsResult()
потоки без переоценки в вашей деятельности или фрагментах, повышает безопасность типа с помощьюActivityResultContract
и обеспечивает крючки для тестирования. Смотрите обновленную получение результата от деятельности .
ContextAware
:ComponentActivity
теперь реализуетContextAware
, позволяя вам добавить один или несколько экземпляровOnContextAvailableListener
, которые получат обратный вызов перед базовойActivity.onCreate()
.- Приостановление расширения Kotlin
withContextAvailable()
позволяет запустить блок, не связанный с SUSPENDING, когда контекст становится доступным, и вернуть результат. - Этот API используется
FragmentActivity
в фрагменте 1.3.0 для восстановления состоянияFragmentManager
. Любые слушатели, добавленные к подклассамFragmentActivity
будут работать после этого слушателя. - Этот API используется
AppCompatActivity
в AppCompat 1.3.0-Alpha02 или выше. Любые слушатели, добавленные к подклассамAppCompatActivity
будут работать после этого слушателя.
- Приостановление расширения Kotlin
Поддержка
ViewTree
:ComponentActivity
теперь поддерживаетViewTreeLifecycleOwner.get(View)
LifecycleOwner
1.1.0
ViewTreeViewModelStoreOwner.get(View)
ViewModelStoreOwner
ViewTreeSavedStateRegistryOwner
2.3.0
SavedStateRegistryOwner
для любых представлений, непосредственно добавленных кComponentActivity
.
- Отчетный отчетмон () Backport - Метод
Activity
reportFullyDrawn()
был возвращен вComponentActivity
чтобы работать на всех уровнях API, исправляя сбой на API 19 и добавляя трассировку для этого метода для всех уровней API.
Версия 1.2.0-RC01
16 декабря 2020 года
androidx.activity:activity:1.2.0-rc01
и androidx.activity:activity-ktx:1.2.0-rc01
выпускаются. Версия 1.2.0-RC01 содержит эти коммиты.
Исправления ошибок
-
ActivityResultRegistry
теперь всегда восстанавливает точное состояние, которое было сохранено. ( Idd56b ) - Добавить трассировку в
ComponentActivity.reportFullyDrawn
.
Внешний вклад
-
ComponentActivity
теперь переопределяетreportFullyDrawn()
, позволяя его вызвать на все уровни API и исправлять сбой при вызове этого метода без соответствующего разрешения системы на устройствах API 19. Спасибо Саймон Шиллер! ( B/163239764 , #103 )
Версия 1.2.0-бета02
2 декабря 2020 года
androidx.activity:activity:1.2.0-beta02
и androidx.activity:activity-ktx:1.2.0-beta02
выпускаются. Версия 1.2.0-бета02 содержит эти коммиты.
Исправления ошибок
- Исправлена проблема, в которой API результата активности не будет ждать
STARTED
жизненного цикла до получения результатов при регистрации вLifecycle
. ( I109ea )
Внешний вклад
- Обновлено документацию для
launch()
, чтобы явно назвать, что она может броситьActivityNotFoundException
. Спасибо, Михал, Зелиньски! ( AOSP/1493580 )
Версия 1.2.0-бета01
1 октября 2020 года
androidx.activity:activity:1.2.0-beta01
и androidx.activity:activity-ktx:1.2.0-beta01
выпускаются. Версия 1.2.0-бета01 содержит эти коммиты.
Исправления ошибок
ActivityResultRegistry
теперь случайным образом генерирует целые числа, пока не найдет тот, который не раскрывается для использования в качествеregister()
, что предотвращает возможное переполнение целого числа, вызванное увеличением кодов запросов. ( B/168779518 )Наблюдатели
Lifecycle
должным образом удаляются при вызовеunregister()
наActivityResultLauncher
. ( B/165608393 )
Поведение изменяется
-
ActivityResultRegistry
теперь бросаетIllegalStateException
, когда попытка позвонить вregister()
сLifecycleOwner
, чейLifecycle
уже достигSTARTED
. ( B/165435866 )
Документация обновлена
-
ContextAware
документация ссылается наLifecycleOwner
, чтобы выделить обратные вызовыLifecycle
в качестве подходящего места для событий создания и разрушения. ( AOSP/1414152 )
Версия 1.2.0-Alpha08
19 августа 2020 года
androidx.activity:activity:1.2.0-alpha08
и androidx.activity:activity-ktx:1.2.0-alpha08
выпускаются. Версия 1.2.0-Alpha08 содержит эти коммиты.
Новые возможности
-
ComponentActivity
теперь реализуетContextAware
, позволяя добавлять один или несколько экземпляровOnContextAvailableListener
, которые получат обратный вызов перед базовойActivity.onCreate()
. ( B/161390636 )- Приостановление расширения Kotlin
withContextAvailable()
позволяет запустить блок, не связанный с SUSPENDING, когда контекст становится доступным, и вернуть результат. ( I8290c ) - Этот API используется
FragmentActivity
в фрагменте 1.3.0-Alpha08 для восстановления состоянияFragmentManager
. Любые слушатели, добавленные к подклассамFragmentActivity
будут работать после этого слушателя. ( I513da ) - Этот API используется
AppCompatActivity
в AppCompat 1.3.0-Alpha02 . Любые слушатели, добавленные к подклассамAppCompatActivity
будут работать после этого слушателя. ( I513da )
- Приостановление расширения Kotlin
Исправления ошибок
- Исправлена проблема с проверкой LINT
ActivityResultFragmentVersionDetector
, которая заставила его сломаться при использовании Lint 27.1.0 или выше. ( B/162155191 )
Версия 1.2.0-Alpha07
22 июля 2020 года
androidx.activity:activity:1.2.0-alpha07
и androidx.activity:activity-ktx:1.2.0-alpha07
выпускаются. Версия 1.2.0-Alpha07 содержит эти коммиты.
Новые возможности
- Добавлена новая
InvalidFragmentVersionForActivityResult
Lint Проверка, которая проверяет, что вы используете фрагмент1.3.0-alpha07
при использовании API результата активности , избегая сбоев времени выполнения из-за проблем «неверного запроса» и запросов на разрешение на разрешение на не функционирование, вызванные использованием более старых версий фрагментов. ( B/152554847 )
Внешний вклад
- Исправлено
ArrayIndexOutOfBoundsException
при анализе результатов для договора результатов деятельностиRequestPermission
. ( I8f9e3 , b/161057605 )
Версия 1.2.0-Alpha06
10 июня 2020 года
androidx.activity:activity:1.2.0-alpha06
и androidx.activity:activity-ktx:1.2.0-alpha06
выпускаются. Версия 1.2.0-Alpha06 содержит эти коммиты.
Новые возможности
- Теперь вы можете уничтожить класс
ActivityResult
в Котлине, чтобы напрямую получить доступ к кодуrequestCode
иintent
. ( B/157212935 ) -
ActivityResultLauncher
теперь позволяет вам получитьActivityResultContract
, который использовался для регистрации пусковой установки. ( B/156875743 )
Изменения API
- Перерывные изменения : метод
invoke()
наActivityResultRegistry
был переименован вonLaunch()
. ( B/157496491 ) - Контракт
OpenMultipleDocuments
теперь возвращает пустой список вместоnull
в зарегистрированный обратный вызов, если результат не возвращается. ( B/157348014 )
Версия 1.2.0-Alpha05
20 мая 2020 года
androidx.activity:activity:1.2.0-alpha05
и androidx.activity:activity-ktx:1.2.0-alpha05
выпускаются. Версия 1.2.0-Alpha05 содержит эти коммиты.
Новые возможности
- Добавлена поддержка
ViewTreeViewModelStoreOwner
из LifeCycle2.3.0-alpha03
иViewTreeSavedStateRegistryOwner
из SavedState1.1.0-alpha01
при использованииView
в рамкахComponentActivity
. ( AOSP/1297993 , AOSP/1300264 )
Изменения API
- The
TakePicture
contract now returns aboolean
indicating success rather than a thumbnailBitmap
as this was very rarely supported by camera apps when writing the image to the providedUri
. ( b/154302879 ) - The
invoke()
extensions onActivityResultLauncher
have been removed in favor of explicitly usinglaunch()
to better indicate that these are asynchronous operations. Kotlin extensions forlaunch
have been added to theandroidx.activity.result
package forActivityResultLauncher<Void>
andActivityResultLauncher<Unit>
that remove the need to pass innull
orUnit
, respectively, mirroring that behavior from the previouslyinvoke()
extensions. ( aosp/1304674 , aosp/1304675 ) - The
IntentSenderRequest.Builder
methods forsetFlagsMask()
andsetFlagsValues()
has been combined into a singlesetFlags()
method. ( aosp/1302111 )
Исправления ошибок
- When registering an
ActivityResultCallback
with aLifecycleOwner
, fixed an issue where the callback would be triggered before the state reachesSTARTED
. ( aosp/1309744 )
Behavior Changes
- The
ActivityResultRegistry
now generates request codes starting at0xFFFF
rather than at0
, preventing overlap when usingstartActivityForResult()
orrequestPermissions()
in an activity. ( aosp/1302324 )
Версия 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. Версия 1.2.0-Alpha04 содержит эти коммиты.
Новые возможности
- Added a contract that can call startIntentSenderForResult to the ActivityResult APIs. ( b/153007517 )
Изменения API
- The
prepareCall()
method has been renamed toregisterForActivityResult()
, both onComponentActivity
here and in Fragment1.3.0-alpha04
. ( aosp/1278717 ) - The
GetContents
,OpenDocuments
, andRequestPermissions
contracts have been renamed toGetMultipleContents
,OpenMultipleDocuments
, andRequestMultiplePermissions
, respectively. ( aosp/1280161 ) -
ComponentActivity
now implements theActivityResultRegisteryOwner
interface. ( aosp/1290888 ) - - The
startActivityForResult()
/onActivityResult()
andonRequestPermissionsResult()
APIs onComponentActivity
have been deprecated. Please use the Activity Result APIs . ( b/154751887 )
Исправления ошибок
- When using the
GetMultipleContents
andOpenMultipleDocuments
contracts and selecting a single item, it is now correctly returned to your callback. ( b/152941153 )
Версия 1.2.0-Alpha03
April 1, 2020
androidx.activity:activity:1.2.0-alpha03
and androidx.activity:activity-ktx:1.2.0-alpha03
are released. Версия 1.2.0-Alpha03 содержит эти коммиты.
Новые возможности
- Added the
TakeVideo
,PickContact
,GetContent
,GetContents
,OpenDocument
,OpenDocuments
,OpenDocumentTree
, andCreateDocument
contracts 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
- The
TakePicture
contract now takes aUri
input 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 onActivityResultRegistry
has been renamed toregister()
. ( aosp/1267621 ) - The
dispose()
method onActivityResultLauncher
has been renamed tounregister()
and theunregisterResultCallback()
onActivityResultRegistry
has been removed. ( aosp/1267621 ) - The
createIntent()
method ofActivityResultContact
now takes aContext
in addition to the input to make it possible to create explicit Intents. ( aosp/1238800 ) - An
ActivityResultContract
can now overridegetSynchronousResult()
to deliver a result without callingstartActivityForResult
. This is used by theRequestPermission
andRequestPermissions
contracts to correctly deliver a 'granted' status if the requested permissions are already granted. ( b/151110799 ) - The previously available
Dial
contract has been removed as thatIntent
is 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 ofActivityResultRegistry
exceptinvoke()
, and a number of the default contracts that do not support optional extras. ( b/152439361 )
Исправления ошибок
- Fixed a
NullPointerException
inActivityResultRegistry
when attempting to deliver results to a callback that has not yet been re-registered after a configuration change;ActivityResultRegistry
now holds onto these pending results and delivers them when the callback is re-registered. ( b/152137004 )
Версия 1.2.0-Alpha02
March 18, 2020
androidx.activity:activity:1.2.0-alpha02
and androidx.activity:activity-ktx:1.2.0-alpha02
are released. Версия 1.2.0-Alpha02 содержит эти коммиты.
Новые возможности
- ActivityResultRegistry :
ComponentActivity
now provides anActivityResultRegistry
that 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 )
Версия 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. Версия 1.2.0-Alpha01 содержит эти коммиты.
Новые возможности
- Added support for the
ViewTreeLifecycleOwner.get(View)
API added in Lifecycle2.3.0-alpha01
such that it will return the Activity as theLifecycleOwner
for any Views directly added to the Activity. ( aosp/1182955 )
Исправления ошибок
- Fixed a regression introduced in Activity
1.1.0
when running on older versions of the platform whereonBackPressed()
would cause anIllegalStateException
due to a bug in theandroid.app.FragmentManager
. ( b/146290338 )
Версия 1.1.0
Версия 1.1.0
January 22, 2020
androidx.activity:activity:1.1.0
is released. Версия 1.1.0 содержит эти коммиты .
Важные изменения с версии 1.0.0
- Lifecycle ViewModel SavedState Integration :
SavedStateViewModelFactory
is now the default factory used when usingby viewModels()
, theViewModelProvider
constructor, orViewModelProviders.of()
with aComponentActivity
or its subclasses.
Версия 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-rc03
and 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
.
Версия 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
. Версия 1.1.0-rc01 содержит эти коммиты .
Версия 1.1.0-бета01
October 9, 2019
androidx.activity:activity:1.1.0-beta01
and androidx.activity:activity-ktx:1.1.0-beta01
are released. Версия 1.1.0-beta01 содержит эти коммиты .
Dependency changes
- Activity now depends on SavedState 1.0.0 stable.
Версия 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 .
New features
- Activity now depends on Core 1.1.0 stable.
Исправления ошибок
- Activity now depends on Lifecycle
2.2.0-alpha04
.
Версия 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 .
New features
-
SavedStateViewModelFactory
is now the default factory used when usingby viewModels()
, theViewModelProvider
constructor, orViewModelProviders.of()
with aComponentActivity
( b/135716331 )
Версия 1.1.0-альфа01
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 .
New features
-
activity
now depends on Lifecycle2.2.0-alpha02
. ( aosp/1007817 ) -
activity-ktx
added a dependency onlifecycle-runtime-ktx
; you no longer need to explicitly add it to your dependencies when usingactivity-ktx
or libraries that depend onactivity-ktx
(such asfragment-ktx
). ( aosp/987162 )
Версия 1.0.0
Версия 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 :
ComponentActivity
serves as the new base class forFragmentActivity
in Fragment1.1.0
and, by extension,AppCompatActivity
in AppCompat1.1.0
. - activity-ktx : The
activity-ktx
module includes aby viewModels
Kotlin property extension for accessing ViewModels. This module is automatically included when you includefragment-ktx
from Fragment1.1.0
. - OnBackPressedDispatcher : As a composable alternative to overriding
onBackPressed()
, you can now register aOnBackPressedCallback
from anyLifecycleOwner
(such as a fragment) to intercept system back button events. A lambda with receiver versionaddCallback
has 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 anyViewModelStoreOwner
that makes the ownership of the retained objects clear and provides anonCleared()
callback for cleaning up resources when the activity is finally destroyed.
Версия 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 .
Версия 1.0.0-бета01
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
addOnBackPressedCallback
andremoveOnBackPressedCallback
methods onComponentActivity
have been removed. aosp/953857 - The
setEnabled()
andisEnabled()
methods ofOnBackPressedCallback
are now final. b/131416833 - The
remove()
method ofOnBackPressedCallback
is now final. aosp/952720 -
OnBackPressedDispatcher
now has public constructors, allowing you to construct your own instances for testing, etc. aosp/953431 -
onBackPressed()
forComponentActivity
is now explicitly marked as@MainThread
aosp/952721
Исправления ошибок
- Fixed a
ConcurrentModificationException
when callingremove()
from within thehandleOnBackPressed()
method of aOnBackPressedCalback
that 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
OnBackPressedCallback
andOnBackPressedDispatcher
have been marked as@MainThread
. ( aosp/943813 ) - The
handleOnBackPressed()
method no longer returns aboolean
. Instead,OnBackPressedCallback
is 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
addCallback
methods ofOnBackPressedDispatcher
no longer return aCancellable
instance.OnBackPressedCallback
now contain aremove()
method that fulfill this functionality, allowing you to callremove()
duringhandleOnBackPressed()
. ( aosp/944519 ) ( aosp/946316 ) -
activity-ktx
now contains a receiver scoped callback foraddCallback
that accepts a lamdba that implementshandleOnBackPressed()
and has access toisEnabled
andremove()
( 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
OnBackPressedCallback
related APIs on ComponentActivity have been deprecated in favor of the newOnBackPressedDispatcher
, retrievable viagetOnBackPressedDispatcher()
. ( aosp/922523 ) - Methods to add a new
OnBackPressedCallback
to theOnBackPressedDispatcher
now return aCancellable
object, allowing removal of the callback without requiring an explicit reference to theOnBackPressedDispatcher
. ( aosp/922523 ) - Adding a
OnBackPressedCallback
with an associatedLifecycleOwner
now results in adding and removing theOnBackPressedCallback
as the Lifecycle is started and stopped, respectively. ( aosp/922523 )
Версия 1.0.0-альфа05
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 .
New features
-
@ContentView
annotation lookups are now cached ( b/123709449 )
Версия 1.0.0-альфа04
January 30, 2019
androidx.activity:activity 1.0.0-alpha04
and androidx.activity:activity-ktx 1.0.0-alpha04
are released.
New features
- Added support for the
@ContentView
class 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
activity
module now depends on version 2.1.0-alpha02 of ViewModel to match theactivity-ktx
module's dependency.
Version 1.0.0-alpha03
December 17, 2018
androidx.activity 1.0.0-alpha03
is released.
New features
- ComponentActivity now implements
BundleSavedStateRegistryOwner
and depends on the newly released SavedState library [ aosp/815133 ] - ComponentActivity now works around an Android framework bug that would cause InputMethodManager to leak the last focused view [ b/37122102 ]
Версия 1.0.0-альфа02
December 3, 2018
API changes
- Added a note that
getLifecycle()
should not be overridden and will be madefinal
in a future release. Please file a feature request if you are currently overriding this method. ( aosp/815834 )
Версия 1.0.0-альфа01
November 5, 2018
androidx.activity 1.0.0-alpha01
introduces ComponentActivity
, a new base class of the existing FragmentActivity
and AppCompatActivity
.
New features
- You can now register an
OnBackPressedCallback
viaaddOnBackPressedCallback
to receiveonBackPressed()
callbacks without needing to override the method in your activity. - Added a new
by viewModels()
Kotlin property delegate for retrievingViewModel
s from aComponentActivity
. - Pending input events (such as clicks) are now canceled in
onStop()
.
API changes
- The implementation of
LifecycleOwner
andViewModelStoreOwner
have been moved fromFragmentActivity
toComponentActivity
. -
onRetainCustomNonConfigurationInstance
has been deprecated. Use aViewModel
for storing objects that need to survive configuration changes.
Активность
Последнее обновление | Стабильный выпуск | Кандидат на выпуск | Бета-версия | Альфа-релиз |
---|---|---|---|---|
9 апреля 2025 г. | 1.10.1 | - | 1.11.0-beta01 | - |
Объявление зависимостей
To add a dependency on Activity, you must add the Google Maven repository to your project. Для получения дополнительной информации прочтите репозиторий Google Maven .
Добавьте зависимости для нужных вам артефактов в файл build.gradle
для вашего приложения или модуля:
классный
dependencies { def activity_version = "1.10.1" // Java language implementation implementation "androidx.activity:activity:$activity_version" // Kotlin implementation "androidx.activity:activity-ktx:$activity_version" }
Котлин
dependencies { val activity_version = "1.10.1" // Java language implementation implementation("androidx.activity:activity:$activity_version") // Kotlin implementation("androidx.activity:activity-ktx:$activity_version") }
Дополнительные сведения о зависимостях см. в разделе Добавление зависимостей сборки .
Обратная связь
Ваши отзывы помогают сделать Jetpack лучше. Дайте нам знать, если вы обнаружите новые проблемы или у вас есть идеи по улучшению этой библиотеки. Пожалуйста, ознакомьтесь с существующими проблемами в этой библиотеке, прежде чем создавать новую. Вы можете добавить свой голос к существующей проблеме, нажав кнопку со звездочкой.
Дополнительную информацию см. в документации по системе отслеживания проблем .
Version 1.11
Version 1.11.0-beta01
9 апреля 2025 г.
androidx.activity:activity:1.11.0-beta01
, androidx.activity:activity-compose:1.11.0-beta01
, and androidx.activity:activity-ktx:1.11.0-beta01
are released. Version 1.11.0-beta01 contains these commits .
Version 1.11.0-alpha02
26 марта 2025 г.
androidx.activity:activity:1.11.0-alpha02
, androidx.activity:activity-compose:1.11.0-alpha02
, and androidx.activity:activity-ktx:1.11.0-alpha02
are released. Version 1.11.0-alpha02 contains these commits .
Изменения API
- Integrated the new
EDGE_NONE
andframeTimeMillis
from Android 16 Beta03 into theBackEventCompat
provided byOnBackPressedCallback
'shandleOnBackStarted
andhandleOnBackProgressed
functions.
Обновления зависимости
- Activity is now compiled with API 36. ( I510e8 , b/301910674 )
Version 1.11.0-alpha01
12 марта 2025 г.
androidx.activity:activity:1.11.0-alpha01
, androidx.activity:activity-compose:1.11.0-alpha01
, and androidx.activity:activity-ktx:1.11.0-alpha01
are released. Version 1.11.0-alpha01 contains these commits .
Новые возможности
- Added
MediaCapabilities
API toPickVisualMediaRequest
to let applications specify its media capabilities, such as supported HDR Types. ( Ic3ee7 )
Version 1.10
Version 1.10.1
26 февраля 2025 г.
androidx.activity:activity:1.10.1
, androidx.activity:activity-compose:1.10.1
, and androidx.activity:activity-ktx:1.10.1
are released. Version 1.10.1 contains these commits .
Исправления ошибок
-
ViewTree
OnBackPressedDispatcherOwners
andFullyDrawnReporterOwners
can now be resolved through disjoint parents of a view, such as aViewOverlay
. See the release notes of core or the documentation inViewTree.setViewTreeDisjointParent
for more information on disjoint view parents. ( Ie7750 )
Version 1.10.0
15 января 2025 г.
androidx.activity:activity:1.10.0
, androidx.activity:activity-compose:1.10.0
, and androidx.activity:activity-ktx:1.10.0
are released. Version 1.10.0 contains these commits .
Important changes since 1.9.0
-
PhotoPicker
now allows picking images in order and choosing which tab (either albums or images) should be initially visible. - The
PickVisualMedia
andPickMultipleVisualMedia
Activity Result contracts that trigger the Photo Picker no longer directly delegates to Google Play services if the system Photo picker is not available, but uses the publicACTION_SYSTEM_FALLBACK_PICK_IMAGES
action and related extras to provide a consistent Photo Picker experience to OEMs and system apps as a fallback. - New
LocalActivity
composition local that provides theActivity
for the current scope, removing the need for developers to get anActivity
from theLocalContext
.
Version 1.10.0-rc01
11 декабря 2024 г.
androidx.activity:activity:1.10.0-rc01
, androidx.activity:activity-compose:1.10.0-rc01
, and androidx.activity:activity-ktx:1.10.0-rc01
are released. Version 1.10.0-rc01 contains these commits .
Исправления ошибок
- Fixed an issue where changing the enabled state while the
PredictiveBackHandler
is currently active would short circuit the callback immediately. It will now finish the current callback regardless of the enabled status changes. ( Ib8719 )
Version 1.10.0-beta01
13 ноября 2024 г.
androidx.activity:activity:1.10.0-beta01
, androidx.activity:activity-compose:1.10.0-beta01
, and androidx.activity:activity-ktx:1.10.0-beta01
are released with no changes since the last alpha. Version 1.10.0-beta01 contains these commits .
Version 1.10.0-alpha03
30 октября 2024 г.
androidx.activity:activity:1.10.0-alpha03
, androidx.activity:activity-compose:1.10.0-alpha03
, and androidx.activity:activity-ktx:1.10.0-alpha03
are released. Version 1.10.0-alpha03 contains these commits .
Изменения API
- Added a new
LocalActivity
composition local that provides theActivity
for the current scope, removing the need for developers to get anActivity
from theLocalContext
. It also comes with a new lint rule that checks when theLocalContext
is incorrectly being cast to anActivity
. ( I7746a , b/283009666 )
Исправления ошибок
- From Activity
1.9.3
:PredictiveBackHandler
will no longer fire it's callback after the handler has been disabled. This will fix an issue where theNavHost
from Navigation Compose would throw anIndexOutOfBoundsException
. ( I3f75e , b/365027664 , b/340202286 )
Dependency Update
- Activity Compose now depends on Compose Runtime 1.7.0 ( I7746a , b/283009666 )
Version 1.10.0-alpha02
4 сентября 2024 г.
androidx.activity:activity:1.10.0-alpha02
, androidx.activity:activity-compose:1.10.0-alpha02
, and androidx.activity:activity-ktx:1.10.0-alpha02
are released. Version 1.10.0-alpha02 contains these commits .
Behavior Changes
- The
PickVisualMedia
andPickMultipleVisualMedia
Activity Result contracts that trigger the Photo Picker no longer directly delegates to Google Play services if the system Photo picker is not available, but uses the publicACTION_SYSTEM_FALLBACK_PICK_IMAGES
action and related extras to provide a consistent Photo Picker experience to OEMs and system apps as a fallback. This should have no effect on the user experience for devices that have a recent version of Google Play services. ( I3513d )
Исправления ошибок
- Removed manual outlining of access to new platform APIs since this happens automatically via API modeling when using R8 with AGP 7.3 or later (eg R8 version 3.3) and for all builds when using AGP 8.1 or later (eg D8 version 8.1). Clients who are not using AGP are advised to update to D8 version 8.1 or later. See this article for more details. ( I9496c , b/345472586 )
- From Activity
1.9.2
: Fixed an issue where the Activity ComposePredictiveBackHandler
API would continue to handle the system back gesture on the frame it was disabled, which could result in libraries like Navigation Compose to handle back even with an empty back stack, resulting in it throwing anIndexOutOfBoundsException
. ( Ie3301 , b/340202286 ) - From Activity
1.9.1
: Fixed an issue withPredictiveBackHandler
where after doing system back, attempting to doonBackPressed
from theOnBackPressedDispatcher
would fail. ( I5f1f8 )
Version 1.10.0-alpha01
26 июня 2024 г.
androidx.activity:activity:1.10.0-alpha01
, androidx.activity:activity-compose:1.10.0-alpha01
, and androidx.activity:activity-ktx:1.10.0-alpha01
are released. This version is developed in an internal branch.
Новые возможности
- Added support for new
PhotoPicker
features introduced in Android V including being able to pick images in order and choose which tab (either albums or images) should be initially visible.
Version 1.9
Version 1.9.3
16 октября 2024 г.
androidx.activity:activity:1.9.3
, androidx.activity:activity-compose:1.9.3
, and androidx.activity:activity-ktx:1.9.3
are released. Version 1.9.3 contains these commits .
Исправления ошибок
-
PredictiveBackHandler
will no longer fire it's callback after the handler has been disabled. This will fix an issue where theNavHost
from Navigation Compose would throw anIndexOutOfBoundsException
. ( I3f75e , b/340202286 )
Version 1.9.2
4 сентября 2024 г.
androidx.activity:activity:1.9.2
, androidx.activity:activity-compose:1.9.2
, and androidx.activity:activity-ktx:1.9.2
are released. Version 1.9.2 contains these lthcocommits .
Исправления ошибок
- Fixed an issue where the Activity Compose
PredictiveBackHandler
API would continue to handle the system back gesture on the frame it was disabled, which could result in libraries like Navigation Compose to handle back even with an empty back stack, resulting in it throwing anIndexOutOfBoundsException
. ( Ie3301 , b/340202286 )
Version 1.9.1
24 июля 2024 г.
androidx.activity:activity:1.9.1
, androidx.activity:activity-compose:1.9.1
, and androidx.activity:activity-ktx:1.9.1
are released. Version 1.9.1 contains these commits .
Исправления ошибок
- Fixed an issue with
PredictiveBackHandler
where after doing system back, attempting to doonBackPressed
from theOnBackPressedDispatcher
would fail. ( I5f1f8 )
Version 1.9.0
17 апреля 2024 г.
androidx.activity:activity:1.9.0
, androidx.activity:activity-compose:1.9.0
, and androidx.activity:activity-ktx:1.9.0
are released. Version 1.9.0 contains these commits .
Important changes since 1.8.0
-
ComponentActivity
now implementsOnUserLeaveHintProvider
to allow components to callbacks foronUserLeaveHint
events. - The
OnBackPressedCallback
,BackHandler
, andPredictiveBackHandler
APIs now warn when callingonBackPressedDispatcher.onBackPressed()
when handling back as that will always break the Predictive Back Animation . See the best practices guide for more details. - The remainder of the Activity APIs have been rewritten in Kotlin and all extensions previously available in
activity-ktx
have been moved toactivity
.activity-ktx
is now completely empty.- As part of the conversion of
ActivityResultLauncher
to Kotlin, thegetContract
method is now an abstract Kotlin property. This is a binary compatible change, but source breaking if your implementation ofActivityResultLauncher
is written in Kotlin.
- As part of the conversion of
Version 1.9.0-rc01
3 апреля 2024 г.
androidx.activity:activity:1.9.0-rc01
, androidx.activity:activity-compose:1.9.0-rc01
, and androidx.activity:activity-ktx:1.9.0-rc01
are released. Version 1.9.0-rc01 contains these commits .
Dependency update
- Activity now depends on Profile Installer 1.3.1 .
Version 1.9.0-beta01
20 марта 2024 г.
androidx.activity:activity:1.9.0-beta01
, androidx.activity:activity-compose:1.9.0-beta01
, and androidx.activity:activity-ktx:1.9.0-beta01
are released. Version 1.9.0-beta01 contains these commits .
Исправления ошибок
- Fixed an Activity startup performance regression introduced in Activity
1.9.0-alpha02
caused by calling theOnBackPressedDispatcher
as part of the creation of the Activity. ( Ie75e3 )
Version 1.9.0-alpha03
7 февраля 2024 г.
androidx.activity:activity:1.9.0-alpha03
, androidx.activity:activity-compose:1.9.0-alpha03
, and androidx.activity:activity-ktx:1.9.0-alpha03
are released. Version 1.9.0-alpha03 contains these commits.
Lint Warning
- The
OnBackPressedCallback
,BackHandler
, andPredictiveBackHandler
APIs now warn when callingonBackPressedDispatcher.onBackPressed()
when handling back as that will always break the Predictive Back Animation . See the best practices guide for more details. ( 1e4222 , 2c950d , b/287505200 )
Исправления ошибок
- If a back event is sent from the system started during an already running Predictive Back Gesture, the currently running Predictive Back Gesture is canceled and the new back event takes over to begin a new Predictive Back Gesture. ( I3482e )
- Fixed a crash when accessing the
onBackPressedDispatcher
from aComponentActivity
for the first time from a background thread. It is now safe to access theonBackPressedDispatcher
on any thread. ( I79955 )
Version 1.9.0-alpha02
24 января 2024 г.
androidx.activity:activity:1.9.0-alpha02
, androidx.activity:activity-compose:1.9.0-alpha02
, and androidx.activity:activity-ktx:1.9.0-alpha02
are released. Version 1.9.0-alpha02 contains these commits.
Kotlin Conversions
-
ActivityResultRegistry
has been rewritten in Kotlin. This ensures that the nullability of the generics on the contract passed toregister
will correctly be passed through to theActivityResultLauncher
returned to you. ( I121f0 ) -
ActivityResult
has been rewritten in Kotlin. TheActivityResult
Kotlin extensions that support destructuring into theresultCode
anddata
fields have been moved fromactivity-ktx
toactivity
. ( I0565a ) - The Kotlin extensions of
by viewModels()
forComponentActivity
andtrackPipAnimationHintView
have been moved fromactivity-ktx
toactivity
. Theactivity-ktx
artifact is now completely empty. ( I0a444 )
Исправления ошибок
- The
enableEdgeToEdge
API now draws around any display cutouts. ( a3644b , b/311173461 ) - From Activity
1.8.2
: Fixed the extra passed to the Photo Picker Activity Contract'sACTION_SYSTEM_FALLBACK_PICK_IMAGES
to correctly pass it theEXTRA_SYSTEM_FALLBACK_PICK_IMAGES_MAX
key, rather than using the extra with the key"com.google.android.gms.provider.extra.PICK_IMAGES_MAX"
. It is strongly recommended if you are an OEM who implements a system fallback Photo Picker to support both extras to ensure the widest compatibility. ( I96a00 )
Version 1.9.0-alpha01
29 ноября 2023 г.
androidx.activity:activity:1.9.0-alpha01
, androidx.activity:activity-compose:1.9.0-alpha01
, and androidx.activity:activity-ktx:1.9.0-alpha01
are released. Version 1.9.0-alpha01 contains these commits.
Новые возможности
-
ComponentActivity
now implementsOnUserLeaveHintProvider
to allow components to callbacks foronUserLeaveHint
events. ( I54892 )
Изменения API
-
ComponentActivity
has been rewritten in Kotlin. ( I14f31 ) -
ActivityResultCaller
has been rewritten in Kotlin. ( Ib02e4 ) -
ActivityResultLauncher
has been rewritten in Kotlin. As part of that conversion, thegetContract
method is now an abstract Kotlin property. This is a binary compatible change, but source breaking if your implementation ofActivityResultLauncher
is written in Kotlin. ( Id4615 ) -
PickVisualMediaRequest
now has the same minimum API level of 19 as thePickVisualMedia
Activity Result contract. ( Id6e21 )
Dependency Update
- Activity now depends on Core
1.13.0-alpha01
. ( I14f31 )
Версия 1.8
Version 1.8.2
13 декабря 2023 г.
androidx.activity:activity:1.8.2
, androidx.activity:activity-compose:1.8.2
, and androidx.activity:activity-ktx:1.8.2
are released. Version 1.8.2 contains these commits.
Исправления ошибок
- Fixed the extra passed to the Photo Picker Activity Contract's
ACTION_SYSTEM_FALLBACK_PICK_IMAGES
to correctly pass it theEXTRA_SYSTEM_FALLBACK_PICK_IMAGES_MAX
key, rather than using the extra with the key"com.google.android.gms.provider.extra.PICK_IMAGES_MAX"
. It is strongly recommended if you are an OEM who implements a system fallback Photo Picker to support both extras to ensure the widest compatibility. ( I96a00 )
Version 1.8.1
15 ноября 2023 г.
androidx.activity:activity:1.8.1
, androidx.activity:activity-compose:1.8.1
, and androidx.activity:activity-ktx:1.8.1
are released. Version 1.8.1 contains these commits.
Исправления ошибок
-
OnBackPressedDispatcher
now continues to dispatch to the correctOnBackPressedCallback
even after a newOnBackPressedCallback
is added while the back gesture is being handled. ( Id0ff6 )
Version 1.8.0
4 октября 2023 г.
androidx.activity:activity:1.8.0
, androidx.activity:activity-compose:1.8.0
, and androidx.activity:activity-ktx:1.8.0
are released. Version 1.8.0 contains these commits.
Important changes since 1.7.0
- Predictive Back - The
OnBackPressedCallback
now offers new Predictive Back callbacks for handling the back gesture starting, progress throughout the gesture, and the back gesture being canceled in addition to the previoushandleOnBackPressed()
callback for when the back gesture is committed. This also comes with thePredictiveBackHandler
Composable to handle predictive back gesture events in Activity Compose. It provides a Flow of BackEventCompat objects that must be collected in the suspending lamba you provide:
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()
has now been deprecated in favor of the APIs for handling back. Developers should now utilize the OnBackPressedDispatcher
, rather than overriding this method.
- EdgeToEdge -
ComponentActivity.enableEdgeToEdge()
has been added to easily set up the edge-to-edge display in a backward-compatible manner.
Версия 1.8.0-rc01
20 сентября 2023 г.
androidx.activity:activity:1.8.0-rc01
, androidx.activity:activity-compose:1.8.0-rc01
, and androidx.activity:activity-ktx:1.8.0-rc01
are released. Version 1.8.0-rc01 contains these commits.
Версия 1.8.0-бета01
6 сентября 2023 г.
androidx.activity:activity:1.8.0-beta01
, androidx.activity:activity-compose:1.8.0-beta01
, and androidx.activity:activity-ktx:1.8.0-beta01
are released. Version 1.8.0-beta01 contains these commits.
Documentation Improvement
- Improved the documentation of
BackEventCompat
. ( aosp/2722254 )
Версия 1.8.0-альфа07
23 августа 2023 г.
androidx.activity:activity:1.8.0-alpha07
, androidx.activity:activity-compose:1.8.0-alpha07
, and androidx.activity:activity-ktx:1.8.0-alpha07
are released. Version 1.8.0-alpha07 contains these commits.
Новые возможности
Activity Compose has added a new
PredictiveBackHandler
Composable to handle predictive back gesture events. It provides aFlow
ofBackEventCompat
objects that must be collected in the suspending lamba you provide: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 } }
It also comes with a compile time warning via lint rule to ensure the
Flow
callscollect()
. ( Id2773 , b/294884345 )The
onBackPressedDispatcher
inComponentActivity
is now initialized lazily so that it is only created when required. ( I0bf8e )
Исправления ошибок
-
ComponentActivity
will no longer show a NPE on Android 13 when it gets anonBackPressed()
callback and the Activity has already beenDESTROYED
. ( Idb055 , b/291869278 ) - Removed usages of experimental
isAtLeastU()
API ( Ie9117 , b/289269026 )
Версия 1.8.0-альфа06
21 июня 2023 г.
androidx.activity:activity:1.8.0-alpha06
, androidx.activity:activity-compose:1.8.0-alpha06
, and androidx.activity:activity-ktx:1.8.0-alpha06
are released. Version 1.8.0-alpha06 contains these commits.
Новые возможности
- The
OnBackPressedDispatcher
now correctly cancels any callbacks that are removed during a Predictive Back Gesture. ( I3f90f )
Изменения API
- When passing
SystemBarStyle.auto
to theenableEdgeToEdge
API, you can now override thedetectDarkMode
lambda parameter to provide custom logic for detecting night mode. ( 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
, and androidx.activity:activity-ktx:1.8.0-alpha05
are released. This version is developed in an internal branch.
Изменения API
- Activity now provides a
BackEventCompat
class that serves as a backward compatible version ofBackEvent
that is decoupled from the frameworkBackEvent
class. - Breaking change: The
handleOnBackStarted
andhandleOnBackProgressed
methods ofOnBackPressedCallback
now receive anandroidx.activity.BackEventCompat
instance rather than a frameworkandroid.window.BackEvent
class. The equivalent@VisibleForTesting
APIs onOnBackPressedDispatcher
have also been updated. - The constructor for
OnBackPressedDispatcher
now takes an optionalConsumer<Boolean>
instance that allows the owners of the dispatcher to receive a callback whenever the number of enabled callbacks changes from zero to non-zero or vice versa.
Исправления ошибок
- From Activity
1.7.2
: FixReportDrawn
crashing when navigating away from a screen beforereport
is called. ( Ic46f1 , b/260506820 )
Версия 1.8.0-альфа04
10 мая 2023 г.
androidx.activity:activity:1.8.0-alpha04
, androidx.activity:activity-compose:1.8.0-alpha04
, and androidx.activity:activity-ktx:1.8.0-alpha04
are released. This was released from an internal branch.
Исправления ошибок
- From Activity 1.7.1 : - The
ReportFullyDrawExecuter
no longer leaks when usingComponentActivity
withActivityScenario
. ( Id2ff2 , b/277434271 )
Версия 1.8.0-альфа03
April 12, 2023
androidx.activity:activity:1.8.0-alpha03
, androidx.activity:activity-compose:1.8.0-alpha03
, and androidx.activity:activity-ktx:1.8.0-alpha03
are released. This was released from an internal branch.
Новые возможности
- Added
ComponentActivity.setUpEdgeToEdge()
to easily set up the edge-to-edge display in a backward-compatible manner.
Изменения API
-
ComponentActivity.onBackPressed()
has now been deprecated in favor of the APIs for handling back. Developers should now utilize theOnBackPressedDispatcher
, rather than overriding this method. ( Ibce2f , b/271596918 ) -
ComponentDialog
andComponentActivity
now contain public APIinitViewTreeOwners()
to be used to initialize all view tree owners before setting the content view. ( Ibdce0 , b/261314581 )
Исправления ошибок
- Fixed an issue where Fragments were incorrectly invalidating MenuHosts and causing other menus in the Activity to have unexpected behavior. ( I9404e , b/244336571 )
Other Changes
- The
ActivityResultRegister
now uses KotlinRandom
instead of 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
, and androidx.activity:activity-ktx:1.8.0-alpha02
are released. Developed from an internal branch.
Dependency update
- From Activity
1.7.0-rc01
: Activity now depends onLifecycle 2.6.0
.
Версия 1.8.0-альфа01
8 февраля 2023 г.
androidx.activity:activity:1.8.0-alpha01
, androidx.activity:activity-compose:1.8.0-alpha01
, and androidx.activity:activity-ktx:1.8.0-alpha01
are released. This was built from an internal branch.
Новые возможности
- The
OnBackPressedCallback
class now contains new Predictive Back progress callbacks for handling the back gesture starting, progress throughout the gesture, and the back gesture being canceled in addition to the previoushandleOnBackPressed()
callback for when the back gesture is committed.
Версия 1.7
Версия 1.7.2
24 мая 2023 г.
androidx.activity:activity:1.7.2
, androidx.activity:activity-compose:1.7.2
, and androidx.activity:activity-ktx:1.7.2
are released. Version 1.7.2 contains these commits.
Исправления ошибок
- Fix
ReportDrawn
crashing when navigating away from a screen beforereport
is called. ( Ic46f1 , b/260506820 )
Версия 1.7.1
19 апреля 2023 года
androidx.activity:activity:1.7.1
, androidx.activity:activity-compose:1.7.1
, and androidx.activity:activity-ktx:1.7.1
are released. Version 1.7.1 contains these commits.
Исправления ошибок
- The
ReportFullyDrawExecuter
no longer leaks when usingComponentActivity
withActivityScenario
. ( Id2ff2 , b/277434271 )
Версия 1.7.0
22 марта 2023 года
androidx.activity:activity:1.7.0
, androidx.activity:activity-compose:1.7.0
, and androidx.activity:activity-ktx:1.7.0
are released. Version 1.7.0 contains these commits.
Важные изменения с версии 1.6.0
- The Photo Picker activity contracts in
PickVisualMedia
andPickMultipleVisualMedia
have been updated to contain an additional fallback for whenMediaStore.ACTION_PICK_IMAGES
is unavailable that allows OEMs and system apps, such as Google Play services, to provide a consistent Photo Picker experience on a wider range of Android devices and API levels by implementing the fallback action . The Photo Picker will use this fallback if it is available before falling back to usingIntent.ACTION_OPEN_DOCUMENT
, which remains to support all API 19 and higher devices. -
ComponentDialog
now implementsSavedStateRegistryOwner
and has access to its ownSavedStateRegistry
and sets theSavedStateRegistryOwner
for itsViewTree
. It is now possible to use Jetpack Compose within aComponentDialog
as it meets both theLifecycleOwner
andSavedStateRegistryOwner
attached to the Window via theViewTree
APIs requirements. -
IntentSenderRequest.Builder.setFlags()
now allows you to set multiple flags fromIntent
, rather than only a single flag.
Kotlin Conversion
A number of Activity classes have been converted to Kotlin. All converted classes still retain their binary compatibility with previous versions. The following classes have source incompatible changes for classes written in Kotlin: ActivityResultRegistryOwner
, OnBackPressedDispatcherOwner
.
The table below provides the source conversions for the new version of Activity:
Activity 1.5 | Activity 1.6 |
---|---|
override fun getActivityResultRegistry() = activityResultRegistry | override val activityResultRegistry = activityResultRegistry |
override fun getOnBackPressedDispatcher() = onBackPressedDispatcher | override val onBackPressedDispatcher = onBackPressedDispatcher |
These classes were also converted to Kotlin, but remain source compatible: ContextAware
, ContextAwareHelper
, OnContextAvailableListener
, IntentSenderRequest
, and OnBackPressedDispatcher
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.
Three Activity Compose APIs have been added to make it more convenient to use the FullyDrawnReporter
from individual composables:
-
ReportDrawn
indicates that your composable is immediately ready for interaction. -
ReportDrawnWhen
takes a predicate (ie,list.count > 0
) to indicate when your composable is ready for interaction. -
ReportDrawnAfter
takes a suspending method that, when it completes, indicates that you are ready for interaction.
Обновления зависимости
- Activity now depends on Lifecycle
2.6.1
. ( 8fc31d ) - Activity now depends on ProfileInstaller
1.3.0
. ( 83d3b1 )
Версия 1.7.0-rc01
8 марта 2023 года
androidx.activity:activity:1.7.0-rc01
, androidx.activity:activity-compose:1.7.0-rc01
, and androidx.activity:activity-ktx:1.7.0-rc01
are released. Version 1.7.0-rc01 contains these commits.
Dependency update
- Activity now depends on
Lifecycle 2.6.0
.
Версия 1.7.0-бета02
22 февраля 2023 года
androidx.activity:activity:1.7.0-beta02
, androidx.activity:activity-compose:1.7.0-beta02
, and androidx.activity:activity-ktx:1.7.0-beta02
are released. Version 1.7.0-beta02 contains these commits.
Изменения API
- The action and extra used by the
PickVisualMedia
andPickMultipleVisualMedia
contracts as a fallback for whenMediaStore.ACTION_PICK_IMAGES
is unavailable are now public constants that provide API stability to OEMs and system apps that want to provide a consistent Photo Picker experience. The implementation of this fallback is still limited to only system apps. ( Icd320 )
Версия 1.7.0-бета01
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 )
Исправления ошибок
- The fallback for
PickVisualMedia
for when the framework Photo Picker is unavailable now correctly limits the handling to apps installed in the device's system image. ( If8ae6 )
Kotlin Conversions
-
ActivityResultRegistryOwner
is now written in Kotlin. This is a source incompatible change for those classes written in Kotlin - you must now override theactivityResultRegistry
property rather than implementing the previousgetActivityResultRegistry()
function. ( I0b00e ) -
OnBackPressedDispatcherOwner
is now written in Kotlin. This is a source incompatible change for those classes written in Kotlin - you must now override theonBackPressedDispatcher
property rather than implementing the previousgetOnBackPressedDispatcher
function. ( Ia277d ) -
ContextAware
,ContextAwareHelper
,OnContextAvailableListener
,IntentSenderRequest
andOnBackPressedDispatcher
are now written in Kotlin. ( I1a73e , Iada92 , aosp/2410754 , I18ac7 , b/257291701 )
Версия 1.7.0-альфа04
25 января 2023 года
androidx.activity:activity:1.7.0-alpha04
, androidx.activity:activity-compose:1.7.0-alpha04
, and androidx.activity:activity-ktx:1.7.0-alpha04
are released. Version 1.7.0-alpha04 contains these commits.
Новые возможности
- The
PickVisualMedia
andPickMultipleVisualMedia
Activity Result contracts will now use a Google Play services provided Photo Picker where available in cases where the Android system provided Photo Picker (eg,MediaStore.ACTION_PICK_IMAGES
) is not available. 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 )
Версия 1.7.0-альфа03
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. Версия 1.7.0-alpha03 содержит эти коммиты.
Новые возможности
-
ComponentDialog
now implementsSavedStateRegistryOwner
and has access to its ownSavedStateRegistry
and sets theSavedStateRegistryOwner
for its ViewTree. It is now possible to use Jetpack Compose within aComponentDialog
as it meets both theLifecycleOwner
andSavedStateRegistryOwner
attached to the Window via the ViewTree APIs requirements. ( Idca17 , I73468 b/261162296 )
Изменения API
- Added a
ReportDrawn
composable that immediately marks the activity as ready to callreportFullyDrawn
. ( Ic5b14 , b/259687964 )
Kotlin Conversions
- The
ActvitiyResultCallback
andOnBackPressedCallback
classes have both been converted to Kotlin while maintaining source and binary compatibility. ( Ifc5e5 , Ide1b0 , b/257291701 )
Версия 1.7.0-альфа02
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. Версия 1.7.0-alpha02 содержит эти коммиты.
Исправления ошибок
- From Activity
1.6.1
: Fixed an issue with thePickMultipleVisualMedia
Activity Result contract not launching on Android R devices when using the default value formaxItems
. ( Ie2776 , b/249182130 )
Версия 1.7.0-альфа01
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. Версия 1.7.0-alpha01 содержит эти коммиты.
FullyDrawnReporter APIs
ComponentActivity
now provides a FullyDrawnReporter
instance that allows multiple components to report when they are ready for interaction. ComponentActivity
will wait for all components to complete before calling reportFullyDrawn()
on your behalf. These APIs take care of the timing requirements for you and do not need to be called as part of an onDraw
call.
These APIs are encouraged to enable:
- Signaling the Android Runtime when startup completes, to ensure all of the code run during a multi-frame startup sequence is included and prioritized for background compilation.
- Signaling Macrobenchmark and Play Vitals when your application should be considered fully drawn for startup metrics, so you can track performance.
Two Activity Compose APIs have been added to make it more convenient to use the FullyDrawnReporter
from individual composables:
-
ReportDrawnWhen
takes a predicate (ie,list.count > 0
) to indicate when your composable is ready for interaction. -
ReportDrawnAfter
takes a suspending method that, when it completes, indicates that you are ready for interaction.
Версия 1.6.1
Версия 1.6.1
24 октября 2022 года
androidx.activity:activity:1.6.1
, androidx.activity:activity-compose:1.6.1
, and androidx.activity:activity-ktx:1.6.1
are released. Версия 1.6.1 содержит эти коммиты.
Исправления ошибок
- Fixed an issue with the
PickMultipleVisualMedia
Activity Result contract not launching on Android R devices when using the default value formaxItems
. ( Ie2776 , b/249182130 )
Версия 1.6.0
Версия 1.6.0
21 сентября 2022 года
androidx.activity:activity:1.6.0
, androidx.activity:activity-compose:1.6.0
, and androidx.activity:activity-ktx:1.6.0
are released. Версия 1.6.0 содержит эти коммиты.
Важные изменения с версии 1.5.0
- Added
ActivityResultContracts.PickVisualMedia
andActivityResultContracts.PickMultipleVisualMedia
for providing a backward compatible contract that usesMediaStore.ACTION_PICK_IMAGES
when the Photo Picker is available andIntent.ACTION_OPEN_DOCUMENT
when it is not available. - Integrated the
OnBackInvokedCallback
in Android 13 into theOnBackPressedDispatchers
provided byComponentActivity
andComponentDialog
. This ensures that all APIs built onOnBackPressedDispatcher
work when enabling a predictive back gesture .
Version 1.6.0-rc02
7 сентября 2022 г.
androidx.activity:activity:1.6.0-rc02
, androidx.activity:activity-compose:1.6.0-rc02
, and androidx.activity:activity-ktx:1.6.0-rc02
are released. Version 1.6.0-rc02 contains these commits.
Исправления ошибок
-
OnBackPressedDispatcher
now registers theOnBackInvokedCallback
with thePRIORITY_DEFAULT
instead ofPRIORITY_OVERLAY
. ( I3901f ) - Classes that extend
ComponentActivity
will now always have both of theironMultiWindowModeChanged()
callbacks dispatched. ( Ic4d85 ) - The
ActivityResultRegistry
will no longer return a result to theActivityResultCallback
when thelaunch
call throws anyException
and the callback was registered without aLifecycleOwner
. ( Ia7ff7 , b/238350794 ) -
ComponentActivity
will now properly dispatch menu calls without the need to call the super function in your activity. ( Ie33c5 , b/238057118 )
Dependency Update
- The
Activity
library now depends on Lifecycle2.5.1
. ( If6697 )
Версия 1.6.0-rc01
24 августа 2022 года
androidx.activity:activity:1.6.0-rc01
, androidx.activity:activity-compose:1.6.0-rc01
, and androidx.activity:activity-ktx:1.6.0-rc01
are released. Версия 1.6.0-rc01 содержит эти коммиты.
Исправления ошибок
- Initializing an
OnBackPressedDispatcher
will no longer causeClassVerificationError
s when using SDK versions prior to 33. ( Ic32e1 ) - Classes that override
ComponentActivity
'sonPictureInPictureModeChanged()
callback will now always have their callbacks dispatched. ( Ib7fdb )
Версия 1.6.0-бета01
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. Версия 1.6.0-beta01 содержит эти коммиты.
Изменения API
- Marked the deprecated
startActivityForResult
andstartIntentSenderForResult
methods onComponentActivity
with@NonNull
because passingnull
has always resulted in a crash. ( Id2a25 , b/231476082 )
Исправления ошибок
- From Activity
1.5.1
: TheActivityResultRegistry
will no longer return a result to theActivityResultCallback
when thelaunch
call throws anyException
and the callback was registered without aLifecycleOwner
. ( Ia7ff7 , b/238350794 ) - From Activity
1.5.1
:ComponentActivity
will 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
: TheActivity
library now depends on theLifecycle
version2.5.1
. ( If6697 )
Версия 1.6.0-альфа05
15 июня 2022 года
androidx.activity:activity:1.6.0-alpha05
, androidx.activity:activity-compose:1.6.0-alpha05
, and androidx.activity:activity-ktx:1.6.0-alpha05
are released. Version 1.6.0-alpha05 was developed in a private pre-release branch and has no public commits.
Изменения API
-
minCompileSdk
is now 33 to align with Tiramisu Beta 3 SDK
Исправления ошибок
- Fixed crash on older devices when doing SDK extension check for the
PickVisualMedia
ActivityResultContract
so that it should now work withACTION_OPEN_DOCUMENT
on devices running Android 10 and lower.
Версия 1.6.0-альфа04
18 мая 2022 года
androidx.activity:activity:1.6.0-alpha04
and androidx.activity:activity-ktx:1.6.0-alpha04
are released.
Исправления ошибок
- Fixed an error in
PickVisualMediaRequest
where attempting to create a request, either via the Builder or the top level Kotlin function, would result in a stack overflow. - Integrated the
OnBackInvokedCallback
in Android 13 Dev Beta 2 into theOnBackPressedDispatcher
provided byComponentDialog
. This ensures that all APIs built onOnBackPressedDispatcher
work when enabling a predictive back gesture .
Версия 1.6.0-альфа03
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.PickVisualMedia
andActivityResultContracts.PickMultipleVisualMedia
for providing a backward compatible contract that usesMediaStore.ACTION_PICK_IMAGES
when the Photo Picker is available andIntent.ACTION_OPEN_DOCUMENT
when it is not available. - Integrated the
OnBackInvokedCallback
in Android 13 Dev Beta 1 into theOnBackPressedDispatcher
provided byComponentActivity
. This ensures that all APIs built onOnBackPressedDispatcher
work when enabling a predictive back gesture .
Версия 1.6.0-альфа01
23 марта 2022 года
androidx.activity:activity:1.6.0-alpha01
, androidx.activity:activity-compose:1.6.0-alpha01
, and androidx.activity:activity-ktx:1.6.0-alpha01
are released.
- Note: This version will only compile against the Android 13 Developer Preview 2 SDK.
Новые возможности
- Integrated changes in Android 13 Dev Preview 2 into
ComponentActivity
.
Версия 1.5.1
Версия 1.5.1
27 июля 2022 года
androidx.activity:activity:1.5.1
, androidx.activity:activity-compose:1.5.1
, and androidx.activity:activity-ktx:1.5.1
are released. Версия 1.5.1 содержит эти коммиты.
Исправления ошибок
The
ActivityResultRegistry
will no longer return a result to theActivityResultCallback
when thelaunch()
call throws anyException
and the callback was registered without aLifecycleOwner
. ( Ia7ff7 , b/238350794 )ComponentActivity
will now properly dispatch menu calls toonPrepareOptionMenu()
,onCreateOptionsMenu()
andonOptionsItemSelected()
overrides without the need to call the super function. ( Ie33c5 , b/238057118 )
Dependency update
- The
Activity
library now depends on the Lifecycle2.5.1
. ( If6697 )
Версия 1.5.0
Версия 1.5.0
29 июня 2022 года
androidx.activity:activity:1.5.0
, androidx.activity:activity-compose:1.5.0
, and androidx.activity:activity-ktx:1.5.0
are released. Версия 1.5.0 содержит эти коммиты.
Important changes since 1.4.0
- ComponentDialog -
ComponentDialog
is a subclass ofDialog
that includes anOnBackPressedDispatcher
that 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 aComponentActivity
or aComponentDialog
. - Callback Interfaces -
ComponentActivity
now implements a set of modular callback interfaces that can be used instead of theActivity
callbacks. These interfaces include the following:OnNewIntentProvider
,OnConfigurationChangedProvider
,OnTrimMemoryProvider
,OnPictureInPictureModeChangedProvider
,OnMultiWindowModeChangedProvider
- CreationExtras Integration -
ComponentActivity
now has the ability to provide a statelessViewModelProvider.Factory
via Lifecycle2.5.0
'sCreationExtras
.
Другие изменения
- The no parameter constructor for
ActivityResultContracts.CreateDocument
has been deprecated and replaced with a new constructor that takes a concrete mime type (eg, "image/png") as is required byIntent.ACTION_CREATE_DOCUMENT
.
Версия 1.5.0-rc01
11 мая 2022 года
androidx.activity:activity:1.5.0-rc01
, androidx.activity:activity-compose:1.5.0-rc01
, and androidx.activity:activity-ktx:1.5.0-rc01
are released with no changes from 1.5.0-beta01. Версия 1.5.0-rc01 содержит эти коммиты.
Версия 1.5.0-бета01
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. Версия 1.5.0-beta01 содержит эти коммиты.
Dependency updates
- Activity now depends on Lifecycle
2.4.0-beta01
.
Version 1.5.0-alpha05
6 апреля 2022 года
androidx.activity:activity:1.5.0-alpha05
, androidx.activity:activity-compose:1.5.0-alpha05
, and androidx.activity:activity-ktx:1.5.0-alpha05
are released. Version 1.5.0-alpha05 contains these commits.
Исправления ошибок
-
ComponentActivity
'sonPanelClosed()
now calls the superonPanelClosed()
as well, fixing an issue where theonContextMenuClosed
method would not be called. ( Ib6f77 )
Версия 1.5.0-альфа04
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. Версия 1.5.0-alpha04 содержит эти коммиты.
Исправления ошибок
-
SavedStateViewFactory
now supports usingCreationExtras
even when it was initialized with aSavedStateRegistryOwner
. If extras are provided, the initialized arguments are ignored. ( I6c43b , b/224844583 )
Версия 1.5.0-Alpha03
23 февраля 2022 года
androidx.activity:activity:1.5.0-alpha03
, androidx.activity:activity-compose:1.5.0-alpha03
, and androidx.activity:activity-ktx:1.5.0-alpha03
are released. Версия 1.5.0-Alpha03 содержит эти коммиты.
Изменения API
- You can now pass
CreationExtras
to the activityby viewModels()
function ( I6a3e6 , b/217600303 )
Версия 1.5.0-Alpha02
9 февраля 2022 года
androidx.activity:activity:1.5.0-alpha02
, androidx.activity:activity-compose:1.5.0-alpha02
, and androidx.activity:activity-ktx:1.5.0-alpha02
are released. Версия 1.5.0-Alpha02 содержит эти коммиты.
Новые возможности
-
ComponentActivity
now implements theOnPictureInPictureModeChangedProvider
interface to allow any component to receive picture-in-picture mode change events. ( I9f567 ) -
ComponentActivity
now implements theOnMultiWindowModeChangedProvider
interface to allow any component to receive multi-window mode change events. ( I62d91 )
Версия 1.5.0-Alpha01
26 января 2022 года
androidx.activity:activity:1.5.0-alpha01
, androidx.activity:activity-compose:1.5.0-alpha01
, and androidx.activity:activity-ktx:1.5.0-alpha01
are released. Версия 1.5.0-Alpha01 содержит эти коммиты.
Новые возможности
-
ComponentActivity
now integrates with ViewModel CreationExtras, introduced as part of Lifecycle2.5.0-alpha01
. ( Ie7e00 , b/207012584 ) - Added
ComponentDialog
, a subclass ofDialog
that includes anOnBackPressedDispatcher
that 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 aComponentActivity
or aComponentDialog
. ( I8a1bc ) -
ComponentActivity
now implements the newOnNewIntentProvider
interface to allow any component to receive these events. ( If1f8b ) -
ComponentActivity
now implements the newOnConfigurationChangedProvider
interface to allow any component to receive these events. ( If623b ) -
ComponentActivity
now implements the newOnTrimMemoryProvider
interface to allow any component to receive these events. ( Ia9295 )
Изменения API
- The no parameter constructor for
ActivityResultContracts.CreateDocument
has been deprecated and replaced with a new constructor that takes a concrete mime type (eg,"image/png"
) as is required byIntent.ACTION_CREATE_DOCUMENT
. ( I2bec6 ) - The
OnBackPressedDispatcherOwner
associated with a View can now be retrieved via theViewTreeOnBackPressedDispatcherOwner
, rather than relying on casting theContext
. ( I74685 )
Исправления ошибок
- Fixed a crash when accessing a
ViewModel
for the very first time from aregisterForActivityResult()
callback or the callbacks to aLifecycleObserver
added as part ofinit
of aComponentActivity
. ( Ife83f )
Версия 1.4.0
Версия 1.4.0
27 октября 2021 года
androidx.activity:activity:1.4.0
, androidx.activity:activity-compose:1.4.0
, and androidx.activity:activity-ktx:1.4.0
are released. Версия 1.4.0 содержит эти коммиты.
Важные изменения с 1.3.0
- AndroidX
ComponentActivity
now implements theMenuHost
interface. This allows any component to add menu items to theActionBar
by adding aMenuProvider
instance to the activity. EachMenuProvider
can optionally be added with aLifecycle
that will automatically control the visibility of those menu items based on theLifecycle
state and handle the removal of theMenuProvider
when theLifecycle
is destroyed. - The
ActivityResultContract
class has been rewritten in Kotlin to ensure that developers writing custom contracts in Kotlin can define the correct nullability for their input and output classes. - The
ActivityResultContracts
class and its contracts have been rewritten in Kotlin to ensure the proper nullability.
Версия 1.4.0-RC01
13 октября 2021 года
androidx.activity:activity:1.4.0-rc01
, androidx.activity:activity-compose:1.4.0-rc01
, and androidx.activity:activity-ktx:1.4.0-rc01
are released. Версия 1.4.0-RC01 содержит эти коммиты.
Исправления ошибок
- The
ActivityResultRegistry
will no longer return a result to theActivityResultCallback
when thelaunch
call throws anyException
. ( If4f91 , b/200845664 )
Версия 1.4.0-бета01
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. Версия 1.4.0-бета01 содержит эти коммиты.
Изменения API
- Fixed the type for the
ActivityResultContracts.OpenMultipleDocuments
andActivityResultContracts.GetMultipleContents
that 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.RequestMultiplePermissions
classes are now accessible when using Kotlin via their now publicCompanion
objects. ( 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 )
Версия 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. Версия 1.4.0-Alpha02 содержит эти коммиты.
Новые возможности
- The
activity-compose
artifact now contains aLaunchDuringComposition
lint error that prevents you from calling thelaunch
method ofActivityResultLauncher
as part of composition as composition should be side-effect free. Use the APIs for handling side-effects . ( 7c2bbe , b/191347220 )
Изменения API
- The
ActivityResultContract
class has been rewritten in Kotlin to ensure that developers writing custom contracts in Kotlin can define the correct nullability for their input and output classes. ( I8a8f5 ) - The
ActivityResultContracts
class and its contracts have been rewritten in Kotlin to ensure the proper nullability. ( I69802 )
Версия 1.4.0-Alpha01
1 сентября 2021 года
androidx.activity:activity:1.4.0-alpha01
, androidx.activity:activity-compose:1.4.0-alpha01
, and androidx.activity:activity-ktx:1.4.0-alpha01
are released. Версия 1.4.0-Alpha01 содержит эти коммиты.
Новые возможности
- AndroidX
ComponentActivity
now implements theMenuHost
interface.. This allows any component to add menu items to theActionBar
by adding aMenuProvider
instance to the activity. EachMenuProvider
can optionally be added with aLifecycle
that will automatically control the visibility of those menu items based on theLifecycle
state and handle the removal of theMenuProvider
when theLifecycle
is destroyed. ( I3b608 ):
/**
* Using the addMenuProvider() API directly in your Activity
**/
class ExampleActivity : ComponentActivity(R.layout.activity_example) {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Add menu items without overriding methods in the Activity
addMenuProvider(object : MenuProvider {
override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
// Add menu items here
menuInflater.inflate(R.menu.example_menu, menu)
}
override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
// Handle the menu selection
return true
}
})
}
}
/**
* Using the addMenuProvider() API in a Fragment
**/
class ExampleFragment : Fragment(R.layout.fragment_example) {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
// The usage of an interface lets you inject your own implementation
val menuHost: MenuHost = requireActivity()
// Add menu items without using the Fragment Menu APIs
// Note how we can tie the MenuProvider to the viewLifecycleOwner
// and an optional Lifecycle.State (here, RESUMED) to indicate when
// the menu should be visible
menuHost.addMenuProvider(object : MenuProvider {
override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
// Add menu items here
menuInflater.inflate(R.menu.example_menu, menu)
}
override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
// Handle the menu selection
return true
}
}, viewLifecycleOwner, Lifecycle.State.RESUMED)
}
Behavior Changes
- The
ActivityResultRegistry
will now throw anIllegalStateException
when attempting to calllaunch()
on anActivityResultLauncher
that has not be registered or that has been unregistered. ( Ida75d , b/192567522 )
Внешний вклад
Версия 1.3.1
Версия 1.3.1
4 августа 2021 года
androidx.activity:activity:1.3.1
, androidx.activity:activity-compose:1.3.1
, and androidx.activity:activity-ktx:1.3.1
are released. Версия 1.3.1 содержит эти коммиты.
Dependency updates
- Activity now depends on Kotlin
1.5.21
. - Activity Compose now depends on Compose
1.0.1
.
Версия 1.3.0
Версия 1.3.0
28 июля 2021 года
androidx.activity:activity:1.3.0
, androidx.activity:activity-compose:1.3.0
, and androidx.activity:activity-ktx:1.3.0
are released. Версия 1.3.0 содержит эти коммиты.
Важные изменения с 1.2.0
- Activity Compose artifact - The
activity-compose
artifact provides thesetContent
extension method for hosting your Jetpack Compose UI in an activity and Compose specific wrappers for interacting with theComponentActivity
APIs for handling the system back button and the Activity Result APIs. See the documentation for more details. - CaptureVideo contract - The
CaptureVideo
ActivityResultContract
replaces the now deprecatedTakeVideo
contract and returns a boolean denoting success that works across many camera apps. - Picture-In-Picture Hint View Tracking - Users of
activity-ktx
can now use thetrackPipAnimationHintView
extension method onActivity
to automatically rebuild thePictureInPictureParams
with the new position of the view as it changes position relative to the window.
Version 1.3.0-rc02
14 июля 2021 года
androidx.activity:activity:1.3.0-rc02
, androidx.activity:activity-compose:1.3.0-rc02
, and androidx.activity:activity-ktx:1.3.0-rc02
are released. Version 1.3.0-rc02 contains these commits.
Исправления ошибок
- The
ActivityResultRegistry
callbacks are now properly saved and restored so callbacks are not duplicated in the savedState. ( I97816 , b/191893160 )
Версия 1.3.0-RC01
1 июля 2021 года
androidx.activity:activity:1.3.0-rc01
, androidx.activity:activity-compose:1.3.0-rc01
, and androidx.activity:activity-ktx:1.3.0-rc01
are released with no changes from 1.3.0-beta02
. Версия 1.3.0-RC01 содержит эти коммиты.
Версия 1.3.0-бета02
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. Версия 1.3.0-бета02 содержит эти коммиты.
Updated activity-compose
to depend on Compose 1.0.0-beta09
. androidx.compose.ui:ui-test-junit4
now has a compile time dependency on activity-compose
.
Версия 1.3.0-бета01
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. Версия 1.3.0-бета01 содержит эти коммиты.
Изменения API
- 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
CaptureVideo
ActivityResultContract
returns a boolean to yourActivityResultCallback
indicating if your video was successfully saved to the given URI. This replaces the now deprecatedTakeVideo
contract as camera apps very rarely supported returning a thumbnail bitmap, making the result unhelpful. ( Ie21f2 , b/185938070 ) - Added new API
Activity#setPipAnimationHintView
to update the PipParams' source rect hint whenever the view moves. ( I9063d )
Изменения API
- The
rememberLauncherForActivityResult
function now returns a launcher that deprecates theunregister()
function - registration and unregistering the launcher is handled automatically byrememberLauncherForActivityResult
. ( I2443e )
Compose Compatibility
-
androidx.activity:activity-compose:1.3.0-alpha08
is only compatible with Compose version1.0.0-beta07
and 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.
Исправления ошибок
-
rememberLauncherForActivityResult
now returns a stable reference to the sameActivityResultLauncher
instance even if the contract changes due to recompositions. ( Id2d6d ) - Using unstable versions of Fragments above
1.3.0
will no longer throw a false positive lint error telling you to 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
- The
registerForActivityResult()
API has been renamed torememberLauncherForActivityResult()
to better indicate that the returnedActivityResultLauncher
is a managed object that is remembered on your behalf. Attempting to callunregister
the returnedActivityResultLauncher
will now throw an error. ( I2bb6d ) -
LocalOnBackPressedDispatcherOwner.current
andLocalActivityResultRegistryOwner.current
now return a nullable value to better determine whether it is available in the current composition. APIs that requires those APIs, such asBackHandler
andrememberLauncherForActivityResult()
, respectively, will now throw a more descriptive error if the underlying owner is not found.NavHost
now works even when anOnBackPressedDispatcherOwner
is not found, such is the case when previewing theNavHost
. ( I7d8b4 )
Исправления ошибок
- The
BackHandler
will now properly intercept back presses in the event that the Activity isSTOPPED
, thenSTARTED
again, and other callbacks were added with a LifecycleOwner. ( I71de6 , b/182284739 ) - Using the
launch()
method extension with a customActivityResultContract
that has aUnit
input 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.
Исправления ошибок
- From Activity 1.2.2 : Fixed an issue in the
InvalidFragmentVersionForActivityResult
lint check that led to a false positive when using Fragment 1.3.1 or higher. ( I54da1 , b/182388985 ) - From Activity 1.2.2 :
ComponentActivity
now avoids aClassNotFoundException
when launching anIntent
from anActivityResultContract
that was previously held as an extra in anotherIntent
. ( Ieff05 , b/182906230 )
Обновления зависимости
- 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.
Исправления ошибок
- From Activity
1.2.1
:RequestMultiplePermissions
now always returns results for all requested permissions instead of only permissions that weren't previously granted. ( I50bc3 , b/180884668 ) - From Activity
1.2.1
:ActivityResultRegistry
now ensures that in 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
BackHandler
where the previously setonBack
lambda was still being used after recomposition. ( 8eb5eb )
Версия 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. Версия 1.3.0-Alpha03 содержит эти коммиты.
Новые возможности
- There is a now a Composable
registerForActivityResult
function for getting results from activities within composables. ( Ia7851 , b/172690553 )
Изменения API
-
LocalOnBackPressedDispatcherOwner
now has aprovides
functions that can be used withCompositionLocalProvider
, replacing theasProvidableCompositionLocal()
API. ( I45d24 )
Версия 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. Версия 1.3.0-Alpha02 содержит эти коммиты.
Исправления ошибок
- Fixed an issue in Activity Compose
1.3.0-alpha01
that causes aNoSuchMethodError: No static method setContent
exception when using Compose1.0.0-alpha12
. All Compose users should depend on1.3.0-alpha02
and above. ( b/179911234 )
Изменения API
- The
BackHandler
API can be used to allow a Composable to intercept the system back button. ( I58ed5 , b/172154006 )
Версия 1.3.0-Alpha01
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. Версия 1.3.0-Alpha01 содержит эти коммиты.
Новые возможности
- The new
activity-compose
artifact provides Jetpack Compose specific helpers forandroidx.activity
specific APIs.-
ComponentActivity.setContent
has moved fromandroidx.compose.ui.platform.setContent
toandroidx.activity.compose.setContent
. ( Icf416 )
-
Известные проблемы
- Using Activity Compose
1.3.0-alpha01
and libraries that depend on it, such asandroidx.compose.ui:ui-test-junit4:1.0.0-alpha12
, will result in aNoSuchMethodError: No static method setContent
exception. ( 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.
Исправления ошибок
- 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.
Исправления ошибок
- Using the
launch()
method extension with a customActivityResultContract
that has aUnit
input will no longer cause aNullPointerException
( I76282 , b/183837954 ) - Fixed a false positive lint error telling you to use Fragment
1.3.0
when using an snapshot, alpha, beta, or RC build of a newer version of Fragments. ( f4a57e , b/184847092 )
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.
Исправления ошибок
- Fixed an issue in the
InvalidFragmentVersionForActivityResult
lint check that led to a false positive when using Fragment 1.3.1 or higher. ( I54da1 , b/182388985 ) -
ComponentActivity
now avoids aClassNotFoundException
when launching anIntent
from anActivityResultContract
that was previously held as an extra in anotherIntent
. ( Ieff05 , b/182906230 )
Обновления зависимости
- Activity now depends on Lifecycle
2.3.1
.
Версия 1.2.1
Версия 1.2.1
March 10, 2021
androidx.activity:activity:1.2.1
and androidx.activity:activity-ktx:1.2.1
are released. Версия 1.2.1 содержит эти коммиты.
Исправления ошибок
-
RequestMultiplePermissions
now always returns results for all requested permissions instead of only permissions that weren't previously granted. ( I50bc3 , b/180884668 ) -
ActivityResultRegistry
now ensures that in progresslaunch()
requests will return their results even if youunregister()
, thenregister()
again with the same key. ( I9ef34 , b/181267562 )
Версия 1.2.0
Версия 1.2.0
February 10, 2021
androidx.activity:activity:1.2.0
and androidx.activity:activity-ktx:1.2.0
are released. Версия 1.2.0 содержит эти коммиты.
Major changes since 1.1.0
- Activity Result APIs :
ComponentActivity
now provides anActivityResultRegistry
that 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
:ComponentActivity
now implementsContextAware
, allowing you to add one or moreOnContextAvailableListener
instances 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
FragmentActivity
in Fragment 1.3.0 to restore the state of theFragmentManager
. Any listeners added to subclasses ofFragmentActivity
will run after that listener. - This API is used by
AppCompatActivity
in AppCompat 1.3.0-alpha02 or higher. Any listeners added to subclasses ofAppCompatActivity
will run after that listener.
- A suspending Kotlin extension
ViewTree
Support :ComponentActivity
now supports theViewTreeLifecycleOwner.get(View)
,ViewTreeViewModelStoreOwner.get(View)
, andViewTreeSavedStateRegistryOwner
APIs added in Lifecycle2.3.0
and SavedState1.1.0
such that it will return the Activity as theLifecycleOwner
,ViewModelStoreOwner
, andSavedStateRegistryOwner
for any Views directly added to theComponentActivity
.
- reportFullyDrawn() backport - The
Activity
method ofreportFullyDrawn()
has been backported inComponentActivity
to work on all API levels, fixing a crash on API 19 and adding tracing for this method for all API levels.
Версия 1.2.0-RC01
December 16, 2020
androidx.activity:activity:1.2.0-rc01
and androidx.activity:activity-ktx:1.2.0-rc01
are released. Версия 1.2.0-RC01 содержит эти коммиты.
Исправления ошибок
- The
ActivityResultRegistry
now always restores the exact state that was saved. ( Idd56b ) - Add tracing to
ComponentActivity.reportFullyDrawn
( Ic7632 )
Внешний вклад
-
ComponentActivity
now 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 )
Версия 1.2.0-бета02
December 2, 2020
androidx.activity:activity:1.2.0-beta02
and androidx.activity:activity-ktx:1.2.0-beta02
are released. Версия 1.2.0-бета02 содержит эти коммиты.
Исправления ошибок
- Fixed an issue where the Activity Result API would not wait for the Lifecycle to be
STARTED
before delivering results when registered with aLifecycle
. ( I109ea )
Внешний вклад
- Updated the documentation for
launch()
to explicitly call out that it can throw anActivityNotFoundException
. Thanks Michał Zieliński! ( aosp/1493580 )
Версия 1.2.0-бета01
October 1, 2020
androidx.activity:activity:1.2.0-beta01
and androidx.activity:activity-ktx:1.2.0-beta01
are released. Версия 1.2.0-бета01 содержит эти коммиты.
Исправления ошибок
The
ActivityResultRegistry
now 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 )Lifecycle
observers are properly removed when callingunregister()
on anActivityResultLauncher
. ( b/165608393 )
Behavior Changes
- The
ActivityResultRegistry
now throws anIllegalStateException
when attempting to callregister()
with aLifecycleOwner
whoseLifecycle
has already reachedSTARTED
. ( b/165435866 )
Documentation Updated
-
ContextAware
documentation links toLifecycleOwner
to highlightLifecycle
callbacks as the appropriate place for creation and destruction events. ( aosp/1414152 )
Версия 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. Версия 1.2.0-Alpha08 содержит эти коммиты.
Новые возможности
-
ComponentActivity
now implementsContextAware
, allowing you to add one or moreOnContextAvailableListener
instances 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
FragmentActivity
in Fragment 1.3.0-alpha08 to restore the state of theFragmentManager
. Any listeners added to subclasses ofFragmentActivity
will run after that listener. ( I513da ) - This API is used by
AppCompatActivity
in AppCompat 1.3.0-alpha02 . Any listeners added to subclasses ofAppCompatActivity
will run after that listener. ( I513da )
- A suspending Kotlin extension
Исправления ошибок
- Fixed an issue with the
ActivityResultFragmentVersionDetector
Lint check that caused it to break when using Lint 27.1.0 or higher. ( b/162155191 )
Версия 1.2.0-Alpha07
July 22, 2020
androidx.activity:activity:1.2.0-alpha07
and androidx.activity:activity-ktx:1.2.0-alpha07
are released. Версия 1.2.0-Alpha07 содержит эти коммиты.
Новые возможности
- Added a new
InvalidFragmentVersionForActivityResult
lint check that verifies that you are using Fragment1.3.0-alpha07
when using the Activity Result API , avoiding runtime crashes due to “invalid request code” issues and non-functioning permission requests caused by using older versions of Fragments. ( b/152554847 )
Внешний вклад
- Fixed an
ArrayIndexOutOfBoundsException
when parsing the results for theRequestPermission
Activity Result contract. ( I8f9e3 , b/161057605 )
Версия 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. Версия 1.2.0-Alpha06 содержит эти коммиты.
Новые возможности
- You can now destructure the
ActivityResult
class in kotlin to directly access therequestCode
andintent
. ( b/157212935 ) -
ActivityResultLauncher
now allows you to get theActivityResultContract
that was used to register the launcher. ( b/156875743 )
Изменения API
- Breaking change : The
invoke()
method onActivityResultRegistry
has been renamed toonLaunch()
. ( b/157496491 ) - The
OpenMultipleDocuments
contract now returns an empty list instead ofnull
to the registered callback if no result is returned. ( b/157348014 )
Версия 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. Версия 1.2.0-Alpha05 содержит эти коммиты.
Новые возможности
- Added support for
ViewTreeViewModelStoreOwner
from Lifecycle2.3.0-alpha03
, andViewTreeSavedStateRegistryOwner
from SavedState1.1.0-alpha01
when using aView
within aComponentActivity
. ( aosp/1297993 , aosp/1300264 )
Изменения API
- The
TakePicture
contract now returns aboolean
indicating success rather than a thumbnailBitmap
as this was very rarely supported by camera apps when writing the image to the providedUri
. ( b/154302879 ) - The
invoke()
extensions onActivityResultLauncher
have been removed in favor of explicitly usinglaunch()
to better indicate that these are asynchronous operations. Kotlin extensions forlaunch
have been added to theandroidx.activity.result
package forActivityResultLauncher<Void>
andActivityResultLauncher<Unit>
that remove the need to pass innull
orUnit
, respectively, mirroring that behavior from the previouslyinvoke()
extensions. ( aosp/1304674 , aosp/1304675 ) - The
IntentSenderRequest.Builder
methods forsetFlagsMask()
andsetFlagsValues()
has been combined into a singlesetFlags()
method. ( aosp/1302111 )
Исправления ошибок
- When registering an
ActivityResultCallback
with aLifecycleOwner
, fixed an issue where the callback would be triggered before the state reachesSTARTED
. ( aosp/1309744 )
Behavior Changes
- The
ActivityResultRegistry
now generates request codes starting at0xFFFF
rather than at0
, preventing overlap when usingstartActivityForResult()
orrequestPermissions()
in an activity. ( aosp/1302324 )
Версия 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. Версия 1.2.0-Alpha04 содержит эти коммиты.
Новые возможности
- Added a contract that can call startIntentSenderForResult to the ActivityResult APIs. ( b/153007517 )
Изменения API
- The
prepareCall()
method has been renamed toregisterForActivityResult()
, both onComponentActivity
here and in Fragment1.3.0-alpha04
. ( aosp/1278717 ) - The
GetContents
,OpenDocuments
, andRequestPermissions
contracts have been renamed toGetMultipleContents
,OpenMultipleDocuments
, andRequestMultiplePermissions
, respectively. ( aosp/1280161 ) -
ComponentActivity
now implements theActivityResultRegisteryOwner
interface. ( aosp/1290888 ) - - The
startActivityForResult()
/onActivityResult()
andonRequestPermissionsResult()
APIs onComponentActivity
have been deprecated. Please use the Activity Result APIs . ( b/154751887 )
Исправления ошибок
- When using the
GetMultipleContents
andOpenMultipleDocuments
contracts and selecting a single item, it is now correctly returned to your callback. ( b/152941153 )
Версия 1.2.0-Alpha03
April 1, 2020
androidx.activity:activity:1.2.0-alpha03
and androidx.activity:activity-ktx:1.2.0-alpha03
are released. Версия 1.2.0-Alpha03 содержит эти коммиты.
Новые возможности
- Added the
TakeVideo
,PickContact
,GetContent
,GetContents
,OpenDocument
,OpenDocuments
,OpenDocumentTree
, andCreateDocument
contracts 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
- The
TakePicture
contract now takes aUri
input 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 onActivityResultRegistry
has been renamed toregister()
. ( aosp/1267621 ) - The
dispose()
method onActivityResultLauncher
has been renamed tounregister()
and theunregisterResultCallback()
onActivityResultRegistry
has been removed. ( aosp/1267621 ) - The
createIntent()
method ofActivityResultContact
now takes aContext
in addition to the input to make it possible to create explicit Intents. ( aosp/1238800 ) - An
ActivityResultContract
can now overridegetSynchronousResult()
to deliver a result without callingstartActivityForResult
. This is used by theRequestPermission
andRequestPermissions
contracts to correctly deliver a 'granted' status if the requested permissions are already granted. ( b/151110799 ) - The previously available
Dial
contract has been removed as thatIntent
is 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 ofActivityResultRegistry
exceptinvoke()
, and a number of the default contracts that do not support optional extras. ( b/152439361 )
Исправления ошибок
- Fixed a
NullPointerException
inActivityResultRegistry
when attempting to deliver results to a callback that has not yet been re-registered after a configuration change;ActivityResultRegistry
now holds onto these pending results and delivers them when the callback is re-registered. ( b/152137004 )
Версия 1.2.0-Alpha02
March 18, 2020
androidx.activity:activity:1.2.0-alpha02
and androidx.activity:activity-ktx:1.2.0-alpha02
are released. Версия 1.2.0-Alpha02 содержит эти коммиты.
Новые возможности
- ActivityResultRegistry :
ComponentActivity
now provides anActivityResultRegistry
that 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 )
Версия 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. Версия 1.2.0-Alpha01 содержит эти коммиты.
Новые возможности
- Added support for the
ViewTreeLifecycleOwner.get(View)
API added in Lifecycle2.3.0-alpha01
such that it will return the Activity as theLifecycleOwner
for any Views directly added to the Activity. ( aosp/1182955 )
Исправления ошибок
- Fixed a regression introduced in Activity
1.1.0
when running on older versions of the platform whereonBackPressed()
would cause anIllegalStateException
due to a bug in theandroid.app.FragmentManager
. ( b/146290338 )
Версия 1.1.0
Версия 1.1.0
January 22, 2020
androidx.activity:activity:1.1.0
is released. Версия 1.1.0 содержит эти коммиты .
Важные изменения с версии 1.0.0
- Lifecycle ViewModel SavedState Integration :
SavedStateViewModelFactory
is now the default factory used when usingby viewModels()
, theViewModelProvider
constructor, orViewModelProviders.of()
with aComponentActivity
or its subclasses.
Версия 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-rc03
and 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
.
Версия 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
. Версия 1.1.0-rc01 содержит эти коммиты .
Версия 1.1.0-бета01
October 9, 2019
androidx.activity:activity:1.1.0-beta01
and androidx.activity:activity-ktx:1.1.0-beta01
are released. Версия 1.1.0-beta01 содержит эти коммиты .
Dependency changes
- Activity now depends on SavedState 1.0.0 stable.
Версия 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 .
New features
- Activity now depends on Core 1.1.0 stable.
Исправления ошибок
- Activity now depends on Lifecycle
2.2.0-alpha04
.
Версия 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 .
New features
-
SavedStateViewModelFactory
is now the default factory used when usingby viewModels()
, theViewModelProvider
constructor, orViewModelProviders.of()
with aComponentActivity
( b/135716331 )
Версия 1.1.0-альфа01
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 .
New features
-
activity
now depends on Lifecycle2.2.0-alpha02
. ( aosp/1007817 ) -
activity-ktx
added a dependency onlifecycle-runtime-ktx
; you no longer need to explicitly add it to your dependencies when usingactivity-ktx
or libraries that depend onactivity-ktx
(such asfragment-ktx
). ( aosp/987162 )
Версия 1.0.0
Версия 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 :
ComponentActivity
serves as the new base class forFragmentActivity
in Fragment1.1.0
and, by extension,AppCompatActivity
in AppCompat1.1.0
. - activity-ktx : The
activity-ktx
module includes aby viewModels
Kotlin property extension for accessing ViewModels. This module is automatically included when you includefragment-ktx
from Fragment1.1.0
. - OnBackPressedDispatcher : As a composable alternative to overriding
onBackPressed()
, you can now register aOnBackPressedCallback
from anyLifecycleOwner
(such as a fragment) to intercept system back button events. A lambda with receiver versionaddCallback
has 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 anyViewModelStoreOwner
that makes the ownership of the retained objects clear and provides anonCleared()
callback for cleaning up resources when the activity is finally destroyed.
Версия 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 .
Версия 1.0.0-бета01
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
addOnBackPressedCallback
andremoveOnBackPressedCallback
methods onComponentActivity
have been removed. aosp/953857 - The
setEnabled()
andisEnabled()
methods ofOnBackPressedCallback
are now final. b/131416833 - The
remove()
method ofOnBackPressedCallback
is now final. aosp/952720 -
OnBackPressedDispatcher
now has public constructors, allowing you to construct your own instances for testing, etc. aosp/953431 -
onBackPressed()
forComponentActivity
is now explicitly marked as@MainThread
aosp/952721
Исправления ошибок
- Fixed a
ConcurrentModificationException
when callingremove()
from within thehandleOnBackPressed()
method of aOnBackPressedCalback
that 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
OnBackPressedCallback
andOnBackPressedDispatcher
have been marked as@MainThread
. ( aosp/943813 ) - The
handleOnBackPressed()
method no longer returns aboolean
. Instead,OnBackPressedCallback
is 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
addCallback
methods ofOnBackPressedDispatcher
no longer return aCancellable
instance.OnBackPressedCallback
now contain aremove()
method that fulfill this functionality, allowing you to callremove()
duringhandleOnBackPressed()
. ( aosp/944519 ) ( aosp/946316 ) -
activity-ktx
now contains a receiver scoped callback foraddCallback
that accepts a lamdba that implementshandleOnBackPressed()
and has access toisEnabled
andremove()
( 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
OnBackPressedCallback
related APIs on ComponentActivity have been deprecated in favor of the newOnBackPressedDispatcher
, retrievable viagetOnBackPressedDispatcher()
. ( aosp/922523 ) - Methods to add a new
OnBackPressedCallback
to theOnBackPressedDispatcher
now return aCancellable
object, allowing removal of the callback without requiring an explicit reference to theOnBackPressedDispatcher
. ( aosp/922523 ) - Adding a
OnBackPressedCallback
with an associatedLifecycleOwner
now results in adding and removing theOnBackPressedCallback
as the Lifecycle is started and stopped, respectively. ( aosp/922523 )
Версия 1.0.0-альфа05
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 .
New features
-
@ContentView
annotation lookups are now cached ( b/123709449 )
Версия 1.0.0-альфа04
January 30, 2019
androidx.activity:activity 1.0.0-alpha04
and androidx.activity:activity-ktx 1.0.0-alpha04
are released.
New features
- Added support for the
@ContentView
class 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
activity
module now depends on version 2.1.0-alpha02 of ViewModel to match theactivity-ktx
module's dependency.
Version 1.0.0-alpha03
December 17, 2018
androidx.activity 1.0.0-alpha03
is released.
New features
- ComponentActivity now implements
BundleSavedStateRegistryOwner
and depends on the newly released SavedState library [ aosp/815133 ] - ComponentActivity now works around an Android framework bug that would cause InputMethodManager to leak the last focused view [ b/37122102 ]
Версия 1.0.0-альфа02
December 3, 2018
API changes
- Added a note that
getLifecycle()
should not be overridden and will be madefinal
in a future release. Please file a feature request if you are currently overriding this method. ( aosp/815834 )
Версия 1.0.0-альфа01
November 5, 2018
androidx.activity 1.0.0-alpha01
introduces ComponentActivity
, a new base class of the existing FragmentActivity
and AppCompatActivity
.
New features
- You can now register an
OnBackPressedCallback
viaaddOnBackPressedCallback
to receiveonBackPressed()
callbacks without needing to override the method in your activity. - Added a new
by viewModels()
Kotlin property delegate for retrievingViewModel
s from aComponentActivity
. - Pending input events (such as clicks) are now canceled in
onStop()
.
API changes
- The implementation of
LifecycleOwner
andViewModelStoreOwner
have been moved fromFragmentActivity
toComponentActivity
. -
onRetainCustomNonConfigurationInstance
has been deprecated. Use aViewModel
for storing objects that need to survive configuration changes.
Активность
Последнее обновление | Стабильный выпуск | Кандидат на выпуск | Бета-версия | Альфа-релиз |
---|---|---|---|---|
9 апреля 2025 г. | 1.10.1 | - | 1.11.0-beta01 | - |
Объявление зависимостей
To add a dependency on Activity, you must add the Google Maven repository to your project. Для получения дополнительной информации прочтите репозиторий Google Maven .
Добавьте зависимости для нужных вам артефактов в файл build.gradle
для вашего приложения или модуля:
классный
dependencies { def activity_version = "1.10.1" // Java language implementation implementation "androidx.activity:activity:$activity_version" // Kotlin implementation "androidx.activity:activity-ktx:$activity_version" }
Котлин
dependencies { val activity_version = "1.10.1" // Java language implementation implementation("androidx.activity:activity:$activity_version") // Kotlin implementation("androidx.activity:activity-ktx:$activity_version") }
Дополнительные сведения о зависимостях см. в разделе Добавление зависимостей сборки .
Обратная связь
Ваши отзывы помогают сделать Jetpack лучше. Дайте нам знать, если вы обнаружите новые проблемы или у вас есть идеи по улучшению этой библиотеки. Пожалуйста, ознакомьтесь с существующими проблемами в этой библиотеке, прежде чем создавать новую. Вы можете добавить свой голос к существующей проблеме, нажав кнопку со звездочкой.
Дополнительную информацию см. в документации по системе отслеживания проблем .
Version 1.11
Version 1.11.0-beta01
9 апреля 2025 г.
androidx.activity:activity:1.11.0-beta01
, androidx.activity:activity-compose:1.11.0-beta01
, and androidx.activity:activity-ktx:1.11.0-beta01
are released. Version 1.11.0-beta01 contains these commits .
Version 1.11.0-alpha02
26 марта 2025 г.
androidx.activity:activity:1.11.0-alpha02
, androidx.activity:activity-compose:1.11.0-alpha02
, and androidx.activity:activity-ktx:1.11.0-alpha02
are released. Version 1.11.0-alpha02 contains these commits .
Изменения API
- Integrated the new
EDGE_NONE
andframeTimeMillis
from Android 16 Beta03 into theBackEventCompat
provided byOnBackPressedCallback
'shandleOnBackStarted
andhandleOnBackProgressed
functions.
Обновления зависимости
- Activity is now compiled with API 36. ( I510e8 , b/301910674 )
Version 1.11.0-alpha01
12 марта 2025 г.
androidx.activity:activity:1.11.0-alpha01
, androidx.activity:activity-compose:1.11.0-alpha01
, and androidx.activity:activity-ktx:1.11.0-alpha01
are released. Version 1.11.0-alpha01 contains these commits .
Новые возможности
- Added
MediaCapabilities
API toPickVisualMediaRequest
to let applications specify its media capabilities, such as supported HDR Types. ( Ic3ee7 )
Version 1.10
Version 1.10.1
26 февраля 2025 г.
androidx.activity:activity:1.10.1
, androidx.activity:activity-compose:1.10.1
, and androidx.activity:activity-ktx:1.10.1
are released. Version 1.10.1 contains these commits .
Исправления ошибок
-
ViewTree
OnBackPressedDispatcherOwners
andFullyDrawnReporterOwners
can now be resolved through disjoint parents of a view, such as aViewOverlay
. See the release notes of core or the documentation inViewTree.setViewTreeDisjointParent
for more information on disjoint view parents. ( Ie7750 )
Version 1.10.0
15 января 2025 г.
androidx.activity:activity:1.10.0
, androidx.activity:activity-compose:1.10.0
, and androidx.activity:activity-ktx:1.10.0
are released. Version 1.10.0 contains these commits .
Important changes since 1.9.0
-
PhotoPicker
now allows picking images in order and choosing which tab (either albums or images) should be initially visible. - The
PickVisualMedia
andPickMultipleVisualMedia
Activity Result contracts that trigger the Photo Picker no longer directly delegates to Google Play services if the system Photo picker is not available, but uses the publicACTION_SYSTEM_FALLBACK_PICK_IMAGES
action and related extras to provide a consistent Photo Picker experience to OEMs and system apps as a fallback. - New
LocalActivity
composition local that provides theActivity
for the current scope, removing the need for developers to get anActivity
from theLocalContext
.
Version 1.10.0-rc01
11 декабря 2024 г.
androidx.activity:activity:1.10.0-rc01
, androidx.activity:activity-compose:1.10.0-rc01
, and androidx.activity:activity-ktx:1.10.0-rc01
are released. Version 1.10.0-rc01 contains these commits .
Исправления ошибок
- Fixed an issue where changing the enabled state while the
PredictiveBackHandler
is currently active would short circuit the callback immediately. It will now finish the current callback regardless of the enabled status changes. ( Ib8719 )
Version 1.10.0-beta01
13 ноября 2024 г.
androidx.activity:activity:1.10.0-beta01
, androidx.activity:activity-compose:1.10.0-beta01
, and androidx.activity:activity-ktx:1.10.0-beta01
are released with no changes since the last alpha. Version 1.10.0-beta01 contains these commits .
Version 1.10.0-alpha03
30 октября 2024 г.
androidx.activity:activity:1.10.0-alpha03
, androidx.activity:activity-compose:1.10.0-alpha03
, and androidx.activity:activity-ktx:1.10.0-alpha03
are released. Version 1.10.0-alpha03 contains these commits .
Изменения API
- Added a new
LocalActivity
composition local that provides theActivity
for the current scope, removing the need for developers to get anActivity
from theLocalContext
. It also comes with a new lint rule that checks when theLocalContext
is incorrectly being cast to anActivity
. ( I7746a , b/283009666 )
Исправления ошибок
- From Activity
1.9.3
:PredictiveBackHandler
will no longer fire it's callback after the handler has been disabled. This will fix an issue where theNavHost
from Navigation Compose would throw anIndexOutOfBoundsException
. ( I3f75e , b/365027664 , b/340202286 )
Dependency Update
- Activity Compose now depends on Compose Runtime 1.7.0 ( I7746a , b/283009666 )
Version 1.10.0-alpha02
4 сентября 2024 г.
androidx.activity:activity:1.10.0-alpha02
, androidx.activity:activity-compose:1.10.0-alpha02
, and androidx.activity:activity-ktx:1.10.0-alpha02
are released. Version 1.10.0-alpha02 contains these commits .
Behavior Changes
- The
PickVisualMedia
andPickMultipleVisualMedia
Activity Result contracts that trigger the Photo Picker no longer directly delegates to Google Play services if the system Photo picker is not available, but uses the publicACTION_SYSTEM_FALLBACK_PICK_IMAGES
action and related extras to provide a consistent Photo Picker experience to OEMs and system apps as a fallback. This should have no effect on the user experience for devices that have a recent version of Google Play services. ( I3513d )
Исправления ошибок
- Removed manual outlining of access to new platform APIs since this happens automatically via API modeling when using R8 with AGP 7.3 or later (eg R8 version 3.3) and for all builds when using AGP 8.1 or later (eg D8 version 8.1). Clients who are not using AGP are advised to update to D8 version 8.1 or later. See this article for more details. ( I9496c , b/345472586 )
- From Activity
1.9.2
: Fixed an issue where the Activity ComposePredictiveBackHandler
API would continue to handle the system back gesture on the frame it was disabled, which could result in libraries like Navigation Compose to handle back even with an empty back stack, resulting in it throwing anIndexOutOfBoundsException
. ( Ie3301 , b/340202286 ) - From Activity
1.9.1
: Fixed an issue withPredictiveBackHandler
where after doing system back, attempting to doonBackPressed
from theOnBackPressedDispatcher
would fail. ( I5f1f8 )
Version 1.10.0-alpha01
26 июня 2024 г.
androidx.activity:activity:1.10.0-alpha01
, androidx.activity:activity-compose:1.10.0-alpha01
, and androidx.activity:activity-ktx:1.10.0-alpha01
are released. This version is developed in an internal branch.
Новые возможности
- Added support for new
PhotoPicker
features introduced in Android V including being able to pick images in order and choose which tab (either albums or images) should be initially visible.
Version 1.9
Version 1.9.3
16 октября 2024 г.
androidx.activity:activity:1.9.3
, androidx.activity:activity-compose:1.9.3
, and androidx.activity:activity-ktx:1.9.3
are released. Version 1.9.3 contains these commits .
Исправления ошибок
-
PredictiveBackHandler
will no longer fire it's callback after the handler has been disabled. This will fix an issue where theNavHost
from Navigation Compose would throw anIndexOutOfBoundsException
. ( I3f75e , b/340202286 )
Version 1.9.2
4 сентября 2024 г.
androidx.activity:activity:1.9.2
, androidx.activity:activity-compose:1.9.2
, and androidx.activity:activity-ktx:1.9.2
are released. Version 1.9.2 contains these lthcocommits .
Исправления ошибок
- Fixed an issue where the Activity Compose
PredictiveBackHandler
API would continue to handle the system back gesture on the frame it was disabled, which could result in libraries like Navigation Compose to handle back even with an empty back stack, resulting in it throwing anIndexOutOfBoundsException
. ( Ie3301 , b/340202286 )
Version 1.9.1
24 июля 2024 г.
androidx.activity:activity:1.9.1
, androidx.activity:activity-compose:1.9.1
, and androidx.activity:activity-ktx:1.9.1
are released. Version 1.9.1 contains these commits .
Исправления ошибок
- Fixed an issue with
PredictiveBackHandler
where after doing system back, attempting to doonBackPressed
from theOnBackPressedDispatcher
would fail. ( I5f1f8 )
Version 1.9.0
17 апреля 2024 г.
androidx.activity:activity:1.9.0
, androidx.activity:activity-compose:1.9.0
, and androidx.activity:activity-ktx:1.9.0
are released. Version 1.9.0 contains these commits .
Important changes since 1.8.0
-
ComponentActivity
now implementsOnUserLeaveHintProvider
to allow components to callbacks foronUserLeaveHint
events. - The
OnBackPressedCallback
,BackHandler
, andPredictiveBackHandler
APIs now warn when callingonBackPressedDispatcher.onBackPressed()
when handling back as that will always break the Predictive Back Animation . See the best practices guide for more details. - The remainder of the Activity APIs have been rewritten in Kotlin and all extensions previously available in
activity-ktx
have been moved toactivity
.activity-ktx
is now completely empty.- As part of the conversion of
ActivityResultLauncher
to Kotlin, thegetContract
method is now an abstract Kotlin property. This is a binary compatible change, but source breaking if your implementation ofActivityResultLauncher
is written in Kotlin.
- As part of the conversion of
Version 1.9.0-rc01
3 апреля 2024 г.
androidx.activity:activity:1.9.0-rc01
, androidx.activity:activity-compose:1.9.0-rc01
, and androidx.activity:activity-ktx:1.9.0-rc01
are released. Version 1.9.0-rc01 contains these commits .
Dependency update
- Activity now depends on Profile Installer 1.3.1 .
Version 1.9.0-beta01
20 марта 2024 г.
androidx.activity:activity:1.9.0-beta01
, androidx.activity:activity-compose:1.9.0-beta01
, and androidx.activity:activity-ktx:1.9.0-beta01
are released. Version 1.9.0-beta01 contains these commits .
Исправления ошибок
- Fixed an Activity startup performance regression introduced in Activity
1.9.0-alpha02
caused by calling theOnBackPressedDispatcher
as part of the creation of the Activity. ( Ie75e3 )
Version 1.9.0-alpha03
7 февраля 2024 г.
androidx.activity:activity:1.9.0-alpha03
, androidx.activity:activity-compose:1.9.0-alpha03
, and androidx.activity:activity-ktx:1.9.0-alpha03
are released. Version 1.9.0-alpha03 contains these commits.
Lint Warning
- The
OnBackPressedCallback
,BackHandler
, andPredictiveBackHandler
APIs now warn when callingonBackPressedDispatcher.onBackPressed()
when handling back as that will always break the Predictive Back Animation . See the best practices guide for more details. ( 1e4222 , 2c950d , b/287505200 )
Исправления ошибок
- If a back event is sent from the system started during an already running Predictive Back Gesture, the currently running Predictive Back Gesture is canceled and the new back event takes over to begin a new Predictive Back Gesture. ( I3482e )
- Fixed a crash when accessing the
onBackPressedDispatcher
from aComponentActivity
for the first time from a background thread. It is now safe to access theonBackPressedDispatcher
on any thread. ( I79955 )
Version 1.9.0-alpha02
24 января 2024 г.
androidx.activity:activity:1.9.0-alpha02
, androidx.activity:activity-compose:1.9.0-alpha02
, and androidx.activity:activity-ktx:1.9.0-alpha02
are released. Version 1.9.0-alpha02 contains these commits.
Kotlin Conversions
-
ActivityResultRegistry
has been rewritten in Kotlin. This ensures that the nullability of the generics on the contract passed toregister
will correctly be passed through to theActivityResultLauncher
returned to you. ( I121f0 ) -
ActivityResult
has been rewritten in Kotlin. TheActivityResult
Kotlin extensions that support destructuring into theresultCode
anddata
fields have been moved fromactivity-ktx
toactivity
. ( I0565a ) - The Kotlin extensions of
by viewModels()
forComponentActivity
andtrackPipAnimationHintView
have been moved fromactivity-ktx
toactivity
. Theactivity-ktx
artifact is now completely empty. ( I0a444 )
Исправления ошибок
- The
enableEdgeToEdge
API now draws around any display cutouts. ( a3644b , b/311173461 ) - From Activity
1.8.2
: Fixed the extra passed to the Photo Picker Activity Contract'sACTION_SYSTEM_FALLBACK_PICK_IMAGES
to correctly pass it theEXTRA_SYSTEM_FALLBACK_PICK_IMAGES_MAX
key, rather than using the extra with the key"com.google.android.gms.provider.extra.PICK_IMAGES_MAX"
. It is strongly recommended if you are an OEM who implements a system fallback Photo Picker to support both extras to ensure the widest compatibility. ( I96a00 )
Version 1.9.0-alpha01
29 ноября 2023 г.
androidx.activity:activity:1.9.0-alpha01
, androidx.activity:activity-compose:1.9.0-alpha01
, and androidx.activity:activity-ktx:1.9.0-alpha01
are released. Version 1.9.0-alpha01 contains these commits.
Новые возможности
-
ComponentActivity
now implementsOnUserLeaveHintProvider
to allow components to callbacks foronUserLeaveHint
events. ( I54892 )
Изменения API
-
ComponentActivity
has been rewritten in Kotlin. ( I14f31 ) -
ActivityResultCaller
has been rewritten in Kotlin. ( Ib02e4 ) -
ActivityResultLauncher
has been rewritten in Kotlin. As part of that conversion, thegetContract
method is now an abstract Kotlin property. This is a binary compatible change, but source breaking if your implementation ofActivityResultLauncher
is written in Kotlin. ( Id4615 ) -
PickVisualMediaRequest
now has the same minimum API level of 19 as thePickVisualMedia
Activity Result contract. ( Id6e21 )
Dependency Update
- Activity now depends on Core
1.13.0-alpha01
. ( I14f31 )
Версия 1.8
Version 1.8.2
13 декабря 2023 г.
androidx.activity:activity:1.8.2
, androidx.activity:activity-compose:1.8.2
, and androidx.activity:activity-ktx:1.8.2
are released. Version 1.8.2 contains these commits.
Исправления ошибок
- Fixed the extra passed to the Photo Picker Activity Contract's
ACTION_SYSTEM_FALLBACK_PICK_IMAGES
to correctly pass it theEXTRA_SYSTEM_FALLBACK_PICK_IMAGES_MAX
key, rather than using the extra with the key"com.google.android.gms.provider.extra.PICK_IMAGES_MAX"
. It is strongly recommended if you are an OEM who implements a system fallback Photo Picker to support both extras to ensure the widest compatibility. ( I96a00 )
Version 1.8.1
15 ноября 2023 г.
androidx.activity:activity:1.8.1
, androidx.activity:activity-compose:1.8.1
, and androidx.activity:activity-ktx:1.8.1
are released. Version 1.8.1 contains these commits.
Исправления ошибок
-
OnBackPressedDispatcher
now continues to dispatch to the correctOnBackPressedCallback
even after a newOnBackPressedCallback
is added while the back gesture is being handled. ( Id0ff6 )
Version 1.8.0
4 октября 2023 г.
androidx.activity:activity:1.8.0
, androidx.activity:activity-compose:1.8.0
, and androidx.activity:activity-ktx:1.8.0
are released. Version 1.8.0 contains these commits.
Important changes since 1.7.0
- Predictive Back - The
OnBackPressedCallback
now offers new Predictive Back callbacks for handling the back gesture starting, progress throughout the gesture, and the back gesture being canceled in addition to the previoushandleOnBackPressed()
callback for when the back gesture is committed. This also comes with thePredictiveBackHandler
Composable to handle predictive back gesture events in Activity Compose. It provides a Flow of BackEventCompat objects that must be collected in the suspending lamba you provide:
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()
has now been deprecated in favor of the APIs for handling back. Developers should now utilize the OnBackPressedDispatcher
, rather than overriding this method.
- EdgeToEdge -
ComponentActivity.enableEdgeToEdge()
has been added to easily set up the edge-to-edge display in a backward-compatible manner.
Версия 1.8.0-rc01
20 сентября 2023 г.
androidx.activity:activity:1.8.0-rc01
, androidx.activity:activity-compose:1.8.0-rc01
, and androidx.activity:activity-ktx:1.8.0-rc01
are released. Version 1.8.0-rc01 contains these commits.
Версия 1.8.0-бета01
6 сентября 2023 г.
androidx.activity:activity:1.8.0-beta01
, androidx.activity:activity-compose:1.8.0-beta01
, and androidx.activity:activity-ktx:1.8.0-beta01
are released. Version 1.8.0-beta01 contains these commits.
Documentation Improvement
- Improved the documentation of
BackEventCompat
. ( aosp/2722254 )
Версия 1.8.0-альфа07
23 августа 2023 г.
androidx.activity:activity:1.8.0-alpha07
, androidx.activity:activity-compose:1.8.0-alpha07
, and androidx.activity:activity-ktx:1.8.0-alpha07
are released. Version 1.8.0-alpha07 contains these commits.
Новые возможности
Activity Compose has added a new
PredictiveBackHandler
Composable to handle predictive back gesture events. It provides aFlow
ofBackEventCompat
objects that must be collected in the suspending lamba you provide: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 } }
It also comes with a compile time warning via lint rule to ensure the
Flow
callscollect()
. ( Id2773 , b/294884345 )The
onBackPressedDispatcher
inComponentActivity
is now initialized lazily so that it is only created when required. ( I0bf8e )
Исправления ошибок
-
ComponentActivity
will no longer show a NPE on Android 13 when it gets anonBackPressed()
callback and the Activity has already beenDESTROYED
. ( Idb055 , b/291869278 ) - Removed usages of experimental
isAtLeastU()
API ( Ie9117 , b/289269026 )
Версия 1.8.0-альфа06
21 июня 2023 г.
androidx.activity:activity:1.8.0-alpha06
, androidx.activity:activity-compose:1.8.0-alpha06
, and androidx.activity:activity-ktx:1.8.0-alpha06
are released. Version 1.8.0-alpha06 contains these commits.
Новые возможности
- The
OnBackPressedDispatcher
now correctly cancels any callbacks that are removed during a Predictive Back Gesture. ( I3f90f )
Изменения API
- When passing
SystemBarStyle.auto
to theenableEdgeToEdge
API, you can now override thedetectDarkMode
lambda parameter to provide custom logic for detecting night mode. ( 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
, and androidx.activity:activity-ktx:1.8.0-alpha05
are released. This version is developed in an internal branch.
Изменения API
- Activity now provides a
BackEventCompat
class that serves as a backward compatible version ofBackEvent
that is decoupled from the frameworkBackEvent
class. - Breaking change: The
handleOnBackStarted
andhandleOnBackProgressed
methods ofOnBackPressedCallback
now receive anandroidx.activity.BackEventCompat
instance rather than a frameworkandroid.window.BackEvent
class. The equivalent@VisibleForTesting
APIs onOnBackPressedDispatcher
have also been updated. - The constructor for
OnBackPressedDispatcher
now takes an optionalConsumer<Boolean>
instance that allows the owners of the dispatcher to receive a callback whenever the number of enabled callbacks changes from zero to non-zero or vice versa.
Исправления ошибок
- From Activity
1.7.2
: FixReportDrawn
crashing when navigating away from a screen beforereport
is called. ( Ic46f1 , b/260506820 )
Версия 1.8.0-альфа04
10 мая 2023 г.
androidx.activity:activity:1.8.0-alpha04
, androidx.activity:activity-compose:1.8.0-alpha04
, and androidx.activity:activity-ktx:1.8.0-alpha04
are released. This was released from an internal branch.
Исправления ошибок
- From Activity 1.7.1 : - The
ReportFullyDrawExecuter
no longer leaks when usingComponentActivity
withActivityScenario
. ( Id2ff2 , b/277434271 )
Версия 1.8.0-альфа03
April 12, 2023
androidx.activity:activity:1.8.0-alpha03
, androidx.activity:activity-compose:1.8.0-alpha03
, and androidx.activity:activity-ktx:1.8.0-alpha03
are released. This was released from an internal branch.
Новые возможности
- Added
ComponentActivity.setUpEdgeToEdge()
to easily set up the edge-to-edge display in a backward-compatible manner.
Изменения API
-
ComponentActivity.onBackPressed()
has now been deprecated in favor of the APIs for handling back. Developers should now utilize theOnBackPressedDispatcher
, rather than overriding this method. ( Ibce2f , b/271596918 ) -
ComponentDialog
andComponentActivity
now contain public APIinitViewTreeOwners()
to be used to initialize all view tree owners before setting the content view. ( Ibdce0 , b/261314581 )
Исправления ошибок
- Fixed an issue where Fragments were incorrectly invalidating MenuHosts and causing other menus in the Activity to have unexpected behavior. ( I9404e , b/244336571 )
Other Changes
- The
ActivityResultRegister
now uses KotlinRandom
instead of 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
, and androidx.activity:activity-ktx:1.8.0-alpha02
are released. Developed from an internal branch.
Dependency update
- From Activity
1.7.0-rc01
: Activity now depends onLifecycle 2.6.0
.
Версия 1.8.0-альфа01
8 февраля 2023 г.
androidx.activity:activity:1.8.0-alpha01
, androidx.activity:activity-compose:1.8.0-alpha01
, and androidx.activity:activity-ktx:1.8.0-alpha01
are released. This was built from an internal branch.
Новые возможности
- The
OnBackPressedCallback
class now contains new Predictive Back progress callbacks for handling the back gesture starting, progress throughout the gesture, and the back gesture being canceled in addition to the previoushandleOnBackPressed()
callback for when the back gesture is committed.
Версия 1.7
Версия 1.7.2
24 мая 2023 г.
androidx.activity:activity:1.7.2
, androidx.activity:activity-compose:1.7.2
, and androidx.activity:activity-ktx:1.7.2
are released. Version 1.7.2 contains these commits.
Исправления ошибок
- Fix
ReportDrawn
crashing when navigating away from a screen beforereport
is called. ( Ic46f1 , b/260506820 )
Версия 1.7.1
19 апреля 2023 года
androidx.activity:activity:1.7.1
, androidx.activity:activity-compose:1.7.1
, and androidx.activity:activity-ktx:1.7.1
are released. Version 1.7.1 contains these commits.
Исправления ошибок
- The
ReportFullyDrawExecuter
no longer leaks when usingComponentActivity
withActivityScenario
. ( Id2ff2 , b/277434271 )
Версия 1.7.0
22 марта 2023 года
androidx.activity:activity:1.7.0
, androidx.activity:activity-compose:1.7.0
, and androidx.activity:activity-ktx:1.7.0
are released. Version 1.7.0 contains these commits.
Важные изменения с версии 1.6.0
- The Photo Picker activity contracts in
PickVisualMedia
andPickMultipleVisualMedia
have been updated to contain an additional fallback for whenMediaStore.ACTION_PICK_IMAGES
is unavailable that allows OEMs and system apps, such as Google Play services, to provide a consistent Photo Picker experience on a wider range of Android devices and API levels by implementing the fallback action . The Photo Picker will use this fallback if it is available before falling back to usingIntent.ACTION_OPEN_DOCUMENT
, which remains to support all API 19 and higher devices. -
ComponentDialog
now implementsSavedStateRegistryOwner
and has access to its ownSavedStateRegistry
and sets theSavedStateRegistryOwner
for itsViewTree
. It is now possible to use Jetpack Compose within aComponentDialog
as it meets both theLifecycleOwner
andSavedStateRegistryOwner
attached to the Window via theViewTree
APIs requirements. -
IntentSenderRequest.Builder.setFlags()
now allows you to set multiple flags fromIntent
, rather than only a single flag.
Kotlin Conversion
A number of Activity classes have been converted to Kotlin. All converted classes still retain their binary compatibility with previous versions. The following classes have source incompatible changes for classes written in Kotlin: ActivityResultRegistryOwner
, OnBackPressedDispatcherOwner
.
The table below provides the source conversions for the new version of Activity:
Activity 1.5 | Activity 1.6 |
---|---|
override fun getActivityResultRegistry() = activityResultRegistry | override val activityResultRegistry = activityResultRegistry |
override fun getOnBackPressedDispatcher() = onBackPressedDispatcher | override val onBackPressedDispatcher = onBackPressedDispatcher |
These classes were also converted to Kotlin, but remain source compatible: ContextAware
, ContextAwareHelper
, OnContextAvailableListener
, IntentSenderRequest
, and OnBackPressedDispatcher
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.
Three Activity Compose APIs have been added to make it more convenient to use the FullyDrawnReporter
from individual composables:
-
ReportDrawn
indicates that your composable is immediately ready for interaction. -
ReportDrawnWhen
takes a predicate (ie,list.count > 0
) to indicate when your composable is ready for interaction. -
ReportDrawnAfter
takes a suspending method that, when it completes, indicates that you are ready for interaction.
Обновления зависимости
- Activity now depends on Lifecycle
2.6.1
. ( 8fc31d ) - Activity now depends on ProfileInstaller
1.3.0
. ( 83d3b1 )
Версия 1.7.0-rc01
8 марта 2023 года
androidx.activity:activity:1.7.0-rc01
, androidx.activity:activity-compose:1.7.0-rc01
, and androidx.activity:activity-ktx:1.7.0-rc01
are released. Version 1.7.0-rc01 contains these commits.
Dependency update
- Activity now depends on
Lifecycle 2.6.0
.
Версия 1.7.0-бета02
22 февраля 2023 года
androidx.activity:activity:1.7.0-beta02
, androidx.activity:activity-compose:1.7.0-beta02
, and androidx.activity:activity-ktx:1.7.0-beta02
are released. Version 1.7.0-beta02 contains these commits.
Изменения API
- The action and extra used by the
PickVisualMedia
andPickMultipleVisualMedia
contracts as a fallback for whenMediaStore.ACTION_PICK_IMAGES
is unavailable are now public constants that provide API stability to OEMs and system apps that want to provide a consistent Photo Picker experience. The implementation of this fallback is still limited to only system apps. ( Icd320 )
Версия 1.7.0-бета01
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 )
Исправления ошибок
- The fallback for
PickVisualMedia
for when the framework Photo Picker is unavailable now correctly limits the handling to apps installed in the device's system image. ( If8ae6 )
Kotlin Conversions
-
ActivityResultRegistryOwner
is now written in Kotlin. This is a source incompatible change for those classes written in Kotlin - you must now override theactivityResultRegistry
property rather than implementing the previousgetActivityResultRegistry()
function. ( I0b00e ) -
OnBackPressedDispatcherOwner
is now written in Kotlin. This is a source incompatible change for those classes written in Kotlin - you must now override theonBackPressedDispatcher
property rather than implementing the previousgetOnBackPressedDispatcher
function. ( Ia277d ) -
ContextAware
,ContextAwareHelper
,OnContextAvailableListener
,IntentSenderRequest
andOnBackPressedDispatcher
are now written in Kotlin. ( I1a73e , Iada92 , aosp/2410754 , I18ac7 , b/257291701 )
Версия 1.7.0-альфа04
25 января 2023 года
androidx.activity:activity:1.7.0-alpha04
, androidx.activity:activity-compose:1.7.0-alpha04
, and androidx.activity:activity-ktx:1.7.0-alpha04
are released. Version 1.7.0-alpha04 contains these commits.
Новые возможности
- The
PickVisualMedia
andPickMultipleVisualMedia
Activity Result contracts will now use a Google Play services provided Photo Picker where available in cases where the Android system provided Photo Picker (eg,MediaStore.ACTION_PICK_IMAGES
) is not available. 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 )
Версия 1.7.0-альфа03
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. Версия 1.7.0-alpha03 содержит эти коммиты.
Новые возможности
-
ComponentDialog
now implementsSavedStateRegistryOwner
and has access to its ownSavedStateRegistry
and sets theSavedStateRegistryOwner
for its ViewTree. It is now possible to use Jetpack Compose within aComponentDialog
as it meets both theLifecycleOwner
andSavedStateRegistryOwner
attached to the Window via the ViewTree APIs requirements. ( Idca17 , I73468 b/261162296 )
Изменения API
- Added a
ReportDrawn
composable that immediately marks the activity as ready to callreportFullyDrawn
. ( Ic5b14 , b/259687964 )
Kotlin Conversions
- The
ActvitiyResultCallback
andOnBackPressedCallback
classes have both been converted to Kotlin while maintaining source and binary compatibility. ( Ifc5e5 , Ide1b0 , b/257291701 )
Версия 1.7.0-альфа02
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. Версия 1.7.0-alpha02 содержит эти коммиты.
Исправления ошибок
- From Activity
1.6.1
: Fixed an issue with thePickMultipleVisualMedia
Activity Result contract not launching on Android R devices when using the default value formaxItems
. ( Ie2776 , b/249182130 )
Версия 1.7.0-альфа01
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. Версия 1.7.0-alpha01 содержит эти коммиты.
FullyDrawnReporter APIs
ComponentActivity
now provides a FullyDrawnReporter
instance that allows multiple components to report when they are ready for interaction. ComponentActivity
will wait for all components to complete before calling reportFullyDrawn()
on your behalf. These APIs take care of the timing requirements for you and do not need to be called as part of an onDraw
call.
These APIs are encouraged to enable:
- Signaling the Android Runtime when startup completes, to ensure all of the code run during a multi-frame startup sequence is included and prioritized for background compilation.
- Signaling Macrobenchmark and Play Vitals when your application should be considered fully drawn for startup metrics, so you can track performance.
Two Activity Compose APIs have been added to make it more convenient to use the FullyDrawnReporter
from individual composables:
-
ReportDrawnWhen
takes a predicate (ie,list.count > 0
) to indicate when your composable is ready for interaction. -
ReportDrawnAfter
takes a suspending method that, when it completes, indicates that you are ready for interaction.
Версия 1.6.1
Версия 1.6.1
24 октября 2022 года
androidx.activity:activity:1.6.1
, androidx.activity:activity-compose:1.6.1
, and androidx.activity:activity-ktx:1.6.1
are released. Версия 1.6.1 содержит эти коммиты.
Исправления ошибок
- Fixed an issue with the
PickMultipleVisualMedia
Activity Result contract not launching on Android R devices when using the default value formaxItems
. ( Ie2776 , b/249182130 )
Версия 1.6.0
Версия 1.6.0
21 сентября 2022 года
androidx.activity:activity:1.6.0
, androidx.activity:activity-compose:1.6.0
, and androidx.activity:activity-ktx:1.6.0
are released. Версия 1.6.0 содержит эти коммиты.
Важные изменения с версии 1.5.0
- Added
ActivityResultContracts.PickVisualMedia
andActivityResultContracts.PickMultipleVisualMedia
for providing a backward compatible contract that usesMediaStore.ACTION_PICK_IMAGES
when the Photo Picker is available andIntent.ACTION_OPEN_DOCUMENT
when it is not available. - Integrated the
OnBackInvokedCallback
in Android 13 into theOnBackPressedDispatchers
provided byComponentActivity
andComponentDialog
. This ensures that all APIs built onOnBackPressedDispatcher
work when enabling a predictive back gesture .
Version 1.6.0-rc02
7 сентября 2022 г.
androidx.activity:activity:1.6.0-rc02
, androidx.activity:activity-compose:1.6.0-rc02
, and androidx.activity:activity-ktx:1.6.0-rc02
are released. Version 1.6.0-rc02 contains these commits.
Исправления ошибок
-
OnBackPressedDispatcher
now registers theOnBackInvokedCallback
with thePRIORITY_DEFAULT
instead ofPRIORITY_OVERLAY
. ( I3901f ) - Classes that extend
ComponentActivity
will now always have both of theironMultiWindowModeChanged()
callbacks dispatched. ( Ic4d85 ) - The
ActivityResultRegistry
will no longer return a result to theActivityResultCallback
when thelaunch
call throws anyException
and the callback was registered without aLifecycleOwner
. ( Ia7ff7 , b/238350794 ) -
ComponentActivity
will now properly dispatch menu calls without the need to call the super function in your activity. ( Ie33c5 , b/238057118 )
Dependency Update
- The
Activity
library now depends on Lifecycle2.5.1
. ( If6697 )
Версия 1.6.0-rc01
24 августа 2022 года
androidx.activity:activity:1.6.0-rc01
, androidx.activity:activity-compose:1.6.0-rc01
, and androidx.activity:activity-ktx:1.6.0-rc01
are released. Версия 1.6.0-rc01 содержит эти коммиты.
Исправления ошибок
- Initializing an
OnBackPressedDispatcher
will no longer causeClassVerificationError
s when using SDK versions prior to 33. ( Ic32e1 ) - Classes that override
ComponentActivity
'sonPictureInPictureModeChanged()
callback will now always have their callbacks dispatched. ( Ib7fdb )
Версия 1.6.0-бета01
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. Версия 1.6.0-beta01 содержит эти коммиты.
Изменения API
- Marked the deprecated
startActivityForResult
andstartIntentSenderForResult
methods onComponentActivity
with@NonNull
because passingnull
has always resulted in a crash. ( Id2a25 , b/231476082 )
Исправления ошибок
- From Activity
1.5.1
: TheActivityResultRegistry
will no longer return a result to theActivityResultCallback
when thelaunch
call throws anyException
and the callback was registered without aLifecycleOwner
. ( Ia7ff7 , b/238350794 ) - From Activity
1.5.1
:ComponentActivity
will 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
: TheActivity
library now depends on theLifecycle
version2.5.1
. ( If6697 )
Версия 1.6.0-альфа05
15 июня 2022 года
androidx.activity:activity:1.6.0-alpha05
, androidx.activity:activity-compose:1.6.0-alpha05
, and androidx.activity:activity-ktx:1.6.0-alpha05
are released. Version 1.6.0-alpha05 was developed in a private pre-release branch and has no public commits.
Изменения API
-
minCompileSdk
is now 33 to align with Tiramisu Beta 3 SDK
Исправления ошибок
- Fixed crash on older devices when doing SDK extension check for the
PickVisualMedia
ActivityResultContract
so that it should now work withACTION_OPEN_DOCUMENT
on devices running Android 10 and lower.
Версия 1.6.0-альфа04
18 мая 2022 года
androidx.activity:activity:1.6.0-alpha04
and androidx.activity:activity-ktx:1.6.0-alpha04
are released.
Исправления ошибок
- Fixed an error in
PickVisualMediaRequest
where attempting to create a request, either via the Builder or the top level Kotlin function, would result in a stack overflow. - Integrated the
OnBackInvokedCallback
in Android 13 Dev Beta 2 into theOnBackPressedDispatcher
provided byComponentDialog
. This ensures that all APIs built onOnBackPressedDispatcher
work when enabling a predictive back gesture .
Версия 1.6.0-альфа03
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.PickVisualMedia
andActivityResultContracts.PickMultipleVisualMedia
for providing a backward compatible contract that usesMediaStore.ACTION_PICK_IMAGES
when the Photo Picker is available andIntent.ACTION_OPEN_DOCUMENT
when it is not available. - Integrated the
OnBackInvokedCallback
in Android 13 Dev Beta 1 into theOnBackPressedDispatcher
provided byComponentActivity
. This ensures that all APIs built onOnBackPressedDispatcher
work when enabling a predictive back gesture .
Версия 1.6.0-альфа01
23 марта 2022 года
androidx.activity:activity:1.6.0-alpha01
, androidx.activity:activity-compose:1.6.0-alpha01
, and androidx.activity:activity-ktx:1.6.0-alpha01
are released.
- Note: This version will only compile against the Android 13 Developer Preview 2 SDK.
Новые возможности
- Integrated changes in Android 13 Dev Preview 2 into
ComponentActivity
.
Версия 1.5.1
Версия 1.5.1
27 июля 2022 года
androidx.activity:activity:1.5.1
, androidx.activity:activity-compose:1.5.1
, and androidx.activity:activity-ktx:1.5.1
are released. Версия 1.5.1 содержит эти коммиты.
Исправления ошибок
The
ActivityResultRegistry
will no longer return a result to theActivityResultCallback
when thelaunch()
call throws anyException
and the callback was registered without aLifecycleOwner
. ( Ia7ff7 , b/238350794 )ComponentActivity
will now properly dispatch menu calls toonPrepareOptionMenu()
,onCreateOptionsMenu()
andonOptionsItemSelected()
overrides without the need to call the super function. ( Ie33c5 , b/238057118 )
Dependency update
- The
Activity
library now depends on the Lifecycle2.5.1
. ( If6697 )
Версия 1.5.0
Версия 1.5.0
29 июня 2022 года
androidx.activity:activity:1.5.0
, androidx.activity:activity-compose:1.5.0
, and androidx.activity:activity-ktx:1.5.0
are released. Версия 1.5.0 содержит эти коммиты.
Important changes since 1.4.0
- ComponentDialog -
ComponentDialog
is a subclass ofDialog
that includes anOnBackPressedDispatcher
that 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 aComponentActivity
or aComponentDialog
. - Callback Interfaces -
ComponentActivity
now implements a set of modular callback interfaces that can be used instead of theActivity
callbacks. These interfaces include the following:OnNewIntentProvider
,OnConfigurationChangedProvider
,OnTrimMemoryProvider
,OnPictureInPictureModeChangedProvider
,OnMultiWindowModeChangedProvider
- CreationExtras Integration -
ComponentActivity
now has the ability to provide a statelessViewModelProvider.Factory
via Lifecycle2.5.0
'sCreationExtras
.
Другие изменения
- The no parameter constructor for
ActivityResultContracts.CreateDocument
has been deprecated and replaced with a new constructor that takes a concrete mime type (eg, "image/png") as is required byIntent.ACTION_CREATE_DOCUMENT
.
Версия 1.5.0-rc01
11 мая 2022 года
androidx.activity:activity:1.5.0-rc01
, androidx.activity:activity-compose:1.5.0-rc01
, and androidx.activity:activity-ktx:1.5.0-rc01
are released with no changes from 1.5.0-beta01. Версия 1.5.0-rc01 содержит эти коммиты.
Версия 1.5.0-бета01
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. Версия 1.5.0-beta01 содержит эти коммиты.
Dependency updates
- Activity now depends on Lifecycle
2.4.0-beta01
.
Version 1.5.0-alpha05
6 апреля 2022 года
androidx.activity:activity:1.5.0-alpha05
, androidx.activity:activity-compose:1.5.0-alpha05
, and androidx.activity:activity-ktx:1.5.0-alpha05
are released. Version 1.5.0-alpha05 contains these commits.
Исправления ошибок
-
ComponentActivity
'sonPanelClosed()
now calls the superonPanelClosed()
as well, fixing an issue where theonContextMenuClosed
method would not be called. ( Ib6f77 )
Версия 1.5.0-альфа04
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. Версия 1.5.0-alpha04 содержит эти коммиты.
Исправления ошибок
-
SavedStateViewFactory
now supports usingCreationExtras
even when it was initialized with aSavedStateRegistryOwner
. If extras are provided, the initialized arguments are ignored. ( I6c43b , b/224844583 )
Версия 1.5.0-Alpha03
23 февраля 2022 года
androidx.activity:activity:1.5.0-alpha03
, androidx.activity:activity-compose:1.5.0-alpha03
, and androidx.activity:activity-ktx:1.5.0-alpha03
are released. Версия 1.5.0-Alpha03 содержит эти коммиты.
Изменения API
- You can now pass
CreationExtras
to the activityby viewModels()
function ( I6a3e6 , b/217600303 )
Версия 1.5.0-Alpha02
9 февраля 2022 года
androidx.activity:activity:1.5.0-alpha02
, androidx.activity:activity-compose:1.5.0-alpha02
, and androidx.activity:activity-ktx:1.5.0-alpha02
are released. Версия 1.5.0-Alpha02 содержит эти коммиты.
Новые возможности
-
ComponentActivity
now implements theOnPictureInPictureModeChangedProvider
interface to allow any component to receive picture-in-picture mode change events. ( I9f567 ) -
ComponentActivity
now implements theOnMultiWindowModeChangedProvider
interface to allow any component to receive multi-window mode change events. ( I62d91 )
Версия 1.5.0-Alpha01
26 января 2022 года
androidx.activity:activity:1.5.0-alpha01
, androidx.activity:activity-compose:1.5.0-alpha01
, and androidx.activity:activity-ktx:1.5.0-alpha01
are released. Версия 1.5.0-Alpha01 содержит эти коммиты.
Новые возможности
-
ComponentActivity
now integrates with ViewModel CreationExtras, introduced as part of Lifecycle2.5.0-alpha01
. ( Ie7e00 , b/207012584 ) - Added
ComponentDialog
, a subclass ofDialog
that includes anOnBackPressedDispatcher
that 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 aComponentActivity
or aComponentDialog
. ( I8a1bc ) -
ComponentActivity
now implements the newOnNewIntentProvider
interface to allow any component to receive these events. ( If1f8b ) -
ComponentActivity
now implements the newOnConfigurationChangedProvider
interface to allow any component to receive these events. ( If623b ) -
ComponentActivity
now implements the newOnTrimMemoryProvider
interface to allow any component to receive these events. ( Ia9295 )
Изменения API
- The no parameter constructor for
ActivityResultContracts.CreateDocument
has been deprecated and replaced with a new constructor that takes a concrete mime type (eg,"image/png"
) as is required byIntent.ACTION_CREATE_DOCUMENT
. ( I2bec6 ) - The
OnBackPressedDispatcherOwner
associated with a View can now be retrieved via theViewTreeOnBackPressedDispatcherOwner
, rather than relying on casting theContext
. ( I74685 )
Исправления ошибок
- Fixed a crash when accessing a
ViewModel
for the very first time from aregisterForActivityResult()
callback or the callbacks to aLifecycleObserver
added as part ofinit
of aComponentActivity
. ( Ife83f )
Версия 1.4.0
Версия 1.4.0
27 октября 2021 года
androidx.activity:activity:1.4.0
, androidx.activity:activity-compose:1.4.0
, and androidx.activity:activity-ktx:1.4.0
are released. Версия 1.4.0 содержит эти коммиты.
Важные изменения с 1.3.0
- AndroidX
ComponentActivity
now implements theMenuHost
interface. This allows any component to add menu items to theActionBar
by adding aMenuProvider
instance to the activity. EachMenuProvider
can optionally be added with aLifecycle
that will automatically control the visibility of those menu items based on theLifecycle
state and handle the removal of theMenuProvider
when theLifecycle
is destroyed. - The
ActivityResultContract
class has been rewritten in Kotlin to ensure that developers writing custom contracts in Kotlin can define the correct nullability for their input and output classes. - The
ActivityResultContracts
class and its contracts have been rewritten in Kotlin to ensure the proper nullability.
Версия 1.4.0-RC01
13 октября 2021 года
androidx.activity:activity:1.4.0-rc01
, androidx.activity:activity-compose:1.4.0-rc01
, and androidx.activity:activity-ktx:1.4.0-rc01
are released. Версия 1.4.0-RC01 содержит эти коммиты.
Исправления ошибок
- The
ActivityResultRegistry
will no longer return a result to theActivityResultCallback
when thelaunch
call throws anyException
. ( If4f91 , b/200845664 )
Версия 1.4.0-бета01
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. Версия 1.4.0-бета01 содержит эти коммиты.
Изменения API
- Fixed the type for the
ActivityResultContracts.OpenMultipleDocuments
andActivityResultContracts.GetMultipleContents
that 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.RequestMultiplePermissions
classes are now accessible when using Kotlin via their now publicCompanion
objects. ( 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 )
Версия 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. Версия 1.4.0-Alpha02 содержит эти коммиты.
Новые возможности
- The
activity-compose
artifact now contains aLaunchDuringComposition
lint error that prevents you from calling thelaunch
method ofActivityResultLauncher
as part of composition as composition should be side-effect free. Use the APIs for handling side-effects . ( 7c2bbe , b/191347220 )
Изменения API
- The
ActivityResultContract
class has been rewritten in Kotlin to ensure that developers writing custom contracts in Kotlin can define the correct nullability for their input and output classes. ( I8a8f5 ) - The
ActivityResultContracts
class and its contracts have been rewritten in Kotlin to ensure the proper nullability. ( I69802 )
Версия 1.4.0-Alpha01
1 сентября 2021 года
androidx.activity:activity:1.4.0-alpha01
, androidx.activity:activity-compose:1.4.0-alpha01
, and androidx.activity:activity-ktx:1.4.0-alpha01
are released. Версия 1.4.0-Alpha01 содержит эти коммиты.
Новые возможности
- AndroidX
ComponentActivity
now implements theMenuHost
interface.. This allows any component to add menu items to theActionBar
by adding aMenuProvider
instance to the activity. EachMenuProvider
can optionally be added with aLifecycle
that will automatically control the visibility of those menu items based on theLifecycle
state and handle the removal of theMenuProvider
when theLifecycle
is destroyed. ( I3b608 ):
/**
* Using the addMenuProvider() API directly in your Activity
**/
class ExampleActivity : ComponentActivity(R.layout.activity_example) {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Add menu items without overriding methods in the Activity
addMenuProvider(object : MenuProvider {
override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
// Add menu items here
menuInflater.inflate(R.menu.example_menu, menu)
}
override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
// Handle the menu selection
return true
}
})
}
}
/**
* Using the addMenuProvider() API in a Fragment
**/
class ExampleFragment : Fragment(R.layout.fragment_example) {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
// The usage of an interface lets you inject your own implementation
val menuHost: MenuHost = requireActivity()
// Add menu items without using the Fragment Menu APIs
// Note how we can tie the MenuProvider to the viewLifecycleOwner
// and an optional Lifecycle.State (here, RESUMED) to indicate when
// the menu should be visible
menuHost.addMenuProvider(object : MenuProvider {
override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
// Add menu items here
menuInflater.inflate(R.menu.example_menu, menu)
}
override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
// Handle the menu selection
return true
}
}, viewLifecycleOwner, Lifecycle.State.RESUMED)
}
Behavior Changes
- The
ActivityResultRegistry
will now throw anIllegalStateException
when attempting to calllaunch()
on anActivityResultLauncher
that has not be registered or that has been unregistered. ( Ida75d , b/192567522 )
Внешний вклад
Версия 1.3.1
Версия 1.3.1
4 августа 2021 года
androidx.activity:activity:1.3.1
, androidx.activity:activity-compose:1.3.1
, and androidx.activity:activity-ktx:1.3.1
are released. Версия 1.3.1 содержит эти коммиты.
Dependency updates
- Activity now depends on Kotlin
1.5.21
. - Activity Compose now depends on Compose
1.0.1
.
Версия 1.3.0
Версия 1.3.0
28 июля 2021 года
androidx.activity:activity:1.3.0
, androidx.activity:activity-compose:1.3.0
, and androidx.activity:activity-ktx:1.3.0
are released. Версия 1.3.0 содержит эти коммиты.
Важные изменения с 1.2.0
- Activity Compose artifact - The
activity-compose
artifact provides thesetContent
extension method for hosting your Jetpack Compose UI in an activity and Compose specific wrappers for interacting with theComponentActivity
APIs for handling the system back button and the Activity Result APIs. See the documentation for more details. - CaptureVideo contract - The
CaptureVideo
ActivityResultContract
replaces the now deprecatedTakeVideo
contract and returns a boolean denoting success that works across many camera apps. - Picture-In-Picture Hint View Tracking - Users of
activity-ktx
can now use thetrackPipAnimationHintView
extension method onActivity
to automatically rebuild thePictureInPictureParams
with the new position of the view as it changes position relative to the window.
Version 1.3.0-rc02
14 июля 2021 года
androidx.activity:activity:1.3.0-rc02
, androidx.activity:activity-compose:1.3.0-rc02
, and androidx.activity:activity-ktx:1.3.0-rc02
are released. Version 1.3.0-rc02 contains these commits.
Исправления ошибок
- The
ActivityResultRegistry
callbacks are now properly saved and restored so callbacks are not duplicated in the savedState. ( I97816 , b/191893160 )
Версия 1.3.0-RC01
1 июля 2021 года
androidx.activity:activity:1.3.0-rc01
, androidx.activity:activity-compose:1.3.0-rc01
, and androidx.activity:activity-ktx:1.3.0-rc01
are released with no changes from 1.3.0-beta02
. Версия 1.3.0-RC01 содержит эти коммиты.
Версия 1.3.0-бета02
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. Версия 1.3.0-бета02 содержит эти коммиты.
Updated activity-compose
to depend on Compose 1.0.0-beta09
. androidx.compose.ui:ui-test-junit4
now has a compile time dependency on activity-compose
.
Версия 1.3.0-бета01
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. Версия 1.3.0-бета01 содержит эти коммиты.
Изменения API
- 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
CaptureVideo
ActivityResultContract
returns a boolean to yourActivityResultCallback
indicating if your video was successfully saved to the given URI. This replaces the now deprecatedTakeVideo
contract as camera apps very rarely supported returning a thumbnail bitmap, making the result unhelpful. ( Ie21f2 , b/185938070 ) - Added new API
Activity#setPipAnimationHintView
to update the PipParams' source rect hint whenever the view moves. ( I9063d )
Изменения API
- The
rememberLauncherForActivityResult
function now returns a launcher that deprecates theunregister()
function - registration and unregistering the launcher is handled automatically byrememberLauncherForActivityResult
. ( I2443e )
Compose Compatibility
-
androidx.activity:activity-compose:1.3.0-alpha08
is only compatible with Compose version1.0.0-beta07
and 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.
Исправления ошибок
-
rememberLauncherForActivityResult
now returns a stable reference to the sameActivityResultLauncher
instance even if the contract changes due to recompositions. ( Id2d6d ) - Using unstable versions of Fragments above
1.3.0
will no longer throw a false positive lint error telling you to 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
- The
registerForActivityResult()
API has been renamed torememberLauncherForActivityResult()
to better indicate that the returnedActivityResultLauncher
is a managed object that is remembered on your behalf. Attempting to callunregister
the returnedActivityResultLauncher
will now throw an error. ( I2bb6d ) -
LocalOnBackPressedDispatcherOwner.current
andLocalActivityResultRegistryOwner.current
now return a nullable value to better determine whether it is available in the current composition. APIs that requires those APIs, such asBackHandler
andrememberLauncherForActivityResult()
, respectively, will now throw a more descriptive error if the underlying owner is not found.NavHost
now works even when anOnBackPressedDispatcherOwner
is not found, such is the case when previewing theNavHost
. ( I7d8b4 )
Исправления ошибок
- The
BackHandler
will now properly intercept back presses in the event that the Activity isSTOPPED
, thenSTARTED
again, and other callbacks were added with a LifecycleOwner. ( I71de6 , b/182284739 ) - Using the
launch()
method extension with a customActivityResultContract
that has aUnit
input 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.
Исправления ошибок
- From Activity 1.2.2 : Fixed an issue in the
InvalidFragmentVersionForActivityResult
lint check that led to a false positive when using Fragment 1.3.1 or higher. ( I54da1 , b/182388985 ) - From Activity 1.2.2 :
ComponentActivity
now avoids aClassNotFoundException
when launching anIntent
from anActivityResultContract
that was previously held as an extra in anotherIntent
. ( Ieff05 , b/182906230 )
Обновления зависимости
- 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.
Исправления ошибок
- From Activity
1.2.1
:RequestMultiplePermissions
now always returns results for all requested permissions instead of only permissions that weren't previously granted. ( I50bc3 , b/180884668 ) - From Activity
1.2.1
:ActivityResultRegistry
now ensures that in 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
BackHandler
where the previously setonBack
lambda was still being used after recomposition. ( 8eb5eb )
Версия 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. Версия 1.3.0-Alpha03 содержит эти коммиты.
Новые возможности
- There is a now a Composable
registerForActivityResult
function for getting results from activities within composables. ( Ia7851 , b/172690553 )
Изменения API
-
LocalOnBackPressedDispatcherOwner
now has aprovides
functions that can be used withCompositionLocalProvider
, replacing theasProvidableCompositionLocal()
API. ( I45d24 )
Версия 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. Версия 1.3.0-Alpha02 содержит эти коммиты.
Исправления ошибок
- Fixed an issue in Activity Compose
1.3.0-alpha01
that causes aNoSuchMethodError: No static method setContent
exception when using Compose1.0.0-alpha12
. All Compose users should depend on1.3.0-alpha02
and above. ( b/179911234 )
Изменения API
- The
BackHandler
API can be used to allow a Composable to intercept the system back button. ( I58ed5 , b/172154006 )
Версия 1.3.0-Alpha01
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. Версия 1.3.0-Alpha01 содержит эти коммиты.
Новые возможности
- The new
activity-compose
artifact provides Jetpack Compose specific helpers forandroidx.activity
specific APIs.-
ComponentActivity.setContent
has moved fromandroidx.compose.ui.platform.setContent
toandroidx.activity.compose.setContent
. ( Icf416 )
-
Известные проблемы
- Using Activity Compose
1.3.0-alpha01
and libraries that depend on it, such asandroidx.compose.ui:ui-test-junit4:1.0.0-alpha12
, will result in aNoSuchMethodError: No static method setContent
exception. ( 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.
Исправления ошибок
- 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.
Исправления ошибок
- Using the
launch()
method extension with a customActivityResultContract
that has aUnit
input will no longer cause aNullPointerException
( I76282 , b/183837954 ) - Fixed a false positive lint error telling you to use Fragment
1.3.0
when using an snapshot, alpha, beta, or RC build of a newer version of Fragments. ( f4a57e , b/184847092 )
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.
Исправления ошибок
- Fixed an issue in the
InvalidFragmentVersionForActivityResult
lint check that led to a false positive when using Fragment 1.3.1 or higher. ( I54da1 , b/182388985 ) -
ComponentActivity
now avoids aClassNotFoundException
when launching anIntent
from anActivityResultContract
that was previously held as an extra in anotherIntent
. ( Ieff05 , b/182906230 )
Обновления зависимости
- Activity now depends on Lifecycle
2.3.1
.
Версия 1.2.1
Версия 1.2.1
March 10, 2021
androidx.activity:activity:1.2.1
and androidx.activity:activity-ktx:1.2.1
are released. Версия 1.2.1 содержит эти коммиты.
Исправления ошибок
-
RequestMultiplePermissions
now always returns results for all requested permissions instead of only permissions that weren't previously granted. ( I50bc3 , b/180884668 ) -
ActivityResultRegistry
now ensures that in progresslaunch()
requests will return their results even if youunregister()
, thenregister()
again with the same key. ( I9ef34 , b/181267562 )
Версия 1.2.0
Версия 1.2.0
February 10, 2021
androidx.activity:activity:1.2.0
and androidx.activity:activity-ktx:1.2.0
are released. Версия 1.2.0 содержит эти коммиты.
Major changes since 1.1.0
- Activity Result APIs :
ComponentActivity
now provides anActivityResultRegistry
that 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
:ComponentActivity
now implementsContextAware
, allowing you to add one or moreOnContextAvailableListener
instances 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
FragmentActivity
in Fragment 1.3.0 to restore the state of theFragmentManager
. Any listeners added to subclasses ofFragmentActivity
will run after that listener. - This API is used by
AppCompatActivity
in AppCompat 1.3.0-alpha02 or higher. Any listeners added to subclasses ofAppCompatActivity
will run after that listener.
- A suspending Kotlin extension
ViewTree
Support :ComponentActivity
now supports theViewTreeLifecycleOwner.get(View)
,ViewTreeViewModelStoreOwner.get(View)
, andViewTreeSavedStateRegistryOwner
APIs added in Lifecycle2.3.0
and SavedState1.1.0
such that it will return the Activity as theLifecycleOwner
,ViewModelStoreOwner
, andSavedStateRegistryOwner
for any Views directly added to theComponentActivity
.
- reportFullyDrawn() backport - The
Activity
method ofreportFullyDrawn()
has been backported inComponentActivity
to work on all API levels, fixing a crash on API 19 and adding tracing for this method for all API levels.
Версия 1.2.0-RC01
December 16, 2020
androidx.activity:activity:1.2.0-rc01
and androidx.activity:activity-ktx:1.2.0-rc01
are released. Версия 1.2.0-RC01 содержит эти коммиты.
Исправления ошибок
- The
ActivityResultRegistry
now always restores the exact state that was saved. ( Idd56b ) - Add tracing to
ComponentActivity.reportFullyDrawn
( Ic7632 )
Внешний вклад
-
ComponentActivity
now 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 )
Версия 1.2.0-бета02
December 2, 2020
androidx.activity:activity:1.2.0-beta02
and androidx.activity:activity-ktx:1.2.0-beta02
are released. Версия 1.2.0-бета02 содержит эти коммиты.
Исправления ошибок
- Fixed an issue where the Activity Result API would not wait for the Lifecycle to be
STARTED
before delivering results when registered with aLifecycle
. ( I109ea )
Внешний вклад
- Updated the documentation for
launch()
to explicitly call out that it can throw anActivityNotFoundException
. Thanks Michał Zieliński! ( aosp/1493580 )
Версия 1.2.0-бета01
October 1, 2020
androidx.activity:activity:1.2.0-beta01
and androidx.activity:activity-ktx:1.2.0-beta01
are released. Версия 1.2.0-бета01 содержит эти коммиты.
Исправления ошибок
The
ActivityResultRegistry
now 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 )Lifecycle
observers are properly removed when callingunregister()
on anActivityResultLauncher
. ( b/165608393 )
Behavior Changes
- The
ActivityResultRegistry
now throws anIllegalStateException
when attempting to callregister()
with aLifecycleOwner
whoseLifecycle
has already reachedSTARTED
. ( b/165435866 )
Documentation Updated
-
ContextAware
documentation links toLifecycleOwner
to highlightLifecycle
callbacks as the appropriate place for creation and destruction events. ( aosp/1414152 )
Версия 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. Версия 1.2.0-Alpha08 содержит эти коммиты.
Новые возможности
-
ComponentActivity
now implementsContextAware
, allowing you to add one or moreOnContextAvailableListener
instances 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
FragmentActivity
in Fragment 1.3.0-alpha08 to restore the state of theFragmentManager
. Any listeners added to subclasses ofFragmentActivity
will run after that listener. ( I513da ) - This API is used by
AppCompatActivity
in AppCompat 1.3.0-alpha02 . Any listeners added to subclasses ofAppCompatActivity
will run after that listener. ( I513da )
- A suspending Kotlin extension
Исправления ошибок
- Fixed an issue with the
ActivityResultFragmentVersionDetector
Lint check that caused it to break when using Lint 27.1.0 or higher. ( b/162155191 )
Версия 1.2.0-Alpha07
July 22, 2020
androidx.activity:activity:1.2.0-alpha07
and androidx.activity:activity-ktx:1.2.0-alpha07
are released. Версия 1.2.0-Alpha07 содержит эти коммиты.
Новые возможности
- Added a new
InvalidFragmentVersionForActivityResult
lint check that verifies that you are using Fragment1.3.0-alpha07
when using the Activity Result API , avoiding runtime crashes due to “invalid request code” issues and non-functioning permission requests caused by using older versions of Fragments. ( b/152554847 )
Внешний вклад
- Fixed an
ArrayIndexOutOfBoundsException
when parsing the results for theRequestPermission
Activity Result contract. ( I8f9e3 , b/161057605 )
Версия 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. Версия 1.2.0-Alpha06 содержит эти коммиты.
Новые возможности
- You can now destructure the
ActivityResult
class in kotlin to directly access therequestCode
andintent
. ( b/157212935 ) -
ActivityResultLauncher
now allows you to get theActivityResultContract
that was used to register the launcher. ( b/156875743 )
Изменения API
- Breaking change : The
invoke()
method onActivityResultRegistry
has been renamed toonLaunch()
. ( b/157496491 ) - The
OpenMultipleDocuments
contract now returns an empty list instead ofnull
to the registered callback if no result is returned. ( b/157348014 )
Версия 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. Версия 1.2.0-Alpha05 содержит эти коммиты.
Новые возможности
- Added support for
ViewTreeViewModelStoreOwner
from Lifecycle2.3.0-alpha03
, andViewTreeSavedStateRegistryOwner
from SavedState1.1.0-alpha01
when using aView
within aComponentActivity
. ( aosp/1297993 , aosp/1300264 )
Изменения API
- The
TakePicture
contract now returns aboolean
indicating success rather than a thumbnailBitmap
as this was very rarely supported by camera apps when writing the image to the providedUri
. ( b/154302879 ) - The
invoke()
extensions onActivityResultLauncher
have been removed in favor of explicitly usinglaunch()
to better indicate that these are asynchronous operations. Kotlin extensions forlaunch
have been added to theandroidx.activity.result
package forActivityResultLauncher<Void>
andActivityResultLauncher<Unit>
that remove the need to pass innull
orUnit
, respectively, mirroring that behavior from the previouslyinvoke()
extensions. ( aosp/1304674 , aosp/1304675 ) - The
IntentSenderRequest.Builder
methods forsetFlagsMask()
andsetFlagsValues()
has been combined into a singlesetFlags()
method. ( aosp/1302111 )
Исправления ошибок
- When registering an
ActivityResultCallback
with aLifecycleOwner
, fixed an issue where the callback would be triggered before the state reachesSTARTED
. ( aosp/1309744 )
Behavior Changes
- The
ActivityResultRegistry
now generates request codes starting at0xFFFF
rather than at0
, preventing overlap when usingstartActivityForResult()
orrequestPermissions()
in an activity. ( aosp/1302324 )
Версия 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. Версия 1.2.0-Alpha04 содержит эти коммиты.
Новые возможности
- Added a contract that can call startIntentSenderForResult to the ActivityResult APIs. ( b/153007517 )
Изменения API
- The
prepareCall()
method has been renamed toregisterForActivityResult()
, both onComponentActivity
here and in Fragment1.3.0-alpha04
. ( aosp/1278717 ) - The
GetContents
,OpenDocuments
, andRequestPermissions
contracts have been renamed toGetMultipleContents
,OpenMultipleDocuments
, andRequestMultiplePermissions
, respectively. ( aosp/1280161 ) -
ComponentActivity
now implements theActivityResultRegisteryOwner
interface. ( aosp/1290888 ) - - The
startActivityForResult()
/onActivityResult()
andonRequestPermissionsResult()
APIs onComponentActivity
have been deprecated. Please use the Activity Result APIs . ( b/154751887 )
Исправления ошибок
- When using the
GetMultipleContents
andOpenMultipleDocuments
contracts and selecting a single item, it is now correctly returned to your callback. ( b/152941153 )
Версия 1.2.0-Alpha03
April 1, 2020
androidx.activity:activity:1.2.0-alpha03
and androidx.activity:activity-ktx:1.2.0-alpha03
are released. Версия 1.2.0-Alpha03 содержит эти коммиты.
Новые возможности
- Added the
TakeVideo
,PickContact
,GetContent
,GetContents
,OpenDocument
,OpenDocuments
,OpenDocumentTree
, andCreateDocument
contracts 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
- The
TakePicture
contract now takes aUri
input 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 onActivityResultRegistry
has been renamed toregister()
. ( aosp/1267621 ) - The
dispose()
method onActivityResultLauncher
has been renamed tounregister()
and theunregisterResultCallback()
onActivityResultRegistry
has been removed. ( aosp/1267621 ) - The
createIntent()
method ofActivityResultContact
now takes aContext
in addition to the input to make it possible to create explicit Intents. ( aosp/1238800 ) - An
ActivityResultContract
can now overridegetSynchronousResult()
to deliver a result without callingstartActivityForResult
. This is used by theRequestPermission
andRequestPermissions
contracts to correctly deliver a 'granted' status if the requested permissions are already granted. ( b/151110799 ) - The previously available
Dial
contract has been removed as thatIntent
is 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 ofActivityResultRegistry
exceptinvoke()
, and a number of the default contracts that do not support optional extras. ( b/152439361 )
Исправления ошибок
- Fixed a
NullPointerException
inActivityResultRegistry
when attempting to deliver results to a callback that has not yet been re-registered after a configuration change;ActivityResultRegistry
now holds onto these pending results and delivers them when the callback is re-registered. ( b/152137004 )
Версия 1.2.0-Alpha02
March 18, 2020
androidx.activity:activity:1.2.0-alpha02
and androidx.activity:activity-ktx:1.2.0-alpha02
are released. Версия 1.2.0-Alpha02 содержит эти коммиты.
Новые возможности
- ActivityResultRegistry :
ComponentActivity
now provides anActivityResultRegistry
that 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 )
Версия 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. Версия 1.2.0-Alpha01 содержит эти коммиты.
Новые возможности
- Added support for the
ViewTreeLifecycleOwner.get(View)
API added in Lifecycle2.3.0-alpha01
such that it will return the Activity as theLifecycleOwner
for any Views directly added to the Activity. ( aosp/1182955 )
Исправления ошибок
- Fixed a regression introduced in Activity
1.1.0
when running on older versions of the platform whereonBackPressed()
would cause anIllegalStateException
due to a bug in theandroid.app.FragmentManager
. ( b/146290338 )
Версия 1.1.0
Версия 1.1.0
January 22, 2020
androidx.activity:activity:1.1.0
is released. Версия 1.1.0 содержит эти коммиты .
Важные изменения с версии 1.0.0
- Lifecycle ViewModel SavedState Integration :
SavedStateViewModelFactory
is now the default factory used when usingby viewModels()
, theViewModelProvider
constructor, orViewModelProviders.of()
with aComponentActivity
or its subclasses.
Версия 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-rc03
and 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
.
Версия 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
. Версия 1.1.0-rc01 содержит эти коммиты .
Версия 1.1.0-бета01
October 9, 2019
androidx.activity:activity:1.1.0-beta01
and androidx.activity:activity-ktx:1.1.0-beta01
are released. Версия 1.1.0-beta01 содержит эти коммиты .
Dependency changes
- Activity now depends on SavedState 1.0.0 stable.
Версия 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 .
New features
- Activity now depends on Core 1.1.0 stable.
Исправления ошибок
- Activity now depends on Lifecycle
2.2.0-alpha04
.
Версия 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 .
New features
-
SavedStateViewModelFactory
is now the default factory used when usingby viewModels()
, theViewModelProvider
constructor, orViewModelProviders.of()
with aComponentActivity
( b/135716331 )
Версия 1.1.0-альфа01
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 .
New features
-
activity
now depends on Lifecycle2.2.0-alpha02
. ( aosp/1007817 ) -
activity-ktx
added a dependency onlifecycle-runtime-ktx
; you no longer need to explicitly add it to your dependencies when usingactivity-ktx
or libraries that depend onactivity-ktx
(such asfragment-ktx
). ( aosp/987162 )
Версия 1.0.0
Версия 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 :
ComponentActivity
serves as the new base class forFragmentActivity
in Fragment1.1.0
and, by extension,AppCompatActivity
in AppCompat1.1.0
. - activity-ktx : The
activity-ktx
module includes aby viewModels
Kotlin property extension for accessing ViewModels. This module is automatically included when you includefragment-ktx
from Fragment1.1.0
. - OnBackPressedDispatcher : As a composable alternative to overriding
onBackPressed()
, you can now register aOnBackPressedCallback
from anyLifecycleOwner
(such as a fragment) to intercept system back button events. A lambda with receiver versionaddCallback
has 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 anyViewModelStoreOwner
that makes the ownership of the retained objects clear and provides anonCleared()
callback for cleaning up resources when the activity is finally destroyed.
Версия 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 .
Версия 1.0.0-бета01
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
addOnBackPressedCallback
andremoveOnBackPressedCallback
methods onComponentActivity
have been removed. aosp/953857 - The
setEnabled()
andisEnabled()
methods ofOnBackPressedCallback
are now final. b/131416833 - The
remove()
method ofOnBackPressedCallback
is now final. aosp/952720 -
OnBackPressedDispatcher
now has public constructors, allowing you to construct your own instances for testing, etc. aosp/953431 -
onBackPressed()
forComponentActivity
is now explicitly marked as@MainThread
aosp/952721
Исправления ошибок
- Fixed a
ConcurrentModificationException
when callingremove()
from within thehandleOnBackPressed()
method of aOnBackPressedCalback
that 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
OnBackPressedCallback
andOnBackPressedDispatcher
have been marked as@MainThread
. ( aosp/943813 ) - The
handleOnBackPressed()
method no longer returns aboolean
. Instead,OnBackPressedCallback
is 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
addCallback
methods ofOnBackPressedDispatcher
no longer return aCancellable
instance.OnBackPressedCallback
now contain aremove()
method that fulfill this functionality, allowing you to callremove()
duringhandleOnBackPressed()
. ( aosp/944519 ) ( aosp/946316 ) -
activity-ktx
now contains a receiver scoped callback foraddCallback
that accepts a lamdba that implementshandleOnBackPressed()
and has access toisEnabled
andremove()
( 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
OnBackPressedCallback
related APIs on ComponentActivity have been deprecated in favor of the newOnBackPressedDispatcher
, retrievable viagetOnBackPressedDispatcher()
. ( aosp/922523 ) - Methods to add a new
OnBackPressedCallback
to theOnBackPressedDispatcher
now return aCancellable
object, allowing removal of the callback without requiring an explicit reference to theOnBackPressedDispatcher
. ( aosp/922523 ) - Adding a
OnBackPressedCallback
with an associatedLifecycleOwner
now results in adding and removing theOnBackPressedCallback
as the Lifecycle is started and stopped, respectively. ( aosp/922523 )
Версия 1.0.0-альфа05
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 .
New features
-
@ContentView
annotation lookups are now cached ( b/123709449 )
Версия 1.0.0-альфа04
January 30, 2019
androidx.activity:activity 1.0.0-alpha04
and androidx.activity:activity-ktx 1.0.0-alpha04
are released.
New features
- Added support for the
@ContentView
class 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
activity
module now depends on version 2.1.0-alpha02 of ViewModel to match theactivity-ktx
module's dependency.
Version 1.0.0-alpha03
December 17, 2018
androidx.activity 1.0.0-alpha03
is released.
New features
- ComponentActivity now implements
BundleSavedStateRegistryOwner
and depends on the newly released SavedState library [ aosp/815133 ] - ComponentActivity now works around an Android framework bug that would cause InputMethodManager to leak the last focused view [ b/37122102 ]
Версия 1.0.0-альфа02
December 3, 2018
API changes
- Added a note that
getLifecycle()
should not be overridden and will be madefinal
in a future release. Please file a feature request if you are currently overriding this method. ( aosp/815834 )
Версия 1.0.0-альфа01
November 5, 2018
androidx.activity 1.0.0-alpha01
introduces ComponentActivity
, a new base class of the existing FragmentActivity
and AppCompatActivity
.
New features
- You can now register an
OnBackPressedCallback
viaaddOnBackPressedCallback
to receiveonBackPressed()
callbacks without needing to override the method in your activity. - Added a new
by viewModels()
Kotlin property delegate for retrievingViewModel
s from aComponentActivity
. - Pending input events (such as clicks) are now canceled in
onStop()
.
API changes
- The implementation of
LifecycleOwner
andViewModelStoreOwner
have been moved fromFragmentActivity
toComponentActivity
. -
onRetainCustomNonConfigurationInstance
has been deprecated. Use aViewModel
for storing objects that need to survive configuration changes.
Активность
Последнее обновление | Стабильный выпуск | Кандидат на выпуск | Бета-версия | Альфа-релиз |
---|---|---|---|---|
9 апреля 2025 г. | 1.10.1 | - | 1.11.0-beta01 | - |
Объявление зависимостей
To add a dependency on Activity, you must add the Google Maven repository to your project. Для получения дополнительной информации прочтите репозиторий Google Maven .
Добавьте зависимости для нужных вам артефактов в файл build.gradle
для вашего приложения или модуля:
классный
dependencies { def activity_version = "1.10.1" // Java language implementation implementation "androidx.activity:activity:$activity_version" // Kotlin implementation "androidx.activity:activity-ktx:$activity_version" }
Котлин
dependencies { val activity_version = "1.10.1" // Java language implementation implementation("androidx.activity:activity:$activity_version") // Kotlin implementation("androidx.activity:activity-ktx:$activity_version") }
Дополнительные сведения о зависимостях см. в разделе Добавление зависимостей сборки .
Обратная связь
Ваши отзывы помогают сделать Jetpack лучше. Дайте нам знать, если вы обнаружите новые проблемы или у вас есть идеи по улучшению этой библиотеки. Пожалуйста, ознакомьтесь с существующими проблемами в этой библиотеке, прежде чем создавать новую. Вы можете добавить свой голос к существующей проблеме, нажав кнопку со звездочкой.
Дополнительную информацию см. в документации по системе отслеживания проблем .
Version 1.11
Version 1.11.0-beta01
9 апреля 2025 г.
androidx.activity:activity:1.11.0-beta01
, androidx.activity:activity-compose:1.11.0-beta01
, and androidx.activity:activity-ktx:1.11.0-beta01
are released. Version 1.11.0-beta01 contains these commits .
Version 1.11.0-alpha02
26 марта 2025 г.
androidx.activity:activity:1.11.0-alpha02
, androidx.activity:activity-compose:1.11.0-alpha02
, and androidx.activity:activity-ktx:1.11.0-alpha02
are released. Version 1.11.0-alpha02 contains these commits .
Изменения API
- Integrated the new
EDGE_NONE
andframeTimeMillis
from Android 16 Beta03 into theBackEventCompat
provided byOnBackPressedCallback
'shandleOnBackStarted
andhandleOnBackProgressed
functions.
Обновления зависимости
- Activity is now compiled with API 36. ( I510e8 , b/301910674 )
Version 1.11.0-alpha01
12 марта 2025 г.
androidx.activity:activity:1.11.0-alpha01
, androidx.activity:activity-compose:1.11.0-alpha01
, and androidx.activity:activity-ktx:1.11.0-alpha01
are released. Version 1.11.0-alpha01 contains these commits .
Новые возможности
- Added
MediaCapabilities
API toPickVisualMediaRequest
to let applications specify its media capabilities, such as supported HDR Types. ( Ic3ee7 )
Version 1.10
Version 1.10.1
26 февраля 2025 г.
androidx.activity:activity:1.10.1
, androidx.activity:activity-compose:1.10.1
, and androidx.activity:activity-ktx:1.10.1
are released. Version 1.10.1 contains these commits .
Исправления ошибок
-
ViewTree
OnBackPressedDispatcherOwners
andFullyDrawnReporterOwners
can now be resolved through disjoint parents of a view, such as aViewOverlay
. See the release notes of core or the documentation inViewTree.setViewTreeDisjointParent
for more information on disjoint view parents. ( Ie7750 )
Version 1.10.0
15 января 2025 г.
androidx.activity:activity:1.10.0
, androidx.activity:activity-compose:1.10.0
, and androidx.activity:activity-ktx:1.10.0
are released. Version 1.10.0 contains these commits .
Important changes since 1.9.0
-
PhotoPicker
now allows picking images in order and choosing which tab (either albums or images) should be initially visible. - The
PickVisualMedia
andPickMultipleVisualMedia
Activity Result contracts that trigger the Photo Picker no longer directly delegates to Google Play services if the system Photo picker is not available, but uses the publicACTION_SYSTEM_FALLBACK_PICK_IMAGES
action and related extras to provide a consistent Photo Picker experience to OEMs and system apps as a fallback. - New
LocalActivity
composition local that provides theActivity
for the current scope, removing the need for developers to get anActivity
from theLocalContext
.
Version 1.10.0-rc01
11 декабря 2024 г.
androidx.activity:activity:1.10.0-rc01
, androidx.activity:activity-compose:1.10.0-rc01
, and androidx.activity:activity-ktx:1.10.0-rc01
are released. Version 1.10.0-rc01 contains these commits .
Исправления ошибок
- Fixed an issue where changing the enabled state while the
PredictiveBackHandler
is currently active would short circuit the callback immediately. It will now finish the current callback regardless of the enabled status changes. ( Ib8719 )
Version 1.10.0-beta01
13 ноября 2024 г.
androidx.activity:activity:1.10.0-beta01
, androidx.activity:activity-compose:1.10.0-beta01
, and androidx.activity:activity-ktx:1.10.0-beta01
are released with no changes since the last alpha. Version 1.10.0-beta01 contains these commits .
Version 1.10.0-alpha03
30 октября 2024 г.
androidx.activity:activity:1.10.0-alpha03
, androidx.activity:activity-compose:1.10.0-alpha03
, and androidx.activity:activity-ktx:1.10.0-alpha03
are released. Version 1.10.0-alpha03 contains these commits .
Изменения API
- Added a new
LocalActivity
composition local that provides theActivity
for the current scope, removing the need for developers to get anActivity
from theLocalContext
. It also comes with a new lint rule that checks when theLocalContext
is incorrectly being cast to anActivity
. ( I7746a , b/283009666 )
Исправления ошибок
- From Activity
1.9.3
:PredictiveBackHandler
will no longer fire it's callback after the handler has been disabled. This will fix an issue where theNavHost
from Navigation Compose would throw anIndexOutOfBoundsException
. ( I3f75e , b/365027664 , b/340202286 )
Dependency Update
- Activity Compose now depends on Compose Runtime 1.7.0 ( I7746a , b/283009666 )
Version 1.10.0-alpha02
4 сентября 2024 г.
androidx.activity:activity:1.10.0-alpha02
, androidx.activity:activity-compose:1.10.0-alpha02
, and androidx.activity:activity-ktx:1.10.0-alpha02
are released. Version 1.10.0-alpha02 contains these commits .
Behavior Changes
- The
PickVisualMedia
andPickMultipleVisualMedia
Activity Result contracts that trigger the Photo Picker no longer directly delegates to Google Play services if the system Photo picker is not available, but uses the publicACTION_SYSTEM_FALLBACK_PICK_IMAGES
action and related extras to provide a consistent Photo Picker experience to OEMs and system apps as a fallback. This should have no effect on the user experience for devices that have a recent version of Google Play services. ( I3513d )
Исправления ошибок
- Removed manual outlining of access to new platform APIs since this happens automatically via API modeling when using R8 with AGP 7.3 or later (eg R8 version 3.3) and for all builds when using AGP 8.1 or later (eg D8 version 8.1). Clients who are not using AGP are advised to update to D8 version 8.1 or later. See this article for more details. ( I9496c , b/345472586 )
- From Activity
1.9.2
: Fixed an issue where the Activity ComposePredictiveBackHandler
API would continue to handle the system back gesture on the frame it was disabled, which could result in libraries like Navigation Compose to handle back even with an empty back stack, resulting in it throwing anIndexOutOfBoundsException
. ( Ie3301 , b/340202286 ) - From Activity
1.9.1
: Fixed an issue withPredictiveBackHandler
where after doing system back, attempting to doonBackPressed
from theOnBackPressedDispatcher
would fail. ( I5f1f8 )
Version 1.10.0-alpha01
26 июня 2024 г.
androidx.activity:activity:1.10.0-alpha01
, androidx.activity:activity-compose:1.10.0-alpha01
, and androidx.activity:activity-ktx:1.10.0-alpha01
are released. This version is developed in an internal branch.
Новые возможности
- Added support for new
PhotoPicker
features introduced in Android V including being able to pick images in order and choose which tab (either albums or images) should be initially visible.
Version 1.9
Version 1.9.3
16 октября 2024 г.
androidx.activity:activity:1.9.3
, androidx.activity:activity-compose:1.9.3
, and androidx.activity:activity-ktx:1.9.3
are released. Version 1.9.3 contains these commits .
Исправления ошибок
-
PredictiveBackHandler
will no longer fire it's callback after the handler has been disabled. This will fix an issue where theNavHost
from Navigation Compose would throw anIndexOutOfBoundsException
. ( I3f75e , b/340202286 )
Version 1.9.2
4 сентября 2024 г.
androidx.activity:activity:1.9.2
, androidx.activity:activity-compose:1.9.2
, and androidx.activity:activity-ktx:1.9.2
are released. Version 1.9.2 contains these lthcocommits .
Исправления ошибок
- Fixed an issue where the Activity Compose
PredictiveBackHandler
API would continue to handle the system back gesture on the frame it was disabled, which could result in libraries like Navigation Compose to handle back even with an empty back stack, resulting in it throwing anIndexOutOfBoundsException
. ( Ie3301 , b/340202286 )
Version 1.9.1
24 июля 2024 г.
androidx.activity:activity:1.9.1
, androidx.activity:activity-compose:1.9.1
, and androidx.activity:activity-ktx:1.9.1
are released. Version 1.9.1 contains these commits .
Исправления ошибок
- Fixed an issue with
PredictiveBackHandler
where after doing system back, attempting to doonBackPressed
from theOnBackPressedDispatcher
would fail. ( I5f1f8 )
Version 1.9.0
17 апреля 2024 г.
androidx.activity:activity:1.9.0
, androidx.activity:activity-compose:1.9.0
, and androidx.activity:activity-ktx:1.9.0
are released. Version 1.9.0 contains these commits .
Important changes since 1.8.0
-
ComponentActivity
now implementsOnUserLeaveHintProvider
to allow components to callbacks foronUserLeaveHint
events. - The
OnBackPressedCallback
,BackHandler
, andPredictiveBackHandler
APIs now warn when callingonBackPressedDispatcher.onBackPressed()
when handling back as that will always break the Predictive Back Animation . See the best practices guide for more details. - The remainder of the Activity APIs have been rewritten in Kotlin and all extensions previously available in
activity-ktx
have been moved toactivity
.activity-ktx
is now completely empty.- As part of the conversion of
ActivityResultLauncher
to Kotlin, thegetContract
method is now an abstract Kotlin property. This is a binary compatible change, but source breaking if your implementation ofActivityResultLauncher
is written in Kotlin.
- As part of the conversion of
Version 1.9.0-rc01
3 апреля 2024 г.
androidx.activity:activity:1.9.0-rc01
, androidx.activity:activity-compose:1.9.0-rc01
, and androidx.activity:activity-ktx:1.9.0-rc01
are released. Version 1.9.0-rc01 contains these commits .
Dependency update
- Activity now depends on Profile Installer 1.3.1 .
Version 1.9.0-beta01
20 марта 2024 г.
androidx.activity:activity:1.9.0-beta01
, androidx.activity:activity-compose:1.9.0-beta01
, and androidx.activity:activity-ktx:1.9.0-beta01
are released. Version 1.9.0-beta01 contains these commits .
Исправления ошибок
- Fixed an Activity startup performance regression introduced in Activity
1.9.0-alpha02
caused by calling theOnBackPressedDispatcher
as part of the creation of the Activity. ( Ie75e3 )
Version 1.9.0-alpha03
7 февраля 2024 г.
androidx.activity:activity:1.9.0-alpha03
, androidx.activity:activity-compose:1.9.0-alpha03
, and androidx.activity:activity-ktx:1.9.0-alpha03
are released. Version 1.9.0-alpha03 contains these commits.
Lint Warning
- The
OnBackPressedCallback
,BackHandler
, andPredictiveBackHandler
APIs now warn when callingonBackPressedDispatcher.onBackPressed()
when handling back as that will always break the Predictive Back Animation . See the best practices guide for more details. ( 1e4222 , 2c950d , b/287505200 )
Исправления ошибок
- If a back event is sent from the system started during an already running Predictive Back Gesture, the currently running Predictive Back Gesture is canceled and the new back event takes over to begin a new Predictive Back Gesture. ( I3482e )
- Fixed a crash when accessing the
onBackPressedDispatcher
from aComponentActivity
for the first time from a background thread. It is now safe to access theonBackPressedDispatcher
on any thread. ( I79955 )
Version 1.9.0-alpha02
24 января 2024 г.
androidx.activity:activity:1.9.0-alpha02
, androidx.activity:activity-compose:1.9.0-alpha02
, and androidx.activity:activity-ktx:1.9.0-alpha02
are released. Version 1.9.0-alpha02 contains these commits.
Kotlin Conversions
-
ActivityResultRegistry
has been rewritten in Kotlin. This ensures that the nullability of the generics on the contract passed toregister
will correctly be passed through to theActivityResultLauncher
returned to you. ( I121f0 ) -
ActivityResult
has been rewritten in Kotlin. TheActivityResult
Kotlin extensions that support destructuring into theresultCode
anddata
fields have been moved fromactivity-ktx
toactivity
. ( I0565a ) - The Kotlin extensions of
by viewModels()
forComponentActivity
andtrackPipAnimationHintView
have been moved fromactivity-ktx
toactivity
. Theactivity-ktx
artifact is now completely empty. ( I0a444 )
Исправления ошибок
- The
enableEdgeToEdge
API now draws around any display cutouts. ( a3644b , b/311173461 ) - From Activity
1.8.2
: Fixed the extra passed to the Photo Picker Activity Contract'sACTION_SYSTEM_FALLBACK_PICK_IMAGES
to correctly pass it theEXTRA_SYSTEM_FALLBACK_PICK_IMAGES_MAX
key, rather than using the extra with the key"com.google.android.gms.provider.extra.PICK_IMAGES_MAX"
. It is strongly recommended if you are an OEM who implements a system fallback Photo Picker to support both extras to ensure the widest compatibility. ( I96a00 )
Version 1.9.0-alpha01
29 ноября 2023 г.
androidx.activity:activity:1.9.0-alpha01
, androidx.activity:activity-compose:1.9.0-alpha01
, and androidx.activity:activity-ktx:1.9.0-alpha01
are released. Version 1.9.0-alpha01 contains these commits.
Новые возможности
-
ComponentActivity
now implementsOnUserLeaveHintProvider
to allow components to callbacks foronUserLeaveHint
events. ( I54892 )
Изменения API
-
ComponentActivity
has been rewritten in Kotlin. ( I14f31 ) -
ActivityResultCaller
has been rewritten in Kotlin. ( Ib02e4 ) -
ActivityResultLauncher
has been rewritten in Kotlin. As part of that conversion, thegetContract
method is now an abstract Kotlin property. This is a binary compatible change, but source breaking if your implementation ofActivityResultLauncher
is written in Kotlin. ( Id4615 ) -
PickVisualMediaRequest
now has the same minimum API level of 19 as thePickVisualMedia
Activity Result contract. ( Id6e21 )
Dependency Update
- Activity now depends on Core
1.13.0-alpha01
. ( I14f31 )
Версия 1.8
Version 1.8.2
13 декабря 2023 г.
androidx.activity:activity:1.8.2
, androidx.activity:activity-compose:1.8.2
, and androidx.activity:activity-ktx:1.8.2
are released. Version 1.8.2 contains these commits.
Исправления ошибок
- Fixed the extra passed to the Photo Picker Activity Contract's
ACTION_SYSTEM_FALLBACK_PICK_IMAGES
to correctly pass it theEXTRA_SYSTEM_FALLBACK_PICK_IMAGES_MAX
key, rather than using the extra with the key"com.google.android.gms.provider.extra.PICK_IMAGES_MAX"
. It is strongly recommended if you are an OEM who implements a system fallback Photo Picker to support both extras to ensure the widest compatibility. ( I96a00 )
Version 1.8.1
15 ноября 2023 г.
androidx.activity:activity:1.8.1
, androidx.activity:activity-compose:1.8.1
, and androidx.activity:activity-ktx:1.8.1
are released. Version 1.8.1 contains these commits.
Исправления ошибок
-
OnBackPressedDispatcher
now continues to dispatch to the correctOnBackPressedCallback
even after a newOnBackPressedCallback
is added while the back gesture is being handled. ( Id0ff6 )
Version 1.8.0
4 октября 2023 г.
androidx.activity:activity:1.8.0
, androidx.activity:activity-compose:1.8.0
, and androidx.activity:activity-ktx:1.8.0
are released. Version 1.8.0 contains these commits.
Important changes since 1.7.0
- Predictive Back - The
OnBackPressedCallback
now offers new Predictive Back callbacks for handling the back gesture starting, progress throughout the gesture, and the back gesture being canceled in addition to the previoushandleOnBackPressed()
callback for when the back gesture is committed. This also comes with thePredictiveBackHandler
Composable to handle predictive back gesture events in Activity Compose. It provides a Flow of BackEventCompat objects that must be collected in the suspending lamba you provide:
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()
has now been deprecated in favor of the APIs for handling back. Developers should now utilize the OnBackPressedDispatcher
, rather than overriding this method.
- EdgeToEdge -
ComponentActivity.enableEdgeToEdge()
has been added to easily set up the edge-to-edge display in a backward-compatible manner.
Версия 1.8.0-rc01
20 сентября 2023 г.
androidx.activity:activity:1.8.0-rc01
, androidx.activity:activity-compose:1.8.0-rc01
, and androidx.activity:activity-ktx:1.8.0-rc01
are released. Version 1.8.0-rc01 contains these commits.
Версия 1.8.0-бета01
6 сентября 2023 г.
androidx.activity:activity:1.8.0-beta01
, androidx.activity:activity-compose:1.8.0-beta01
, and androidx.activity:activity-ktx:1.8.0-beta01
are released. Version 1.8.0-beta01 contains these commits.
Documentation Improvement
- Improved the documentation of
BackEventCompat
. ( aosp/2722254 )
Версия 1.8.0-альфа07
23 августа 2023 г.
androidx.activity:activity:1.8.0-alpha07
, androidx.activity:activity-compose:1.8.0-alpha07
, and androidx.activity:activity-ktx:1.8.0-alpha07
are released. Version 1.8.0-alpha07 contains these commits.
Новые возможности
Activity Compose has added a new
PredictiveBackHandler
Composable to handle predictive back gesture events. It provides aFlow
ofBackEventCompat
objects that must be collected in the suspending lamba you provide: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 } }
It also comes with a compile time warning via lint rule to ensure the
Flow
callscollect()
. ( Id2773 , b/294884345 )The
onBackPressedDispatcher
inComponentActivity
is now initialized lazily so that it is only created when required. ( I0bf8e )
Исправления ошибок
-
ComponentActivity
will no longer show a NPE on Android 13 when it gets anonBackPressed()
callback and the Activity has already beenDESTROYED
. ( Idb055 , b/291869278 ) - Removed usages of experimental
isAtLeastU()
API ( Ie9117 , b/289269026 )
Версия 1.8.0-альфа06
21 июня 2023 г.
androidx.activity:activity:1.8.0-alpha06
, androidx.activity:activity-compose:1.8.0-alpha06
, and androidx.activity:activity-ktx:1.8.0-alpha06
are released. Version 1.8.0-alpha06 contains these commits.
Новые возможности
- The
OnBackPressedDispatcher
now correctly cancels any callbacks that are removed during a Predictive Back Gesture. ( I3f90f )
Изменения API
- When passing
SystemBarStyle.auto
to theenableEdgeToEdge
API, you can now override thedetectDarkMode
lambda parameter to provide custom logic for detecting night mode. ( 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
, and androidx.activity:activity-ktx:1.8.0-alpha05
are released. This version is developed in an internal branch.
Изменения API
- Activity now provides a
BackEventCompat
class that serves as a backward compatible version ofBackEvent
that is decoupled from the frameworkBackEvent
class. - Breaking change: The
handleOnBackStarted
andhandleOnBackProgressed
methods ofOnBackPressedCallback
now receive anandroidx.activity.BackEventCompat
instance rather than a frameworkandroid.window.BackEvent
class. The equivalent@VisibleForTesting
APIs onOnBackPressedDispatcher
have also been updated. - The constructor for
OnBackPressedDispatcher
now takes an optionalConsumer<Boolean>
instance that allows the owners of the dispatcher to receive a callback whenever the number of enabled callbacks changes from zero to non-zero or vice versa.
Исправления ошибок
- From Activity
1.7.2
: FixReportDrawn
crashing when navigating away from a screen beforereport
is called. ( Ic46f1 , b/260506820 )
Версия 1.8.0-альфа04
10 мая 2023 г.
androidx.activity:activity:1.8.0-alpha04
, androidx.activity:activity-compose:1.8.0-alpha04
, and androidx.activity:activity-ktx:1.8.0-alpha04
are released. This was released from an internal branch.
Исправления ошибок
- From Activity 1.7.1 : - The
ReportFullyDrawExecuter
no longer leaks when usingComponentActivity
withActivityScenario
. ( Id2ff2 , b/277434271 )
Версия 1.8.0-альфа03
April 12, 2023
androidx.activity:activity:1.8.0-alpha03
, androidx.activity:activity-compose:1.8.0-alpha03
, and androidx.activity:activity-ktx:1.8.0-alpha03
are released. This was released from an internal branch.
Новые возможности
- Added
ComponentActivity.setUpEdgeToEdge()
to easily set up the edge-to-edge display in a backward-compatible manner.
Изменения API
-
ComponentActivity.onBackPressed()
has now been deprecated in favor of the APIs for handling back. Developers should now utilize theOnBackPressedDispatcher
, rather than overriding this method. ( Ibce2f , b/271596918 ) -
ComponentDialog
andComponentActivity
now contain public APIinitViewTreeOwners()
to be used to initialize all view tree owners before setting the content view. ( Ibdce0 , b/261314581 )
Исправления ошибок
- Fixed an issue where Fragments were incorrectly invalidating MenuHosts and causing other menus in the Activity to have unexpected behavior. ( I9404e , b/244336571 )
Other Changes
- The
ActivityResultRegister
now uses KotlinRandom
instead of 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
, and androidx.activity:activity-ktx:1.8.0-alpha02
are released. Developed from an internal branch.
Dependency update
- From Activity
1.7.0-rc01
: Activity now depends onLifecycle 2.6.0
.
Версия 1.8.0-альфа01
8 февраля 2023 г.
androidx.activity:activity:1.8.0-alpha01
, androidx.activity:activity-compose:1.8.0-alpha01
, and androidx.activity:activity-ktx:1.8.0-alpha01
are released. This was built from an internal branch.
Новые возможности
- The
OnBackPressedCallback
class now contains new Predictive Back progress callbacks for handling the back gesture starting, progress throughout the gesture, and the back gesture being canceled in addition to the previoushandleOnBackPressed()
callback for when the back gesture is committed.
Версия 1.7
Версия 1.7.2
24 мая 2023 г.
androidx.activity:activity:1.7.2
, androidx.activity:activity-compose:1.7.2
, and androidx.activity:activity-ktx:1.7.2
are released. Version 1.7.2 contains these commits.
Исправления ошибок
- Fix
ReportDrawn
crashing when navigating away from a screen beforereport
is called. ( Ic46f1 , b/260506820 )
Версия 1.7.1
19 апреля 2023 года
androidx.activity:activity:1.7.1
, androidx.activity:activity-compose:1.7.1
, and androidx.activity:activity-ktx:1.7.1
are released. Version 1.7.1 contains these commits.
Исправления ошибок
- The
ReportFullyDrawExecuter
no longer leaks when usingComponentActivity
withActivityScenario
. ( Id2ff2 , b/277434271 )
Версия 1.7.0
22 марта 2023 года
androidx.activity:activity:1.7.0
, androidx.activity:activity-compose:1.7.0
, and androidx.activity:activity-ktx:1.7.0
are released. Version 1.7.0 contains these commits.
Важные изменения с версии 1.6.0
- The Photo Picker activity contracts in
PickVisualMedia
andPickMultipleVisualMedia
have been updated to contain an additional fallback for whenMediaStore.ACTION_PICK_IMAGES
is unavailable that allows OEMs and system apps, such as Google Play services, to provide a consistent Photo Picker experience on a wider range of Android devices and API levels by implementing the fallback action . The Photo Picker will use this fallback if it is available before falling back to usingIntent.ACTION_OPEN_DOCUMENT
, which remains to support all API 19 and higher devices. -
ComponentDialog
now implementsSavedStateRegistryOwner
and has access to its ownSavedStateRegistry
and sets theSavedStateRegistryOwner
for itsViewTree
. It is now possible to use Jetpack Compose within aComponentDialog
as it meets both theLifecycleOwner
andSavedStateRegistryOwner
attached to the Window via theViewTree
APIs requirements. -
IntentSenderRequest.Builder.setFlags()
now allows you to set multiple flags fromIntent
, rather than only a single flag.
Kotlin Conversion
A number of Activity classes have been converted to Kotlin. All converted classes still retain their binary compatibility with previous versions. The following classes have source incompatible changes for classes written in Kotlin: ActivityResultRegistryOwner
, OnBackPressedDispatcherOwner
.
The table below provides the source conversions for the new version of Activity:
Activity 1.5 | Activity 1.6 |
---|---|
override fun getActivityResultRegistry() = activityResultRegistry | override val activityResultRegistry = activityResultRegistry |
override fun getOnBackPressedDispatcher() = onBackPressedDispatcher | override val onBackPressedDispatcher = onBackPressedDispatcher |
These classes were also converted to Kotlin, but remain source compatible: ContextAware
, ContextAwareHelper
, OnContextAvailableListener
, IntentSenderRequest
, and OnBackPressedDispatcher
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.
Three Activity Compose APIs have been added to make it more convenient to use the FullyDrawnReporter
from individual composables:
-
ReportDrawn
indicates that your composable is immediately ready for interaction. -
ReportDrawnWhen
takes a predicate (ie,list.count > 0
) to indicate when your composable is ready for interaction. -
ReportDrawnAfter
takes a suspending method that, when it completes, indicates that you are ready for interaction.
Обновления зависимости
- Activity now depends on Lifecycle
2.6.1
. ( 8fc31d ) - Activity now depends on ProfileInstaller
1.3.0
. ( 83d3b1 )
Версия 1.7.0-rc01
8 марта 2023 года
androidx.activity:activity:1.7.0-rc01
, androidx.activity:activity-compose:1.7.0-rc01
, and androidx.activity:activity-ktx:1.7.0-rc01
are released. Version 1.7.0-rc01 contains these commits.
Dependency update
- Activity now depends on
Lifecycle 2.6.0
.
Версия 1.7.0-бета02
22 февраля 2023 года
androidx.activity:activity:1.7.0-beta02
, androidx.activity:activity-compose:1.7.0-beta02
, and androidx.activity:activity-ktx:1.7.0-beta02
are released. Version 1.7.0-beta02 contains these commits.
Изменения API
- The action and extra used by the
PickVisualMedia
andPickMultipleVisualMedia
contracts as a fallback for whenMediaStore.ACTION_PICK_IMAGES
is unavailable are now public constants that provide API stability to OEMs and system apps that want to provide a consistent Photo Picker experience. The implementation of this fallback is still limited to only system apps. ( Icd320 )
Версия 1.7.0-бета01
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 )
Исправления ошибок
- The fallback for
PickVisualMedia
for when the framework Photo Picker is unavailable now correctly limits the handling to apps installed in the device's system image. ( If8ae6 )
Kotlin Conversions
-
ActivityResultRegistryOwner
is now written in Kotlin. This is a source incompatible change for those classes written in Kotlin - you must now override theactivityResultRegistry
property rather than implementing the previousgetActivityResultRegistry()
function. ( I0b00e ) -
OnBackPressedDispatcherOwner
is now written in Kotlin. This is a source incompatible change for those classes written in Kotlin - you must now override theonBackPressedDispatcher
property rather than implementing the previousgetOnBackPressedDispatcher
function. ( Ia277d ) -
ContextAware
,ContextAwareHelper
,OnContextAvailableListener
,IntentSenderRequest
andOnBackPressedDispatcher
are now written in Kotlin. ( I1a73e , Iada92 , aosp/2410754 , I18ac7 , b/257291701 )
Версия 1.7.0-альфа04
25 января 2023 года
androidx.activity:activity:1.7.0-alpha04
, androidx.activity:activity-compose:1.7.0-alpha04
, and androidx.activity:activity-ktx:1.7.0-alpha04
are released. Version 1.7.0-alpha04 contains these commits.
Новые возможности
- The
PickVisualMedia
andPickMultipleVisualMedia
Activity Result contracts will now use a Google Play services provided Photo Picker where available in cases where the Android system provided Photo Picker (eg,MediaStore.ACTION_PICK_IMAGES
) is not available. 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 )
Версия 1.7.0-альфа03
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. Версия 1.7.0-alpha03 содержит эти коммиты.
Новые возможности
-
ComponentDialog
now implementsSavedStateRegistryOwner
and has access to its ownSavedStateRegistry
and sets theSavedStateRegistryOwner
for its ViewTree. It is now possible to use Jetpack Compose within aComponentDialog
as it meets both theLifecycleOwner
andSavedStateRegistryOwner
attached to the Window via the ViewTree APIs requirements. ( Idca17 , I73468 b/261162296 )
Изменения API
- Added a
ReportDrawn
composable that immediately marks the activity as ready to callreportFullyDrawn
. ( Ic5b14 , b/259687964 )
Kotlin Conversions
- The
ActvitiyResultCallback
andOnBackPressedCallback
classes have both been converted to Kotlin while maintaining source and binary compatibility. ( Ifc5e5 , Ide1b0 , b/257291701 )
Версия 1.7.0-альфа02
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. Версия 1.7.0-alpha02 содержит эти коммиты.
Исправления ошибок
- From Activity
1.6.1
: Fixed an issue with thePickMultipleVisualMedia
Activity Result contract not launching on Android R devices when using the default value formaxItems
. ( Ie2776 , b/249182130 )
Версия 1.7.0-альфа01
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. Версия 1.7.0-alpha01 содержит эти коммиты.
FullyDrawnReporter APIs
ComponentActivity
now provides a FullyDrawnReporter
instance that allows multiple components to report when they are ready for interaction. ComponentActivity
will wait for all components to complete before calling reportFullyDrawn()
on your behalf. These APIs take care of the timing requirements for you and do not need to be called as part of an onDraw
call.
These APIs are encouraged to enable:
- Signaling the Android Runtime when startup completes, to ensure all of the code run during a multi-frame startup sequence is included and prioritized for background compilation.
- Signaling Macrobenchmark and Play Vitals when your application should be considered fully drawn for startup metrics, so you can track performance.
Two Activity Compose APIs have been added to make it more convenient to use the FullyDrawnReporter
from individual composables:
-
ReportDrawnWhen
takes a predicate (ie,list.count > 0
) to indicate when your composable is ready for interaction. -
ReportDrawnAfter
takes a suspending method that, when it completes, indicates that you are ready for interaction.
Версия 1.6.1
Версия 1.6.1
24 октября 2022 года
androidx.activity:activity:1.6.1
, androidx.activity:activity-compose:1.6.1
, and androidx.activity:activity-ktx:1.6.1
are released. Версия 1.6.1 содержит эти коммиты.
Исправления ошибок
- Fixed an issue with the
PickMultipleVisualMedia
Activity Result contract not launching on Android R devices when using the default value formaxItems
. ( Ie2776 , b/249182130 )
Версия 1.6.0
Версия 1.6.0
21 сентября 2022 года
androidx.activity:activity:1.6.0
, androidx.activity:activity-compose:1.6.0
, and androidx.activity:activity-ktx:1.6.0
are released. Версия 1.6.0 содержит эти коммиты.
Важные изменения с версии 1.5.0
- Added
ActivityResultContracts.PickVisualMedia
andActivityResultContracts.PickMultipleVisualMedia
for providing a backward compatible contract that usesMediaStore.ACTION_PICK_IMAGES
when the Photo Picker is available andIntent.ACTION_OPEN_DOCUMENT
when it is not available. - Integrated the
OnBackInvokedCallback
in Android 13 into theOnBackPressedDispatchers
provided byComponentActivity
andComponentDialog
. This ensures that all APIs built onOnBackPressedDispatcher
work when enabling a predictive back gesture .
Version 1.6.0-rc02
7 сентября 2022 г.
androidx.activity:activity:1.6.0-rc02
, androidx.activity:activity-compose:1.6.0-rc02
, and androidx.activity:activity-ktx:1.6.0-rc02
are released. Version 1.6.0-rc02 contains these commits.
Исправления ошибок
-
OnBackPressedDispatcher
now registers theOnBackInvokedCallback
with thePRIORITY_DEFAULT
instead ofPRIORITY_OVERLAY
. ( I3901f ) - Classes that extend
ComponentActivity
will now always have both of theironMultiWindowModeChanged()
callbacks dispatched. ( Ic4d85 ) - The
ActivityResultRegistry
will no longer return a result to theActivityResultCallback
when thelaunch
call throws anyException
and the callback was registered without aLifecycleOwner
. ( Ia7ff7 , b/238350794 ) -
ComponentActivity
will now properly dispatch menu calls without the need to call the super function in your activity. ( Ie33c5 , b/238057118 )
Dependency Update
- The
Activity
library now depends on Lifecycle2.5.1
. ( If6697 )
Версия 1.6.0-rc01
24 августа 2022 года
androidx.activity:activity:1.6.0-rc01
, androidx.activity:activity-compose:1.6.0-rc01
, and androidx.activity:activity-ktx:1.6.0-rc01
are released. Версия 1.6.0-rc01 содержит эти коммиты.
Исправления ошибок
- Initializing an
OnBackPressedDispatcher
will no longer causeClassVerificationError
s when using SDK versions prior to 33. ( Ic32e1 ) - Classes that override
ComponentActivity
'sonPictureInPictureModeChanged()
callback will now always have their callbacks dispatched. ( Ib7fdb )
Версия 1.6.0-бета01
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. Версия 1.6.0-beta01 содержит эти коммиты.
Изменения API
- Marked the deprecated
startActivityForResult
andstartIntentSenderForResult
methods onComponentActivity
with@NonNull
because passingnull
has always resulted in a crash. ( Id2a25 , b/231476082 )
Исправления ошибок
- From Activity
1.5.1
: TheActivityResultRegistry
will no longer return a result to theActivityResultCallback
when thelaunch
call throws anyException
and the callback was registered without aLifecycleOwner
. ( Ia7ff7 , b/238350794 ) - From Activity
1.5.1
:ComponentActivity
will 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
: TheActivity
library now depends on theLifecycle
version2.5.1
. ( If6697 )
Версия 1.6.0-альфа05
15 июня 2022 года
androidx.activity:activity:1.6.0-alpha05
, androidx.activity:activity-compose:1.6.0-alpha05
, and androidx.activity:activity-ktx:1.6.0-alpha05
are released. Version 1.6.0-alpha05 was developed in a private pre-release branch and has no public commits.
Изменения API
-
minCompileSdk
is now 33 to align with Tiramisu Beta 3 SDK
Исправления ошибок
- Fixed crash on older devices when doing SDK extension check for the
PickVisualMedia
ActivityResultContract
so that it should now work withACTION_OPEN_DOCUMENT
on devices running Android 10 and lower.
Версия 1.6.0-альфа04
18 мая 2022 года
androidx.activity:activity:1.6.0-alpha04
and androidx.activity:activity-ktx:1.6.0-alpha04
are released.
Исправления ошибок
- Fixed an error in
PickVisualMediaRequest
where attempting to create a request, either via the Builder or the top level Kotlin function, would result in a stack overflow. - Integrated the
OnBackInvokedCallback
in Android 13 Dev Beta 2 into theOnBackPressedDispatcher
provided byComponentDialog
. This ensures that all APIs built onOnBackPressedDispatcher
work when enabling a predictive back gesture .
Версия 1.6.0-альфа03
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.PickVisualMedia
andActivityResultContracts.PickMultipleVisualMedia
for providing a backward compatible contract that usesMediaStore.ACTION_PICK_IMAGES
when the Photo Picker is available andIntent.ACTION_OPEN_DOCUMENT
when it is not available. - Integrated the
OnBackInvokedCallback
in Android 13 Dev Beta 1 into theOnBackPressedDispatcher
provided byComponentActivity
. This ensures that all APIs built onOnBackPressedDispatcher
work when enabling a predictive back gesture .
Версия 1.6.0-альфа01
23 марта 2022 года
androidx.activity:activity:1.6.0-alpha01
, androidx.activity:activity-compose:1.6.0-alpha01
, and androidx.activity:activity-ktx:1.6.0-alpha01
are released.
- Note: This version will only compile against the Android 13 Developer Preview 2 SDK.
Новые возможности
- Integrated changes in Android 13 Dev Preview 2 into
ComponentActivity
.
Версия 1.5.1
Версия 1.5.1
27 июля 2022 года
androidx.activity:activity:1.5.1
, androidx.activity:activity-compose:1.5.1
, and androidx.activity:activity-ktx:1.5.1
are released. Версия 1.5.1 содержит эти коммиты.
Исправления ошибок
The
ActivityResultRegistry
will no longer return a result to theActivityResultCallback
when thelaunch()
call throws anyException
and the callback was registered without aLifecycleOwner
. ( Ia7ff7 , b/238350794 )ComponentActivity
will now properly dispatch menu calls toonPrepareOptionMenu()
,onCreateOptionsMenu()
andonOptionsItemSelected()
overrides without the need to call the super function. ( Ie33c5 , b/238057118 )
Dependency update
- The
Activity
library now depends on the Lifecycle2.5.1
. ( If6697 )
Версия 1.5.0
Версия 1.5.0
29 июня 2022 года
androidx.activity:activity:1.5.0
, androidx.activity:activity-compose:1.5.0
, and androidx.activity:activity-ktx:1.5.0
are released. Версия 1.5.0 содержит эти коммиты.
Important changes since 1.4.0
- ComponentDialog -
ComponentDialog
is a subclass ofDialog
that includes anOnBackPressedDispatcher
that 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 aComponentActivity
or aComponentDialog
. - Callback Interfaces -
ComponentActivity
now implements a set of modular callback interfaces that can be used instead of theActivity
callbacks. These interfaces include the following:OnNewIntentProvider
,OnConfigurationChangedProvider
,OnTrimMemoryProvider
,OnPictureInPictureModeChangedProvider
,OnMultiWindowModeChangedProvider
- CreationExtras Integration -
ComponentActivity
now has the ability to provide a statelessViewModelProvider.Factory
via Lifecycle2.5.0
'sCreationExtras
.
Другие изменения
- The no parameter constructor for
ActivityResultContracts.CreateDocument
has been deprecated and replaced with a new constructor that takes a concrete mime type (eg, "image/png") as is required byIntent.ACTION_CREATE_DOCUMENT
.
Версия 1.5.0-rc01
11 мая 2022 года
androidx.activity:activity:1.5.0-rc01
, androidx.activity:activity-compose:1.5.0-rc01
, and androidx.activity:activity-ktx:1.5.0-rc01
are released with no changes from 1.5.0-beta01. Версия 1.5.0-rc01 содержит эти коммиты.
Версия 1.5.0-бета01
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. Версия 1.5.0-beta01 содержит эти коммиты.
Dependency updates
- Activity now depends on Lifecycle
2.4.0-beta01
.
Version 1.5.0-alpha05
6 апреля 2022 года
androidx.activity:activity:1.5.0-alpha05
, androidx.activity:activity-compose:1.5.0-alpha05
, and androidx.activity:activity-ktx:1.5.0-alpha05
are released. Version 1.5.0-alpha05 contains these commits.
Исправления ошибок
-
ComponentActivity
'sonPanelClosed()
now calls the superonPanelClosed()
as well, fixing an issue where theonContextMenuClosed
method would not be called. ( Ib6f77 )
Версия 1.5.0-альфа04
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. Версия 1.5.0-alpha04 содержит эти коммиты.
Исправления ошибок
-
SavedStateViewFactory
now supports usingCreationExtras
even when it was initialized with aSavedStateRegistryOwner
. If extras are provided, the initialized arguments are ignored. ( I6c43b , b/224844583 )
Версия 1.5.0-Alpha03
23 февраля 2022 года
androidx.activity:activity:1.5.0-alpha03
, androidx.activity:activity-compose:1.5.0-alpha03
, and androidx.activity:activity-ktx:1.5.0-alpha03
are released. Версия 1.5.0-Alpha03 содержит эти коммиты.
Изменения API
- You can now pass
CreationExtras
to the activityby viewModels()
function ( I6a3e6 , b/217600303 )
Версия 1.5.0-Alpha02
9 февраля 2022 года
androidx.activity:activity:1.5.0-alpha02
, androidx.activity:activity-compose:1.5.0-alpha02
, and androidx.activity:activity-ktx:1.5.0-alpha02
are released. Версия 1.5.0-Alpha02 содержит эти коммиты.
Новые возможности
-
ComponentActivity
now implements theOnPictureInPictureModeChangedProvider
interface to allow any component to receive picture-in-picture mode change events. ( I9f567 ) -
ComponentActivity
now implements theOnMultiWindowModeChangedProvider
interface to allow any component to receive multi-window mode change events. ( I62d91 )
Версия 1.5.0-Alpha01
26 января 2022 года
androidx.activity:activity:1.5.0-alpha01
, androidx.activity:activity-compose:1.5.0-alpha01
, and androidx.activity:activity-ktx:1.5.0-alpha01
are released. Версия 1.5.0-Alpha01 содержит эти коммиты.
Новые возможности
-
ComponentActivity
now integrates with ViewModel CreationExtras, introduced as part of Lifecycle2.5.0-alpha01
. ( Ie7e00 , b/207012584 ) - Added
ComponentDialog
, a subclass ofDialog
that includes anOnBackPressedDispatcher
that 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 aComponentActivity
or aComponentDialog
. ( I8a1bc ) -
ComponentActivity
now implements the newOnNewIntentProvider
interface to allow any component to receive these events. ( If1f8b ) -
ComponentActivity
now implements the newOnConfigurationChangedProvider
interface to allow any component to receive these events. ( If623b ) -
ComponentActivity
now implements the newOnTrimMemoryProvider
interface to allow any component to receive these events. ( Ia9295 )
Изменения API
- The no parameter constructor for
ActivityResultContracts.CreateDocument
has been deprecated and replaced with a new constructor that takes a concrete mime type (eg,"image/png"
) as is required byIntent.ACTION_CREATE_DOCUMENT
. ( I2bec6 ) - The
OnBackPressedDispatcherOwner
associated with a View can now be retrieved via theViewTreeOnBackPressedDispatcherOwner
, rather than relying on casting theContext
. ( I74685 )
Исправления ошибок
- Fixed a crash when accessing a
ViewModel
for the very first time from aregisterForActivityResult()
callback or the callbacks to aLifecycleObserver
added as part ofinit
of aComponentActivity
. ( Ife83f )
Версия 1.4.0
Версия 1.4.0
27 октября 2021 года
androidx.activity:activity:1.4.0
, androidx.activity:activity-compose:1.4.0
, and androidx.activity:activity-ktx:1.4.0
are released. Версия 1.4.0 содержит эти коммиты.
Важные изменения с 1.3.0
- AndroidX
ComponentActivity
now implements theMenuHost
interface. This allows any component to add menu items to theActionBar
by adding aMenuProvider
instance to the activity. EachMenuProvider
can optionally be added with aLifecycle
that will automatically control the visibility of those menu items based on theLifecycle
state and handle the removal of theMenuProvider
when theLifecycle
is destroyed. - The
ActivityResultContract
class has been rewritten in Kotlin to ensure that developers writing custom contracts in Kotlin can define the correct nullability for their input and output classes. - The
ActivityResultContracts
class and its contracts have been rewritten in Kotlin to ensure the proper nullability.
Версия 1.4.0-RC01
13 октября 2021 года
androidx.activity:activity:1.4.0-rc01
, androidx.activity:activity-compose:1.4.0-rc01
, and androidx.activity:activity-ktx:1.4.0-rc01
are released. Версия 1.4.0-RC01 содержит эти коммиты.
Исправления ошибок
- The
ActivityResultRegistry
will no longer return a result to theActivityResultCallback
when thelaunch
call throws anyException
. ( If4f91 , b/200845664 )
Версия 1.4.0-бета01
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. Версия 1.4.0-бета01 содержит эти коммиты.
Изменения API
- Fixed the type for the
ActivityResultContracts.OpenMultipleDocuments
andActivityResultContracts.GetMultipleContents
that 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.RequestMultiplePermissions
classes are now accessible when using Kotlin via their now publicCompanion
objects. ( 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 )
Версия 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. Версия 1.4.0-Alpha02 содержит эти коммиты.
Новые возможности
- The
activity-compose
artifact now contains aLaunchDuringComposition
lint error that prevents you from calling thelaunch
method ofActivityResultLauncher
as part of composition as composition should be side-effect free. Use the APIs for handling side-effects . ( 7c2bbe , b/191347220 )
Изменения API
- The
ActivityResultContract
class has been rewritten in Kotlin to ensure that developers writing custom contracts in Kotlin can define the correct nullability for their input and output classes. ( I8a8f5 ) - The
ActivityResultContracts
class and its contracts have been rewritten in Kotlin to ensure the proper nullability. ( I69802 )
Версия 1.4.0-Alpha01
1 сентября 2021 года
androidx.activity:activity:1.4.0-alpha01
, androidx.activity:activity-compose:1.4.0-alpha01
, and androidx.activity:activity-ktx:1.4.0-alpha01
are released. Версия 1.4.0-Alpha01 содержит эти коммиты.
Новые возможности
- AndroidX
ComponentActivity
now implements theMenuHost
interface.. This allows any component to add menu items to theActionBar
by adding aMenuProvider
instance to the activity. EachMenuProvider
can optionally be added with aLifecycle
that will automatically control the visibility of those menu items based on theLifecycle
state and handle the removal of theMenuProvider
when theLifecycle
is destroyed. ( I3b608 ):
/**
* Using the addMenuProvider() API directly in your Activity
**/
class ExampleActivity : ComponentActivity(R.layout.activity_example) {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Add menu items without overriding methods in the Activity
addMenuProvider(object : MenuProvider {
override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
// Add menu items here
menuInflater.inflate(R.menu.example_menu, menu)
}
override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
// Handle the menu selection
return true
}
})
}
}
/**
* Using the addMenuProvider() API in a Fragment
**/
class ExampleFragment : Fragment(R.layout.fragment_example) {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
// The usage of an interface lets you inject your own implementation
val menuHost: MenuHost = requireActivity()
// Add menu items without using the Fragment Menu APIs
// Note how we can tie the MenuProvider to the viewLifecycleOwner
// and an optional Lifecycle.State (here, RESUMED) to indicate when
// the menu should be visible
menuHost.addMenuProvider(object : MenuProvider {
override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
// Add menu items here
menuInflater.inflate(R.menu.example_menu, menu)
}
override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
// Handle the menu selection
return true
}
}, viewLifecycleOwner, Lifecycle.State.RESUMED)
}
Behavior Changes
- The
ActivityResultRegistry
will now throw anIllegalStateException
when attempting to calllaunch()
on anActivityResultLauncher
that has not be registered or that has been unregistered. ( Ida75d , b/192567522 )
Внешний вклад
Версия 1.3.1
Версия 1.3.1
4 августа 2021 года
androidx.activity:activity:1.3.1
, androidx.activity:activity-compose:1.3.1
, and androidx.activity:activity-ktx:1.3.1
are released. Версия 1.3.1 содержит эти коммиты.
Dependency updates
- Activity now depends on Kotlin
1.5.21
. - Activity Compose now depends on Compose
1.0.1
.
Версия 1.3.0
Версия 1.3.0
28 июля 2021 года
androidx.activity:activity:1.3.0
, androidx.activity:activity-compose:1.3.0
, and androidx.activity:activity-ktx:1.3.0
are released. Версия 1.3.0 содержит эти коммиты.
Важные изменения с 1.2.0
- Activity Compose artifact - The
activity-compose
artifact provides thesetContent
extension method for hosting your Jetpack Compose UI in an activity and Compose specific wrappers for interacting with theComponentActivity
APIs for handling the system back button and the Activity Result APIs. See the documentation for more details. - CaptureVideo contract - The
CaptureVideo
ActivityResultContract
replaces the now deprecatedTakeVideo
contract and returns a boolean denoting success that works across many camera apps. - Picture-In-Picture Hint View Tracking - Users of
activity-ktx
can now use thetrackPipAnimationHintView
extension method onActivity
to automatically rebuild thePictureInPictureParams
with the new position of the view as it changes position relative to the window.
Version 1.3.0-rc02
14 июля 2021 года
androidx.activity:activity:1.3.0-rc02
, androidx.activity:activity-compose:1.3.0-rc02
, and androidx.activity:activity-ktx:1.3.0-rc02
are released. Version 1.3.0-rc02 contains these commits.
Исправления ошибок
- The
ActivityResultRegistry
callbacks are now properly saved and restored so callbacks are not duplicated in the savedState. ( I97816 , b/191893160 )
Версия 1.3.0-RC01
1 июля 2021 года
androidx.activity:activity:1.3.0-rc01
, androidx.activity:activity-compose:1.3.0-rc01
, and androidx.activity:activity-ktx:1.3.0-rc01
are released with no changes from 1.3.0-beta02
. Версия 1.3.0-RC01 содержит эти коммиты.
Версия 1.3.0-бета02
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. Версия 1.3.0-бета02 содержит эти коммиты.
Updated activity-compose
to depend on Compose 1.0.0-beta09
. androidx.compose.ui:ui-test-junit4
now has a compile time dependency on activity-compose
.
Версия 1.3.0-бета01
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. Версия 1.3.0-бета01 содержит эти коммиты.
Изменения API
- 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
CaptureVideo
ActivityResultContract
returns a boolean to yourActivityResultCallback
indicating if your video was successfully saved to the given URI. This replaces the now deprecatedTakeVideo
contract as camera apps very rarely supported returning a thumbnail bitmap, making the result unhelpful. ( Ie21f2 , b/185938070 ) - Added new API
Activity#setPipAnimationHintView
to update the PipParams' source rect hint whenever the view moves. ( I9063d )
Изменения API
- The
rememberLauncherForActivityResult
function now returns a launcher that deprecates theunregister()
function - registration and unregistering the launcher is handled automatically byrememberLauncherForActivityResult
. ( I2443e )
Compose Compatibility
-
androidx.activity:activity-compose:1.3.0-alpha08
is only compatible with Compose version1.0.0-beta07
and 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.
Исправления ошибок
-
rememberLauncherForActivityResult
now returns a stable reference to the sameActivityResultLauncher
instance even if the contract changes due to recompositions. ( Id2d6d ) - Using unstable versions of Fragments above
1.3.0
will no longer throw a false positive lint error telling you to 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
- The
registerForActivityResult()
API has been renamed torememberLauncherForActivityResult()
to better indicate that the returnedActivityResultLauncher
is a managed object that is remembered on your behalf. Attempting to callunregister
the returnedActivityResultLauncher
will now throw an error. ( I2bb6d ) -
LocalOnBackPressedDispatcherOwner.current
andLocalActivityResultRegistryOwner.current
now return a nullable value to better determine whether it is available in the current composition. APIs that requires those APIs, such asBackHandler
andrememberLauncherForActivityResult()
, respectively, will now throw a more descriptive error if the underlying owner is not found.NavHost
now works even when anOnBackPressedDispatcherOwner
is not found, such is the case when previewing theNavHost
. ( I7d8b4 )
Исправления ошибок
- The
BackHandler
will now properly intercept back presses in the event that the Activity isSTOPPED
, thenSTARTED
again, and other callbacks were added with a LifecycleOwner. ( I71de6 , b/182284739 ) - Using the
launch()
method extension with a customActivityResultContract
that has aUnit
input 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.
Исправления ошибок
- From Activity 1.2.2 : Fixed an issue in the
InvalidFragmentVersionForActivityResult
lint check that led to a false positive when using Fragment 1.3.1 or higher. ( I54da1 , b/182388985 ) - From Activity 1.2.2 :
ComponentActivity
now avoids aClassNotFoundException
when launching anIntent
from anActivityResultContract
that was previously held as an extra in anotherIntent
. ( Ieff05 , b/182906230 )
Обновления зависимости
- 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.
Исправления ошибок
- From Activity
1.2.1
:RequestMultiplePermissions
now always returns results for all requested permissions instead of only permissions that weren't previously granted. ( I50bc3 , b/180884668 ) - From Activity
1.2.1
:ActivityResultRegistry
now ensures that in 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
BackHandler
where the previously setonBack
lambda was still being used after recomposition. ( 8eb5eb )
Версия 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. Версия 1.3.0-Alpha03 содержит эти коммиты.
Новые возможности
- There is a now a Composable
registerForActivityResult
function for getting results from activities within composables. ( Ia7851 , b/172690553 )
Изменения API
-
LocalOnBackPressedDispatcherOwner
now has aprovides
functions that can be used withCompositionLocalProvider
, replacing theasProvidableCompositionLocal()
API. ( I45d24 )
Версия 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. Версия 1.3.0-Alpha02 содержит эти коммиты.
Исправления ошибок
- Fixed an issue in Activity Compose
1.3.0-alpha01
that causes aNoSuchMethodError: No static method setContent
exception when using Compose1.0.0-alpha12
. All Compose users should depend on1.3.0-alpha02
and above. ( b/179911234 )
Изменения API
- The
BackHandler
API can be used to allow a Composable to intercept the system back button. ( I58ed5 , b/172154006 )
Версия 1.3.0-Alpha01
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. Версия 1.3.0-Alpha01 содержит эти коммиты.
Новые возможности
- The new
activity-compose
artifact provides Jetpack Compose specific helpers forandroidx.activity
specific APIs.-
ComponentActivity.setContent
has moved fromandroidx.compose.ui.platform.setContent
toandroidx.activity.compose.setContent
. ( Icf416 )
-
Известные проблемы
- Using Activity Compose
1.3.0-alpha01
and libraries that depend on it, such asandroidx.compose.ui:ui-test-junit4:1.0.0-alpha12
, will result in aNoSuchMethodError: No static method setContent
exception. ( 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.
Исправления ошибок
- 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.
Исправления ошибок
- Using the
launch()
method extension with a customActivityResultContract
that has aUnit
input will no longer cause aNullPointerException
( I76282 , b/183837954 ) - Fixed a false positive lint error telling you to use Fragment
1.3.0
when using an snapshot, alpha, beta, or RC build of a newer version of Fragments. ( f4a57e , b/184847092 )
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.
Исправления ошибок
- Fixed an issue in the
InvalidFragmentVersionForActivityResult
lint check that led to a false positive when using Fragment 1.3.1 or higher. ( I54da1 , b/182388985 ) -
ComponentActivity
now avoids aClassNotFoundException
when launching anIntent
from anActivityResultContract
that was previously held as an extra in anotherIntent
. ( Ieff05 , b/182906230 )
Обновления зависимости
- Activity now depends on Lifecycle
2.3.1
.
Версия 1.2.1
Версия 1.2.1
March 10, 2021
androidx.activity:activity:1.2.1
and androidx.activity:activity-ktx:1.2.1
are released. Версия 1.2.1 содержит эти коммиты.
Исправления ошибок
-
RequestMultiplePermissions
now always returns results for all requested permissions instead of only permissions that weren't previously granted. ( I50bc3 , b/180884668 ) -
ActivityResultRegistry
now ensures that in progresslaunch()
requests will return their results even if youunregister()
, thenregister()
again with the same key. ( I9ef34 , b/181267562 )
Версия 1.2.0
Версия 1.2.0
February 10, 2021
androidx.activity:activity:1.2.0
and androidx.activity:activity-ktx:1.2.0
are released. Версия 1.2.0 содержит эти коммиты.
Major changes since 1.1.0
- Activity Result APIs :
ComponentActivity
now provides anActivityResultRegistry
that 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
:ComponentActivity
now implementsContextAware
, allowing you to add one or moreOnContextAvailableListener
instances 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
FragmentActivity
in Fragment 1.3.0 to restore the state of theFragmentManager
. Any listeners added to subclasses ofFragmentActivity
will run after that listener. - This API is used by
AppCompatActivity
in AppCompat 1.3.0-alpha02 or higher. Any listeners added to subclasses ofAppCompatActivity
will run after that listener.
- A suspending Kotlin extension
ViewTree
Support :ComponentActivity
now supports theViewTreeLifecycleOwner.get(View)
,ViewTreeViewModelStoreOwner.get(View)
, andViewTreeSavedStateRegistryOwner
APIs added in Lifecycle2.3.0
and SavedState1.1.0
such that it will return the Activity as theLifecycleOwner
,ViewModelStoreOwner
, andSavedStateRegistryOwner
for any Views directly added to theComponentActivity
.
- reportFullyDrawn() backport - The
Activity
method ofreportFullyDrawn()
has been backported inComponentActivity
to work on all API levels, fixing a crash on API 19 and adding tracing for this method for all API levels.
Версия 1.2.0-RC01
December 16, 2020
androidx.activity:activity:1.2.0-rc01
and androidx.activity:activity-ktx:1.2.0-rc01
are released. Версия 1.2.0-RC01 содержит эти коммиты.
Исправления ошибок
- The
ActivityResultRegistry
now always restores the exact state that was saved. ( Idd56b ) - Add tracing to
ComponentActivity.reportFullyDrawn
( Ic7632 )
Внешний вклад
-
ComponentActivity
now 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 )
Версия 1.2.0-бета02
December 2, 2020
androidx.activity:activity:1.2.0-beta02
and androidx.activity:activity-ktx:1.2.0-beta02
are released. Версия 1.2.0-бета02 содержит эти коммиты.
Исправления ошибок
- Fixed an issue where the Activity Result API would not wait for the Lifecycle to be
STARTED
before delivering results when registered with aLifecycle
. ( I109ea )
Внешний вклад
- Updated the documentation for
launch()
to explicitly call out that it can throw anActivityNotFoundException
. Thanks Michał Zieliński! ( aosp/1493580 )
Версия 1.2.0-бета01
October 1, 2020
androidx.activity:activity:1.2.0-beta01
and androidx.activity:activity-ktx:1.2.0-beta01
are released. Версия 1.2.0-бета01 содержит эти коммиты.
Исправления ошибок
The
ActivityResultRegistry
now 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 )Lifecycle
observers are properly removed when callingunregister()
on anActivityResultLauncher
. ( b/165608393 )
Behavior Changes
- The
ActivityResultRegistry
now throws anIllegalStateException
when attempting to callregister()
with aLifecycleOwner
whoseLifecycle
has already reachedSTARTED
. ( b/165435866 )
Documentation Updated
-
ContextAware
documentation links toLifecycleOwner
to highlightLifecycle
callbacks as the appropriate place for creation and destruction events. ( aosp/1414152 )
Версия 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. Версия 1.2.0-Alpha08 содержит эти коммиты.
Новые возможности
-
ComponentActivity
now implementsContextAware
, allowing you to add one or moreOnContextAvailableListener
instances 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
FragmentActivity
in Fragment 1.3.0-alpha08 to restore the state of theFragmentManager
. Any listeners added to subclasses ofFragmentActivity
will run after that listener. ( I513da ) - This API is used by
AppCompatActivity
in AppCompat 1.3.0-alpha02 . Any listeners added to subclasses ofAppCompatActivity
will run after that listener. ( I513da )
- A suspending Kotlin extension
Исправления ошибок
- Fixed an issue with the
ActivityResultFragmentVersionDetector
Lint check that caused it to break when using Lint 27.1.0 or higher. ( b/162155191 )
Версия 1.2.0-Alpha07
July 22, 2020
androidx.activity:activity:1.2.0-alpha07
and androidx.activity:activity-ktx:1.2.0-alpha07
are released. Версия 1.2.0-Alpha07 содержит эти коммиты.
Новые возможности
- Added a new
InvalidFragmentVersionForActivityResult
lint check that verifies that you are using Fragment1.3.0-alpha07
when using the Activity Result API , avoiding runtime crashes due to “invalid request code” issues and non-functioning permission requests caused by using older versions of Fragments. ( b/152554847 )
Внешний вклад
- Fixed an
ArrayIndexOutOfBoundsException
when parsing the results for theRequestPermission
Activity Result contract. ( I8f9e3 , b/161057605 )
Версия 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. Версия 1.2.0-Alpha06 содержит эти коммиты.
Новые возможности
- You can now destructure the
ActivityResult
class in kotlin to directly access therequestCode
andintent
. ( b/157212935 ) -
ActivityResultLauncher
now allows you to get theActivityResultContract
that was used to register the launcher. ( b/156875743 )
Изменения API
- Breaking change : The
invoke()
method onActivityResultRegistry
has been renamed toonLaunch()
. ( b/157496491 ) - The
OpenMultipleDocuments
contract now returns an empty list instead ofnull
to the registered callback if no result is returned. ( b/157348014 )
Версия 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. Версия 1.2.0-Alpha05 содержит эти коммиты.
Новые возможности
- Added support for
ViewTreeViewModelStoreOwner
from Lifecycle2.3.0-alpha03
, andViewTreeSavedStateRegistryOwner
from SavedState1.1.0-alpha01
when using aView
within aComponentActivity
. ( aosp/1297993 , aosp/1300264 )
Изменения API
- The
TakePicture
contract now returns aboolean
indicating success rather than a thumbnailBitmap
as this was very rarely supported by camera apps when writing the image to the providedUri
. ( b/154302879 ) - The
invoke()
extensions onActivityResultLauncher
have been removed in favor of explicitly usinglaunch()
to better indicate that these are asynchronous operations. Kotlin extensions forlaunch
have been added to theandroidx.activity.result
package forActivityResultLauncher<Void>
andActivityResultLauncher<Unit>
that remove the need to pass innull
orUnit
, respectively, mirroring that behavior from the previouslyinvoke()
extensions. ( aosp/1304674 , aosp/1304675 ) - The
IntentSenderRequest.Builder
methods forsetFlagsMask()
andsetFlagsValues()
has been combined into a singlesetFlags()
method. ( aosp/1302111 )
Исправления ошибок
- When registering an
ActivityResultCallback
with aLifecycleOwner
, fixed an issue where the callback would be triggered before the state reachesSTARTED
. ( aosp/1309744 )
Behavior Changes
- The
ActivityResultRegistry
now generates request codes starting at0xFFFF
rather than at0
, preventing overlap when usingstartActivityForResult()
orrequestPermissions()
in an activity. ( aosp/1302324 )
Версия 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. Версия 1.2.0-Alpha04 содержит эти коммиты.
Новые возможности
- Added a contract that can call startIntentSenderForResult to the ActivityResult APIs. ( b/153007517 )
Изменения API
- The
prepareCall()
method has been renamed toregisterForActivityResult()
, both onComponentActivity
here and in Fragment1.3.0-alpha04
. ( aosp/1278717 ) - The
GetContents
,OpenDocuments
, andRequestPermissions
contracts have been renamed toGetMultipleContents
,OpenMultipleDocuments
, andRequestMultiplePermissions
, respectively. ( aosp/1280161 ) -
ComponentActivity
now implements theActivityResultRegisteryOwner
interface. ( aosp/1290888 ) - - The
startActivityForResult()
/onActivityResult()
andonRequestPermissionsResult()
APIs onComponentActivity
have been deprecated. Please use the Activity Result APIs . ( b/154751887 )
Исправления ошибок
- When using the
GetMultipleContents
andOpenMultipleDocuments
contracts and selecting a single item, it is now correctly returned to your callback. ( b/152941153 )
Версия 1.2.0-Alpha03
April 1, 2020
androidx.activity:activity:1.2.0-alpha03
and androidx.activity:activity-ktx:1.2.0-alpha03
are released. Версия 1.2.0-Alpha03 содержит эти коммиты.
Новые возможности
- Added the
TakeVideo
,PickContact
,GetContent
,GetContents
,OpenDocument
,OpenDocuments
,OpenDocumentTree
, andCreateDocument
contracts 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
- The
TakePicture
contract now takes aUri
input 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 onActivityResultRegistry
has been renamed toregister()
. ( aosp/1267621 ) - The
dispose()
method onActivityResultLauncher
has been renamed tounregister()
and theunregisterResultCallback()
onActivityResultRegistry
has been removed. ( aosp/1267621 ) - The
createIntent()
method ofActivityResultContact
now takes aContext
in addition to the input to make it possible to create explicit Intents. ( aosp/1238800 ) - An
ActivityResultContract
can now overridegetSynchronousResult()
to deliver a result without callingstartActivityForResult
. This is used by theRequestPermission
andRequestPermissions
contracts to correctly deliver a 'granted' status if the requested permissions are already granted. ( b/151110799 ) - The previously available
Dial
contract has been removed as thatIntent
is 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 ofActivityResultRegistry
exceptinvoke()
, and a number of the default contracts that do not support optional extras. ( b/152439361 )
Исправления ошибок
- Fixed a
NullPointerException
inActivityResultRegistry
when attempting to deliver results to a callback that has not yet been re-registered after a configuration change;ActivityResultRegistry
now holds onto these pending results and delivers them when the callback is re-registered. ( b/152137004 )
Версия 1.2.0-Alpha02
March 18, 2020
androidx.activity:activity:1.2.0-alpha02
and androidx.activity:activity-ktx:1.2.0-alpha02
are released. Версия 1.2.0-Alpha02 содержит эти коммиты.
Новые возможности
- ActivityResultRegistry :
ComponentActivity
now provides anActivityResultRegistry
that 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 )
Версия 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. Версия 1.2.0-Alpha01 содержит эти коммиты.
Новые возможности
- Added support for the
ViewTreeLifecycleOwner.get(View)
API added in Lifecycle2.3.0-alpha01
such that it will return the Activity as theLifecycleOwner
for any Views directly added to the Activity. ( aosp/1182955 )
Исправления ошибок
- Fixed a regression introduced in Activity
1.1.0
when running on older versions of the platform whereonBackPressed()
would cause anIllegalStateException
due to a bug in theandroid.app.FragmentManager
. ( b/146290338 )
Версия 1.1.0
Версия 1.1.0
January 22, 2020
androidx.activity:activity:1.1.0
is released. Версия 1.1.0 содержит эти коммиты .
Важные изменения с версии 1.0.0
- Lifecycle ViewModel SavedState Integration :
SavedStateViewModelFactory
is now the default factory used when usingby viewModels()
, theViewModelProvider
constructor, orViewModelProviders.of()
with aComponentActivity
or its subclasses.
Версия 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-rc03
and 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
.
Версия 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
. Версия 1.1.0-rc01 содержит эти коммиты .
Версия 1.1.0-бета01
October 9, 2019
androidx.activity:activity:1.1.0-beta01
and androidx.activity:activity-ktx:1.1.0-beta01
are released. Версия 1.1.0-beta01 содержит эти коммиты .
Dependency changes
- Activity now depends on SavedState 1.0.0 stable.
Версия 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 .
New features
- Activity now depends on Core 1.1.0 stable.
Исправления ошибок
- Activity now depends on Lifecycle
2.2.0-alpha04
.
Версия 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 .
New features
-
SavedStateViewModelFactory
is now the default factory used when usingby viewModels()
, theViewModelProvider
constructor, orViewModelProviders.of()
with aComponentActivity
( b/135716331 )
Версия 1.1.0-альфа01
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 .
New features
-
activity
now depends on Lifecycle2.2.0-alpha02
. ( aosp/1007817 ) -
activity-ktx
added a dependency onlifecycle-runtime-ktx
; you no longer need to explicitly add it to your dependencies when usingactivity-ktx
or libraries that depend onactivity-ktx
(such asfragment-ktx
). ( aosp/987162 )
Версия 1.0.0
Версия 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 :
ComponentActivity
serves as the new base class forFragmentActivity
in Fragment1.1.0
and, by extension,AppCompatActivity
in AppCompat1.1.0
. - activity-ktx : The
activity-ktx
module includes aby viewModels
Kotlin property extension for accessing ViewModels. This module is automatically included when you includefragment-ktx
from Fragment1.1.0
. - OnBackPressedDispatcher : As a composable alternative to overriding
onBackPressed()
, you can now register aOnBackPressedCallback
from anyLifecycleOwner
(such as a fragment) to intercept system back button events. A lambda with receiver versionaddCallback
has 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 anyViewModelStoreOwner
that makes the ownership of the retained objects clear and provides anonCleared()
callback for cleaning up resources when the activity is finally destroyed.
Версия 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 .
Версия 1.0.0-бета01
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
addOnBackPressedCallback
andremoveOnBackPressedCallback
methods onComponentActivity
have been removed. aosp/953857 - The
setEnabled()
andisEnabled()
methods ofOnBackPressedCallback
are now final. b/131416833 - The
remove()
method ofOnBackPressedCallback
is now final. aosp/952720 -
OnBackPressedDispatcher
now has public constructors, allowing you to construct your own instances for testing, etc. aosp/953431 -
onBackPressed()
forComponentActivity
is now explicitly marked as@MainThread
aosp/952721
Исправления ошибок
- Fixed a
ConcurrentModificationException
when callingremove()
from within thehandleOnBackPressed()
method of aOnBackPressedCalback
that 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
OnBackPressedCallback
andOnBackPressedDispatcher
have been marked as@MainThread
. ( aosp/943813 ) - The
handleOnBackPressed()
method no longer returns aboolean
. Instead,OnBackPressedCallback
is 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
addCallback
methods ofOnBackPressedDispatcher
no longer return aCancellable
instance.OnBackPressedCallback
now contain aremove()
method that fulfill this functionality, allowing you to callremove()
duringhandleOnBackPressed()
. ( aosp/944519 ) ( aosp/946316 ) -
activity-ktx
now contains a receiver scoped callback foraddCallback
that accepts a lamdba that implementshandleOnBackPressed()
and has access toisEnabled
andremove()
( 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
OnBackPressedCallback
related APIs on ComponentActivity have been deprecated in favor of the newOnBackPressedDispatcher
, retrievable viagetOnBackPressedDispatcher()
. ( aosp/922523 ) - Methods to add a new
OnBackPressedCallback
to theOnBackPressedDispatcher
now return aCancellable
object, allowing removal of the callback without requiring an explicit reference to theOnBackPressedDispatcher
. ( aosp/922523 ) - Adding a
OnBackPressedCallback
with an associatedLifecycleOwner
now results in adding and removing theOnBackPressedCallback
as the Lifecycle is started and stopped, respectively. ( aosp/922523 )
Версия 1.0.0-альфа05
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 .
New features
-
@ContentView
annotation lookups are now cached ( b/123709449 )
Версия 1.0.0-альфа04
January 30, 2019
androidx.activity:activity 1.0.0-alpha04
and androidx.activity:activity-ktx 1.0.0-alpha04
are released.
New features
- Added support for the
@ContentView
class 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
activity
module now depends on version 2.1.0-alpha02 of ViewModel to match theactivity-ktx
module's dependency.
Version 1.0.0-alpha03
December 17, 2018
androidx.activity 1.0.0-alpha03
is released.
New features
- ComponentActivity now implements
BundleSavedStateRegistryOwner
and depends on the newly released SavedState library [ aosp/815133 ] - ComponentActivity now works around an Android framework bug that would cause InputMethodManager to leak the last focused view [ b/37122102 ]
Версия 1.0.0-альфа02
December 3, 2018
API changes
- Added a note that
getLifecycle()
should not be overridden and will be madefinal
in a future release. Please file a feature request if you are currently overriding this method. ( aosp/815834 )
Версия 1.0.0-альфа01
November 5, 2018
androidx.activity 1.0.0-alpha01
introduces ComponentActivity
, a new base class of the existing FragmentActivity
and AppCompatActivity
.
New features
- You can now register an
OnBackPressedCallback
viaaddOnBackPressedCallback
to receiveonBackPressed()
callbacks without needing to override the method in your activity. - Added a new
by viewModels()
Kotlin property delegate for retrievingViewModel
s from aComponentActivity
. - Pending input events (such as clicks) are now canceled in
onStop()
.
API changes
- The implementation of
LifecycleOwner
andViewModelStoreOwner
have been moved fromFragmentActivity
toComponentActivity
. -
onRetainCustomNonConfigurationInstance
has been deprecated. Use aViewModel
for storing objects that need to survive configuration changes.