summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.prebuilt_info/prebuilt_info_packages_CtsShim_apk__arm_CtsShimPriv_apk.asciipb4
-rw-r--r--.prebuilt_info/prebuilt_info_packages_CtsShim_apk__arm_CtsShim_apk.asciipb4
-rw-r--r--.prebuilt_info/prebuilt_info_packages_CtsShim_apk__x86_CtsShimPriv_apk.asciipb4
-rw-r--r--.prebuilt_info/prebuilt_info_packages_CtsShim_apk__x86_CtsShim_apk.asciipb4
-rw-r--r--apex/jobscheduler/framework/java/android/app/AlarmManager.java11
-rw-r--r--apex/jobscheduler/service/java/com/android/server/alarm/AlarmManagerService.java85
-rw-r--r--apex/jobscheduler/service/java/com/android/server/job/JobConcurrencyManager.java2
-rw-r--r--apex/jobscheduler/service/java/com/android/server/job/controllers/PrefetchController.java45
-rw-r--r--core/api/test-current.txt1
-rw-r--r--core/java/android/app/ActivityClient.java9
-rw-r--r--core/java/android/app/ActivityManager.java4
-rw-r--r--core/java/android/app/ActivityOptions.java28
-rw-r--r--core/java/android/app/ActivityThread.java31
-rw-r--r--core/java/android/app/ActivityThreadInternal.java2
-rw-r--r--core/java/android/app/AppOpsManager.java52
-rw-r--r--core/java/android/app/ConfigurationController.java6
-rw-r--r--core/java/android/app/ContextImpl.java47
-rw-r--r--core/java/android/app/IActivityClientController.aidl1
-rw-r--r--core/java/android/app/IActivityManager.aidl2
-rw-r--r--core/java/android/app/INotificationManager.aidl1
-rw-r--r--core/java/android/app/NotificationChannel.java21
-rw-r--r--core/java/android/app/ResourcesManager.java4
-rw-r--r--core/java/android/app/admin/DevicePolicyManager.java53
-rw-r--r--core/java/android/app/admin/DevicePolicyResources.java45
-rw-r--r--core/java/android/app/admin/DevicePolicyResourcesManager.java41
-rw-r--r--core/java/android/app/backup/BackupTransport.java218
-rw-r--r--core/java/android/app/smartspace/SmartspaceTarget.java2
-rw-r--r--core/java/android/companion/virtual/OWNERS1
-rw-r--r--core/java/android/content/Context.java13
-rw-r--r--core/java/android/content/ContextWrapper.java6
-rw-r--r--core/java/android/content/pm/AppSearchShortcutInfo.java5
-rw-r--r--core/java/android/content/res/AssetFileDescriptor.java97
-rw-r--r--core/java/android/hardware/Sensor.java6
-rw-r--r--core/java/android/hardware/camera2/params/OutputConfiguration.java11
-rw-r--r--core/java/android/hardware/display/AmbientDisplayConfiguration.java3
-rw-r--r--core/java/android/inputmethodservice/InputMethodService.java19
-rw-r--r--core/java/android/net/IVpnManager.aidl2
-rw-r--r--core/java/android/net/VpnManager.java78
-rw-r--r--core/java/android/net/VpnProfileState.java42
-rw-r--r--core/java/android/permission/PermissionControllerManager.java2
-rw-r--r--core/java/android/permission/PermissionUsageHelper.java3
-rw-r--r--core/java/android/provider/DeviceConfig.java19
-rw-r--r--core/java/android/service/voice/AbstractHotwordDetector.java9
-rw-r--r--core/java/android/service/voice/IMicrophoneHotwordDetectionVoiceInteractionCallback.aidl5
-rw-r--r--core/java/android/service/voice/SoftwareHotwordDetector.java9
-rw-r--r--core/java/android/service/wallpaper/WallpaperService.java7
-rw-r--r--core/java/android/speech/RecognitionService.java5
-rw-r--r--core/java/android/view/IDisplayChangeWindowCallback.aidl (renamed from core/java/android/view/IDisplayWindowRotationCallback.aidl)10
-rw-r--r--core/java/android/view/IDisplayChangeWindowController.aidl (renamed from core/java/android/view/IDisplayWindowRotationController.aidl)24
-rw-r--r--core/java/android/view/IWindowManager.aidl4
-rw-r--r--core/java/android/view/Surface.java8
-rw-r--r--core/java/android/view/View.java7
-rw-r--r--core/java/android/window/ImeOnBackInvokedDispatcher.java6
-rw-r--r--core/java/android/window/TransitionInfo.java9
-rw-r--r--core/java/com/android/internal/app/AppLocaleStore.java96
-rw-r--r--core/java/com/android/internal/app/ChooserActivity.java8
-rw-r--r--core/java/com/android/internal/app/ChooserTargetActionsDialogFragment.java2
-rw-r--r--core/java/com/android/internal/app/LocalePickerWithRegion.java38
-rw-r--r--core/java/com/android/internal/app/ResolverActivity.java55
-rw-r--r--core/java/com/android/internal/app/procstats/ProcessStats.java16
-rw-r--r--core/java/com/android/internal/jank/InteractionJankMonitor.java12
-rw-r--r--core/java/com/android/internal/os/BatteryStatsImpl.java19
-rw-r--r--core/java/com/android/internal/view/ScrollCaptureViewSupport.java2
-rw-r--r--core/jni/android_view_SurfaceControl.cpp1
-rw-r--r--core/res/AndroidManifest.xml6
-rw-r--r--core/res/res/anim-ldrtl/task_fragment_close_enter.xml38
-rw-r--r--core/res/res/anim-ldrtl/task_fragment_close_exit.xml40
-rw-r--r--core/res/res/anim-ldrtl/task_fragment_open_enter.xml40
-rw-r--r--core/res/res/anim-ldrtl/task_fragment_open_exit.xml38
-rw-r--r--core/res/res/anim/task_fragment_close_enter.xml21
-rw-r--r--core/res/res/anim/task_fragment_close_exit.xml19
-rw-r--r--core/res/res/anim/task_fragment_open_enter.xml14
-rw-r--r--core/res/res/anim/task_fragment_open_exit.xml20
-rw-r--r--core/res/res/layout/miniresolver.xml16
-rw-r--r--core/res/res/values-mcc262/config.xml2
-rw-r--r--core/res/res/values/colors.xml3
-rw-r--r--core/res/res/values/config.xml72
-rw-r--r--core/res/res/values/config_telephony.xml2
-rw-r--r--core/res/res/values/strings.xml6
-rw-r--r--core/res/res/values/symbols.xml22
-rw-r--r--core/tests/coretests/src/android/app/activity/ActivityThreadTest.java48
-rw-r--r--core/tests/coretests/src/android/content/pm/AppSearchShortcutInfoTest.java12
-rw-r--r--core/tests/coretests/src/android/view/RenderNodeAnimatorTest.java49
-rw-r--r--core/tests/coretests/src/com/android/internal/app/ResolverWrapperActivity.java4
-rw-r--r--core/tests/coretests/src/com/android/internal/os/BatteryStatsNoteTest.java49
-rw-r--r--core/tests/coretests/src/com/android/internal/os/MockBatteryStatsImpl.java10
-rw-r--r--data/etc/com.android.systemui.xml1
-rw-r--r--data/etc/services.core.protolog.json42
-rw-r--r--graphics/java/android/graphics/RenderNode.java7
-rw-r--r--keystore/java/android/security/keystore2/AndroidKeyStoreBCWorkaroundProvider.java2
-rw-r--r--keystore/java/android/security/keystore2/AndroidKeyStoreECDSASignatureSpi.java24
-rw-r--r--keystore/java/android/security/keystore2/AndroidKeyStoreKeyAgreementSpi.java11
-rw-r--r--keystore/java/android/security/keystore2/AndroidKeyStoreKeyPairGeneratorSpi.java13
-rw-r--r--keystore/java/android/security/keystore2/AndroidKeyStoreProvider.java5
-rw-r--r--keystore/java/android/security/keystore2/AndroidKeyStoreXDHPrivateKey.java47
-rw-r--r--keystore/java/android/security/keystore2/AndroidKeyStoreXDHPublicKey.java120
-rw-r--r--libs/WindowManager/Jetpack/src/TEST_MAPPING7
-rw-r--r--libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/SplitController.java664
-rw-r--r--libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/SplitPresenter.java42
-rw-r--r--libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/TaskContainer.java19
-rw-r--r--libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/TaskFragmentAnimationAdapter.java32
-rw-r--r--libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/TaskFragmentContainer.java34
-rw-r--r--libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/SplitControllerTest.java641
-rw-r--r--libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/TaskContainerTest.java38
-rw-r--r--libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/TaskFragmentContainerTest.java78
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/ShellCommandHandlerImpl.java34
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/ShellInitImpl.java5
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/animation/Interpolators.java13
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/apppairs/AppPair.java357
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/apppairs/AppPairs.java38
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/apppairs/AppPairsController.java213
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/apppairs/AppPairsPool.java93
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/apppairs/OWNERS2
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BadgedImageView.java2
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleController.java42
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleDebugConfig.java3
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleExpandedView.java276
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubblePositioner.java25
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleStackView.java279
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubblesNavBarGestureTracker.java104
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubblesNavBarInputEventReceiver.java51
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubblesNavBarMotionEventHandler.java175
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/RelativeTouchListener.kt8
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/ExpandedAnimationController.java33
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/ExpandedViewAnimationController.java75
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/ExpandedViewAnimationControllerImpl.java432
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/ExpandedViewAnimationControllerStub.java57
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/OverScroll.java57
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/common/DisplayChangeController.java73
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/common/DisplayController.java4
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/common/DisplayImeController.java5
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/dagger/TvPipModule.java25
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellBaseModule.java18
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellModule.java17
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/onehanded/OneHandedController.java7
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipTaskOrganizer.java3
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipTransition.java49
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipController.java2
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipBoundsAlgorithm.java30
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipBoundsController.java253
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipController.java90
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipKeepClearAlgorithm.kt78
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipMenuController.java21
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/StageCoordinator.java22
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/startingsurface/SplashscreenContentDrawer.java109
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/startingsurface/SplashscreenIconDrawableFactory.java23
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/startingsurface/StartingSurfaceDrawer.java3
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/transition/Transitions.java44
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/unfold/UnfoldTransitionHandler.java3
-rw-r--r--libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/apppairs/AppPairsTestCannotPairNonResizeableApps.kt115
-rw-r--r--libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/apppairs/AppPairsTestPairPrimaryAndSecondaryApps.kt104
-rw-r--r--libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/apppairs/AppPairsTestSupportPairNonResizeableApps.kt128
-rw-r--r--libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/apppairs/AppPairsTestUnpairPrimaryAndSecondaryApps.kt121
-rw-r--r--libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/apppairs/AppPairsTransition.kt178
-rw-r--r--libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/apppairs/OWNERS2
-rw-r--r--libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/apppairs/RotateTwoLaunchedAppsInAppPairsMode.kt109
-rw-r--r--libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/apppairs/RotateTwoLaunchedAppsRotateAndEnterAppPairsMode.kt117
-rw-r--r--libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/apppairs/RotateTwoLaunchedAppsTransition.kt76
-rw-r--r--libs/WindowManager/Shell/tests/unittest/Android.bp1
-rw-r--r--libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/apppairs/AppPairTests.java123
-rw-r--r--libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/apppairs/AppPairsControllerTests.java104
-rw-r--r--libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/apppairs/AppPairsPoolTests.java77
-rw-r--r--libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/apppairs/TestAppPairsController.java42
-rw-r--r--libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/apppairs/TestAppPairsPool.java36
-rw-r--r--libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/bubbles/BubblesNavBarMotionEventHandlerTest.java142
-rw-r--r--libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/bubbles/animation/ExpandedViewAnimationControllerTest.java181
-rw-r--r--libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/onehanded/OneHandedControllerTest.java16
-rw-r--r--libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/tv/TvPipBoundsControllerTest.kt255
-rw-r--r--libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/tv/TvPipKeepClearAlgorithmTest.kt51
-rw-r--r--libs/hwui/AnimatorManager.cpp19
-rw-r--r--libs/hwui/AnimatorManager.h8
-rw-r--r--libs/hwui/Properties.cpp2
-rw-r--r--libs/hwui/jni/android_graphics_RenderNode.cpp7
-rw-r--r--media/java/android/media/AudioDeviceVolumeManager.java30
-rw-r--r--media/java/android/media/AudioTrack.java4
-rw-r--r--media/java/android/media/tv/interactive/ITvInteractiveAppManagerCallback.aidl4
-rw-r--r--media/jni/android_media_MediaCodec.cpp23
-rw-r--r--media/jni/android_media_Utils.cpp6
-rw-r--r--media/jni/android_media_Utils.h14
-rw-r--r--packages/CompanionDeviceManager/res/values/strings.xml7
-rw-r--r--packages/CompanionDeviceManager/src/com/android/companiondevicemanager/CompanionDeviceActivity.java10
-rw-r--r--packages/CompanionDeviceManager/src/com/android/companiondevicemanager/CompanionDeviceDiscoveryService.java3
-rw-r--r--packages/CompanionDeviceManager/src/com/android/companiondevicemanager/DeviceFilterPair.java2
-rw-r--r--packages/CtsShim/apk/arm/CtsShim.apkbin5488 -> 8542 bytes
-rw-r--r--packages/CtsShim/apk/arm/CtsShimPriv.apkbin31623 -> 34930 bytes
-rw-r--r--packages/CtsShim/apk/x86/CtsShim.apkbin5488 -> 8542 bytes
-rw-r--r--packages/CtsShim/apk/x86/CtsShimPriv.apkbin24264 -> 26558 bytes
-rw-r--r--packages/CtsShim/build/Android.bp1
-rw-r--r--packages/SettingsLib/AndroidManifest.xml10
-rw-r--r--packages/SettingsLib/AppPreference/res/layout/preference_app_header.xml36
-rw-r--r--packages/SettingsLib/SettingsTheme/res/values/styles.xml7
-rw-r--r--packages/SettingsLib/TopIntroPreference/Android.bp1
-rw-r--r--packages/SettingsLib/TopIntroPreference/res/values/styles.xml23
-rw-r--r--packages/SettingsLib/res/layout/qrcode_scanner_fragment.xml102
-rw-r--r--packages/SettingsLib/res/values-af/strings.xml5
-rw-r--r--packages/SettingsLib/res/values-am/strings.xml3
-rw-r--r--packages/SettingsLib/res/values-ar/strings.xml20
-rw-r--r--packages/SettingsLib/res/values-as/strings.xml5
-rw-r--r--packages/SettingsLib/res/values-az/strings.xml3
-rw-r--r--packages/SettingsLib/res/values-b+sr+Latn/strings.xml3
-rw-r--r--packages/SettingsLib/res/values-be/strings.xml12
-rw-r--r--packages/SettingsLib/res/values-bg/strings.xml12
-rw-r--r--packages/SettingsLib/res/values-bn/strings.xml3
-rw-r--r--packages/SettingsLib/res/values-bs/strings.xml13
-rw-r--r--packages/SettingsLib/res/values-ca/strings.xml12
-rw-r--r--packages/SettingsLib/res/values-cs/strings.xml12
-rw-r--r--packages/SettingsLib/res/values-da/strings.xml5
-rw-r--r--packages/SettingsLib/res/values-de/strings.xml12
-rw-r--r--packages/SettingsLib/res/values-el/strings.xml12
-rw-r--r--packages/SettingsLib/res/values-en-rAU/strings.xml3
-rw-r--r--packages/SettingsLib/res/values-en-rCA/strings.xml3
-rw-r--r--packages/SettingsLib/res/values-en-rGB/strings.xml3
-rw-r--r--packages/SettingsLib/res/values-en-rIN/strings.xml3
-rw-r--r--packages/SettingsLib/res/values-en-rXC/strings.xml3
-rw-r--r--packages/SettingsLib/res/values-es-rUS/strings.xml12
-rw-r--r--packages/SettingsLib/res/values-es/strings.xml12
-rw-r--r--packages/SettingsLib/res/values-et/strings.xml12
-rw-r--r--packages/SettingsLib/res/values-eu/strings.xml12
-rw-r--r--packages/SettingsLib/res/values-fa/strings.xml12
-rw-r--r--packages/SettingsLib/res/values-fi/strings.xml12
-rw-r--r--packages/SettingsLib/res/values-fr-rCA/strings.xml12
-rw-r--r--packages/SettingsLib/res/values-fr/strings.xml14
-rw-r--r--packages/SettingsLib/res/values-gl/strings.xml14
-rw-r--r--packages/SettingsLib/res/values-gu/strings.xml3
-rw-r--r--packages/SettingsLib/res/values-hi/strings.xml7
-rw-r--r--packages/SettingsLib/res/values-hr/strings.xml3
-rw-r--r--packages/SettingsLib/res/values-hu/strings.xml12
-rw-r--r--packages/SettingsLib/res/values-hy/strings.xml20
-rw-r--r--packages/SettingsLib/res/values-in/strings.xml12
-rw-r--r--packages/SettingsLib/res/values-is/strings.xml12
-rw-r--r--packages/SettingsLib/res/values-it/strings.xml12
-rw-r--r--packages/SettingsLib/res/values-iw/strings.xml12
-rw-r--r--packages/SettingsLib/res/values-ja/strings.xml12
-rw-r--r--packages/SettingsLib/res/values-ka/strings.xml3
-rw-r--r--packages/SettingsLib/res/values-kk/strings.xml14
-rw-r--r--packages/SettingsLib/res/values-km/strings.xml12
-rw-r--r--packages/SettingsLib/res/values-kn/strings.xml3
-rw-r--r--packages/SettingsLib/res/values-ko/strings.xml12
-rw-r--r--packages/SettingsLib/res/values-ky/strings.xml12
-rw-r--r--packages/SettingsLib/res/values-lo/strings.xml7
-rw-r--r--packages/SettingsLib/res/values-lt/strings.xml12
-rw-r--r--packages/SettingsLib/res/values-lv/strings.xml12
-rw-r--r--packages/SettingsLib/res/values-mk/strings.xml3
-rw-r--r--packages/SettingsLib/res/values-ml/strings.xml14
-rw-r--r--packages/SettingsLib/res/values-mn/strings.xml3
-rw-r--r--packages/SettingsLib/res/values-mr/strings.xml3
-rw-r--r--packages/SettingsLib/res/values-ms/strings.xml9
-rw-r--r--packages/SettingsLib/res/values-my/strings.xml12
-rw-r--r--packages/SettingsLib/res/values-nb/strings.xml12
-rw-r--r--packages/SettingsLib/res/values-ne/strings.xml3
-rw-r--r--packages/SettingsLib/res/values-nl/strings.xml3
-rw-r--r--packages/SettingsLib/res/values-or/strings.xml12
-rw-r--r--packages/SettingsLib/res/values-pa/strings.xml12
-rw-r--r--packages/SettingsLib/res/values-pl/strings.xml12
-rw-r--r--packages/SettingsLib/res/values-pt-rBR/strings.xml14
-rw-r--r--packages/SettingsLib/res/values-pt-rPT/strings.xml5
-rw-r--r--packages/SettingsLib/res/values-pt/strings.xml14
-rw-r--r--packages/SettingsLib/res/values-ro/strings.xml12
-rw-r--r--packages/SettingsLib/res/values-ru/strings.xml3
-rw-r--r--packages/SettingsLib/res/values-si/strings.xml16
-rw-r--r--packages/SettingsLib/res/values-sk/strings.xml5
-rw-r--r--packages/SettingsLib/res/values-sl/strings.xml3
-rw-r--r--packages/SettingsLib/res/values-sq/strings.xml12
-rw-r--r--packages/SettingsLib/res/values-sr/strings.xml3
-rw-r--r--packages/SettingsLib/res/values-sv/strings.xml12
-rw-r--r--packages/SettingsLib/res/values-sw/strings.xml16
-rw-r--r--packages/SettingsLib/res/values-ta/strings.xml5
-rw-r--r--packages/SettingsLib/res/values-te/strings.xml17
-rw-r--r--packages/SettingsLib/res/values-th/strings.xml5
-rw-r--r--packages/SettingsLib/res/values-tl/strings.xml5
-rw-r--r--packages/SettingsLib/res/values-tr/strings.xml14
-rw-r--r--packages/SettingsLib/res/values-uk/strings.xml14
-rw-r--r--packages/SettingsLib/res/values-ur/strings.xml3
-rw-r--r--packages/SettingsLib/res/values-uz/strings.xml7
-rw-r--r--packages/SettingsLib/res/values-vi/strings.xml3
-rw-r--r--packages/SettingsLib/res/values-zh-rCN/strings.xml7
-rw-r--r--packages/SettingsLib/res/values-zh-rHK/strings.xml12
-rw-r--r--packages/SettingsLib/res/values-zh-rTW/strings.xml14
-rw-r--r--packages/SettingsLib/res/values-zu/strings.xml3
-rw-r--r--packages/SettingsLib/res/values/dimens.xml6
-rw-r--r--packages/SettingsLib/res/values/strings.xml7
-rw-r--r--packages/SettingsLib/res/values/styles.xml7
-rw-r--r--packages/SettingsLib/src/com/android/settingslib/bluetooth/BluetoothUtils.java40
-rw-r--r--packages/SettingsLib/src/com/android/settingslib/bluetooth/CachedBluetoothDevice.java39
-rw-r--r--packages/SettingsLib/src/com/android/settingslib/bluetooth/HearingAidProfile.java99
-rw-r--r--packages/SettingsLib/src/com/android/settingslib/bluetooth/LocalBluetoothProfileManager.java5
-rw-r--r--packages/SettingsLib/src/com/android/settingslib/media/BluetoothMediaDevice.java2
-rw-r--r--packages/SettingsLib/src/com/android/settingslib/qrcode/QrCodeScanModeActivity.java109
-rw-r--r--packages/SettingsLib/src/com/android/settingslib/qrcode/QrCodeScanModeBaseActivity.java46
-rw-r--r--packages/SettingsLib/src/com/android/settingslib/qrcode/QrCodeScanModeController.java82
-rw-r--r--packages/SettingsLib/src/com/android/settingslib/qrcode/QrCodeScanModeFragment.java235
-rw-r--r--packages/SettingsLib/tests/robotests/src/com/android/settingslib/bluetooth/BluetoothUtilsTest.java14
-rw-r--r--packages/SettingsLib/tests/robotests/src/com/android/settingslib/bluetooth/CachedBluetoothDeviceTest.java63
-rw-r--r--packages/SettingsProvider/src/com/android/providers/settings/SettingsBackupAgent.java52
-rw-r--r--packages/SystemUI/AndroidManifest.xml2
-rw-r--r--packages/SystemUI/TEST_MAPPING44
-rw-r--r--packages/SystemUI/monet/src/com/android/systemui/monet/ColorScheme.kt59
-rw-r--r--packages/SystemUI/res/drawable/broadcast_dialog_btn_bg.xml (renamed from packages/SettingsLib/res/layout/qrcode_scan_mode_activity.xml)19
-rw-r--r--packages/SystemUI/res/drawable/ic_chevron_icon.xml14
-rw-r--r--packages/SystemUI/res/drawable/ic_qs_screen_saver.xml (renamed from packages/SettingsLib/res/drawable/ic_qr_code_scanner.xml)13
-rw-r--r--packages/SystemUI/res/drawable/media_output_status_check.xml4
-rw-r--r--packages/SystemUI/res/drawable/overlay_cancel.xml2
-rw-r--r--packages/SystemUI/res/drawable/settings_input_antenna.xml23
-rw-r--r--packages/SystemUI/res/layout/broadcast_dialog.xml79
-rw-r--r--packages/SystemUI/res/layout/clipboard_edit_text_activity.xml1
-rw-r--r--packages/SystemUI/res/layout/clipboard_overlay.xml4
-rw-r--r--packages/SystemUI/res/values/defaults.xml23
-rw-r--r--packages/SystemUI/res/values/dimens.xml20
-rw-r--r--packages/SystemUI/res/values/strings.xml36
-rw-r--r--packages/SystemUI/res/values/styles.xml44
-rw-r--r--packages/SystemUI/shared/Android.bp1
-rw-r--r--packages/SystemUI/shared/src/com/android/systemui/unfold/config/ResourceUnfoldTransitionConfig.kt49
-rw-r--r--packages/SystemUI/shared/src/com/android/systemui/unfold/system/ActivityManagerActivityTypeProvider.kt35
-rw-r--r--packages/SystemUI/shared/src/com/android/systemui/unfold/system/DeviceStateManagerFoldProvider.kt51
-rw-r--r--packages/SystemUI/shared/src/com/android/systemui/unfold/system/SystemUnfoldSharedModule.kt61
-rw-r--r--packages/SystemUI/shared/src/com/android/systemui/unfold/updates/hinge/EmptyHingeAngleProvider.kt13
-rw-r--r--packages/SystemUI/shared/src/com/android/systemui/unfold/updates/hinge/HingeAngleProvider.kt19
-rw-r--r--packages/SystemUI/shared/src/com/android/systemui/unfold/util/NaturalRotationUnfoldProgressProvider.kt14
-rw-r--r--packages/SystemUI/src/com/android/keyguard/KeyguardHostViewController.java5
-rw-r--r--packages/SystemUI/src/com/android/keyguard/KeyguardPasswordView.java16
-rw-r--r--packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainer.java14
-rw-r--r--packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java2
-rw-r--r--packages/SystemUI/src/com/android/keyguard/LockIconViewController.java20
-rw-r--r--packages/SystemUI/src/com/android/systemui/DisplayCutoutBaseView.kt6
-rw-r--r--packages/SystemUI/src/com/android/systemui/ScreenDecorations.java118
-rw-r--r--packages/SystemUI/src/com/android/systemui/SwipeHelper.java6
-rw-r--r--packages/SystemUI/src/com/android/systemui/SystemUIFactory.java2
-rw-r--r--packages/SystemUI/src/com/android/systemui/appops/AppOpsControllerImpl.java6
-rw-r--r--packages/SystemUI/src/com/android/systemui/biometrics/AuthBiometricFingerprintView.kt10
-rw-r--r--packages/SystemUI/src/com/android/systemui/biometrics/AuthContainerView.java9
-rw-r--r--packages/SystemUI/src/com/android/systemui/biometrics/AuthController.java21
-rw-r--r--packages/SystemUI/src/com/android/systemui/biometrics/UdfpsAnimationViewController.kt5
-rw-r--r--packages/SystemUI/src/com/android/systemui/biometrics/UdfpsController.java66
-rw-r--r--packages/SystemUI/src/com/android/systemui/biometrics/UdfpsControllerOverlay.kt90
-rw-r--r--packages/SystemUI/src/com/android/systemui/biometrics/UdfpsDialogMeasureAdapter.java41
-rw-r--r--packages/SystemUI/src/com/android/systemui/biometrics/UdfpsEnrollViewController.java6
-rw-r--r--packages/SystemUI/src/com/android/systemui/bluetooth/BroadcastDialog.java134
-rw-r--r--packages/SystemUI/src/com/android/systemui/bluetooth/BroadcastDialogController.java60
-rw-r--r--packages/SystemUI/src/com/android/systemui/clipboardoverlay/ClipboardOverlayController.java56
-rw-r--r--packages/SystemUI/src/com/android/systemui/controls/ui/ControlViewHolder.kt8
-rw-r--r--packages/SystemUI/src/com/android/systemui/dagger/SysUIComponent.java4
-rw-r--r--packages/SystemUI/src/com/android/systemui/dagger/WMComponent.java4
-rw-r--r--packages/SystemUI/src/com/android/systemui/decor/OverlayWindow.kt11
-rw-r--r--packages/SystemUI/src/com/android/systemui/flags/Flags.java9
-rw-r--r--packages/SystemUI/src/com/android/systemui/keyguard/KeyguardUnlockAnimationController.kt8
-rw-r--r--packages/SystemUI/src/com/android/systemui/log/LogBuffer.kt99
-rw-r--r--packages/SystemUI/src/com/android/systemui/log/LogBufferFactory.kt13
-rw-r--r--packages/SystemUI/src/com/android/systemui/log/LogcatEchoTrackerDebug.kt6
-rw-r--r--packages/SystemUI/src/com/android/systemui/log/dagger/LogModule.java29
-rw-r--r--packages/SystemUI/src/com/android/systemui/log/dagger/MediaCarouselControllerLog.java (renamed from packages/SystemUI/src/com/android/systemui/statusbar/phone/NotifActivityLaunchEventsModule.java)25
-rw-r--r--packages/SystemUI/src/com/android/systemui/media/MediaCarouselController.kt51
-rw-r--r--packages/SystemUI/src/com/android/systemui/media/MediaCarouselControllerLogger.kt45
-rw-r--r--packages/SystemUI/src/com/android/systemui/media/MediaControlPanel.java6
-rw-r--r--packages/SystemUI/src/com/android/systemui/media/MediaDataUtils.java43
-rw-r--r--packages/SystemUI/src/com/android/systemui/media/MediaTimeoutListener.kt48
-rw-r--r--packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputBaseDialog.java48
-rw-r--r--packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputBroadcastDialog.java117
-rw-r--r--packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputController.java3
-rw-r--r--packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputMetricLogger.java64
-rw-r--r--packages/SystemUI/src/com/android/systemui/navigationbar/buttons/KeyButtonView.java9
-rw-r--r--packages/SystemUI/src/com/android/systemui/navigationbar/gestural/NavigationHandle.java12
-rw-r--r--packages/SystemUI/src/com/android/systemui/navigationbar/gestural/QuickswitchOrientedNavHandle.java20
-rw-r--r--packages/SystemUI/src/com/android/systemui/privacy/PrivacyItemController.kt4
-rw-r--r--packages/SystemUI/src/com/android/systemui/qrcodescanner/controller/QRCodeScannerController.java12
-rw-r--r--packages/SystemUI/src/com/android/systemui/qs/FgsManagerController.kt88
-rw-r--r--packages/SystemUI/src/com/android/systemui/qs/QSSecurityFooter.java128
-rw-r--r--packages/SystemUI/src/com/android/systemui/qs/tiles/DreamTile.java12
-rw-r--r--packages/SystemUI/src/com/android/systemui/qs/tiles/HotspotTile.java15
-rw-r--r--packages/SystemUI/src/com/android/systemui/screenshot/ScreenshotController.java15
-rw-r--r--packages/SystemUI/src/com/android/systemui/screenshot/ScreenshotView.java57
-rw-r--r--packages/SystemUI/src/com/android/systemui/screenshot/TakeScreenshotService.java26
-rw-r--r--packages/SystemUI/src/com/android/systemui/screenshot/TimeoutHandler.java4
-rw-r--r--packages/SystemUI/src/com/android/systemui/scrim/ScrimView.java21
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/HeadsUpStatusBarView.java27
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/LockscreenShadeTransitionController.kt25
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/NotificationLockscreenUserManager.java13
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/NotificationLockscreenUserManagerImpl.java143
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/NotificationShelf.java39
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/NotificationViewHierarchyManager.java28
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/DynamicPrivacyController.java6
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/InstantAppNotifier.java2
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationActivityStarter.java3
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationClicker.java2
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationClickerLogger.kt10
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationUtils.java13
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationUtils.kt31
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotifCollection.java157
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationEntry.java53
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/ShadeListBuilder.java22
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/ActivityLaunchAnimCoordinator.kt95
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/NotifCoordinators.kt4
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/RankingCoordinator.java129
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/SensitiveContentCoordinator.kt124
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/StackCoordinator.kt13
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/dagger/CoordinatorsModule.kt4
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/inflation/NotificationRowBinderImpl.java13
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/inflation/OnUserInteractionCallbackImpl.java59
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/legacy/OnUserInteractionCallbackImplLegacy.java19
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/notifcollection/NotifCollectionLogger.kt81
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/render/NodeSpecBuilder.kt10
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/render/NotifStackController.kt14
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/dagger/NotificationSectionHeadersModule.kt2
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/dagger/NotificationsModule.java5
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/icon/IconManager.kt31
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java121
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRowController.java19
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationContentView.java36
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/row/OnUserInteractionCallback.java33
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/row/RowContentBindParams.java3
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/row/StackScrollerDecorView.java47
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayout.java24
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutController.java63
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/StackScrollAlgorithm.java36
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/phone/HeadsUpAppearanceController.java38
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBottomAreaView.java12
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBouncer.java4
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/phone/NPVCDownEventState.kt17
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/phone/NotifActivityLaunchEvents.kt39
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelViewController.java26
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimController.java2
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimState.java14
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarLaunchAnimatorController.kt5
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarter.java129
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarterLogger.kt42
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationPresenter.java6
-rw-r--r--packages/SystemUI/src/com/android/systemui/theme/ThemeOverlayController.java9
-rw-r--r--packages/SystemUI/src/com/android/systemui/tv/TvBottomSheetActivity.java9
-rw-r--r--packages/SystemUI/src/com/android/systemui/unfold/UnfoldTransitionModule.kt8
-rw-r--r--packages/SystemUI/src/com/android/systemui/util/NotificationChannels.java26
-rw-r--r--packages/SystemUI/src/com/android/systemui/util/collection/RingBuffer.kt122
-rw-r--r--packages/SystemUI/src/com/android/systemui/volume/VolumeDialogImpl.java58
-rw-r--r--packages/SystemUI/src/com/android/systemui/volume/dagger/VolumeModule.java7
-rw-r--r--packages/SystemUI/src/com/android/systemui/wallet/controller/QuickAccessWalletController.java8
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/ScreenDecorationsTest.java1
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/biometrics/UdfpsControllerOverlayTest.kt67
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/biometrics/UdfpsDialogMeasureAdapterTest.java5
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/bluetooth/BroadcastDialogTest.java83
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/dump/LogBufferHelper.kt2
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/keyguard/KeyguardUnlockAnimationControllerTest.kt26
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/keyguard/LockIconViewControllerTest.java39
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/media/MediaCarouselControllerTest.kt4
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/media/MediaTimeoutListenerTest.kt59
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/monet/ColorSchemeTest.java2
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/qrcodescanner/controller/QRCodeScannerControllerTest.java8
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/qs/FgsManagerControllerTest.java285
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/qs/tiles/DreamTileTest.java22
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/qs/tiles/HotspotTileTest.java125
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/shared/animation/UnfoldConstantTranslateAnimatorTest.kt44
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/LSShadeTransitionLoggerTest.kt2
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/LockscreenShadeTransitionControllerTest.kt8
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationLockscreenUserManagerTest.java36
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/DynamicPrivacyControllerTest.java4
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationEntryManagerTest.java28
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/NotifCollectionTest.java71
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/ShadeListBuilderTest.java34
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/ActivityLaunchAnimCoordinatorTest.kt138
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/RankingCoordinatorTest.java65
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/SensitiveContentCoordinatorTest.kt268
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/StackCoordinatorTest.kt33
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/icon/IconManagerTest.kt63
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRowTest.java23
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationEntryManagerInflationTest.java6
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationTestHelper.java11
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationShelfTest.kt112
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutTest.java8
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/HeadsUpAppearanceControllerTest.java18
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/KeyguardBouncerTest.java15
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/PhoneStatusBarViewControllerTest.kt1
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/ScrimControllerTest.java7
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarterTest.java119
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/fragment/CollapsedStatusBarFragmentTest.java2
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/theme/ThemeOverlayControllerTest.java6
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/unfold/FoldStateLoggingProviderTest.kt20
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/unfold/config/ResourceUnfoldTransitionConfigTest.kt54
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/unfold/updates/DeviceFoldStateProviderTest.kt166
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/unfold/util/NaturalRotationUnfoldProgressProviderTest.kt27
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/unfold/util/ScaleAwareUnfoldProgressProviderTest.kt25
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/unfold/util/TestFoldStateProvider.kt2
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/util/NotificationChannelsTest.java (renamed from packages/SystemUI/tests/src/com/android/systemui/util/ChannelsTest.java)15
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/util/collection/RingBufferTest.kt131
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/volume/VolumeDialogImplTest.java6
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/wallet/controller/QuickAccessWalletControllerTest.java1
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/wmshell/TestableBubbleController.java2
-rw-r--r--packages/SystemUI/unfold/Android.bp39
-rw-r--r--packages/SystemUI/unfold/AndroidManifest.xml22
-rw-r--r--packages/SystemUI/unfold/lint-baseline.xml3
-rw-r--r--packages/SystemUI/unfold/src/com/android/systemui/unfold/UnfoldSharedComponent.kt (renamed from packages/SystemUI/shared/src/com/android/systemui/unfold/UnfoldSharedComponent.kt)18
-rw-r--r--packages/SystemUI/unfold/src/com/android/systemui/unfold/UnfoldSharedModule.kt (renamed from packages/SystemUI/shared/src/com/android/systemui/unfold/UnfoldSharedModule.kt)4
-rw-r--r--packages/SystemUI/unfold/src/com/android/systemui/unfold/UnfoldTransitionFactory.kt (renamed from packages/SystemUI/shared/src/com/android/systemui/unfold/UnfoldTransitionFactory.kt)15
-rw-r--r--packages/SystemUI/unfold/src/com/android/systemui/unfold/UnfoldTransitionProgressProvider.kt (renamed from packages/SystemUI/shared/src/com/android/systemui/unfold/UnfoldTransitionProgressProvider.kt)4
-rw-r--r--packages/SystemUI/unfold/src/com/android/systemui/unfold/compat/ScreenSizeFoldProvider.kt56
-rw-r--r--packages/SystemUI/unfold/src/com/android/systemui/unfold/compat/SizeScreenStatusProvider.kt54
-rw-r--r--packages/SystemUI/unfold/src/com/android/systemui/unfold/config/ResourceUnfoldTransitionConfig.kt41
-rw-r--r--packages/SystemUI/unfold/src/com/android/systemui/unfold/config/UnfoldTransitionConfig.kt (renamed from packages/SystemUI/shared/src/com/android/systemui/unfold/config/UnfoldTransitionConfig.kt)1
-rw-r--r--packages/SystemUI/unfold/src/com/android/systemui/unfold/dagger/UnfoldBackground.kt25
-rw-r--r--packages/SystemUI/unfold/src/com/android/systemui/unfold/dagger/UnfoldMain.kt25
-rw-r--r--packages/SystemUI/unfold/src/com/android/systemui/unfold/progress/FixedTimingTransitionProgressProvider.kt (renamed from packages/SystemUI/shared/src/com/android/systemui/unfold/progress/FixedTimingTransitionProgressProvider.kt)0
-rw-r--r--packages/SystemUI/unfold/src/com/android/systemui/unfold/progress/PhysicsBasedUnfoldTransitionProgressProvider.kt (renamed from packages/SystemUI/shared/src/com/android/systemui/unfold/progress/PhysicsBasedUnfoldTransitionProgressProvider.kt)4
-rw-r--r--packages/SystemUI/unfold/src/com/android/systemui/unfold/updates/DeviceFoldStateProvider.kt (renamed from packages/SystemUI/shared/src/com/android/systemui/unfold/updates/DeviceFoldStateProvider.kt)91
-rw-r--r--packages/SystemUI/unfold/src/com/android/systemui/unfold/updates/FoldProvider.kt26
-rw-r--r--packages/SystemUI/unfold/src/com/android/systemui/unfold/updates/FoldStateProvider.kt (renamed from packages/SystemUI/shared/src/com/android/systemui/unfold/updates/FoldStateProvider.kt)7
-rw-r--r--packages/SystemUI/unfold/src/com/android/systemui/unfold/updates/hinge/EmptyHingeAngleProvider.kt27
-rw-r--r--packages/SystemUI/unfold/src/com/android/systemui/unfold/updates/hinge/HingeAngleProvider.kt33
-rw-r--r--packages/SystemUI/unfold/src/com/android/systemui/unfold/updates/hinge/HingeSensorAngleProvider.kt (renamed from packages/SystemUI/shared/src/com/android/systemui/unfold/updates/hinge/HingeSensorAngleProvider.kt)14
-rw-r--r--packages/SystemUI/unfold/src/com/android/systemui/unfold/updates/screen/ScreenStatusProvider.kt (renamed from packages/SystemUI/shared/src/com/android/systemui/unfold/updates/screen/ScreenStatusProvider.kt)2
-rw-r--r--packages/SystemUI/unfold/src/com/android/systemui/unfold/util/ATraceLoggerTransitionProgressListener.kt (renamed from packages/SystemUI/shared/src/com/android/systemui/unfold/util/ATraceLoggerTransitionProgressListener.kt)14
-rw-r--r--packages/SystemUI/unfold/src/com/android/systemui/unfold/util/CallbackController.kt20
-rw-r--r--packages/SystemUI/unfold/src/com/android/systemui/unfold/util/CurrentActivityTypeProvider.kt22
-rw-r--r--packages/SystemUI/unfold/src/com/android/systemui/unfold/util/ScaleAwareTransitionProgressProvider.kt (renamed from packages/SystemUI/shared/src/com/android/systemui/unfold/util/ScaleAwareTransitionProgressProvider.kt)14
-rw-r--r--packages/SystemUI/unfold/src/com/android/systemui/unfold/util/ScopedUnfoldTransitionProgressProvider.kt (renamed from packages/SystemUI/shared/src/com/android/systemui/unfold/util/ScopedUnfoldTransitionProgressProvider.kt)0
-rw-r--r--packages/overlays/NavigationBarModeGesturalOverlay/res/values/dimens.xml6
-rw-r--r--packages/overlays/NavigationBarModeGesturalOverlayExtraWideBack/res/values/dimens.xml6
-rw-r--r--packages/overlays/NavigationBarModeGesturalOverlayNarrowBack/res/values/dimens.xml6
-rw-r--r--packages/overlays/NavigationBarModeGesturalOverlayWideBack/res/values/dimens.xml6
-rw-r--r--services/autofill/java/com/android/server/autofill/Session.java11
-rw-r--r--services/backup/backuplib/java/com/android/server/backup/transport/TransportStatusCallback.java2
-rw-r--r--services/companion/java/com/android/server/companion/AssociationRequestsProcessor.java15
-rw-r--r--services/companion/java/com/android/server/companion/CompanionDeviceManagerService.java62
-rw-r--r--services/companion/java/com/android/server/companion/CompanionDeviceManagerServiceInternal.java8
-rw-r--r--services/companion/java/com/android/server/companion/CompanionDeviceShellCommand.java17
-rw-r--r--services/companion/java/com/android/server/companion/InactiveAssociationsRemovalService.java (renamed from services/companion/java/com/android/server/companion/AssociationCleanUpService.java)29
-rw-r--r--services/companion/java/com/android/server/companion/virtual/InputController.java20
-rw-r--r--services/companion/java/com/android/server/companion/virtual/VirtualDeviceImpl.java6
-rw-r--r--services/contentcapture/java/com/android/server/contentcapture/ContentCaptureManagerService.java5
-rw-r--r--services/contentcapture/java/com/android/server/contentcapture/ContentCaptureMetricsLogger.java57
-rw-r--r--services/contentcapture/java/com/android/server/contentcapture/ContentCapturePerUserService.java10
-rw-r--r--services/contentcapture/java/com/android/server/contentcapture/RemoteContentCaptureService.java8
-rw-r--r--services/core/java/android/content/pm/PackageManagerInternal.java12
-rw-r--r--services/core/java/com/android/server/StorageManagerService.java5
-rw-r--r--services/core/java/com/android/server/TelephonyRegistry.java102
-rw-r--r--services/core/java/com/android/server/VpnManagerService.java32
-rw-r--r--services/core/java/com/android/server/Watchdog.java12
-rw-r--r--services/core/java/com/android/server/am/ActiveServices.java38
-rw-r--r--services/core/java/com/android/server/am/ActivityManagerService.java135
-rw-r--r--services/core/java/com/android/server/am/ActivityManagerShellCommand.java14
-rw-r--r--services/core/java/com/android/server/am/AppBatteryTracker.java46
-rw-r--r--services/core/java/com/android/server/am/BatteryExternalStatsWorker.java5
-rw-r--r--services/core/java/com/android/server/am/BroadcastQueue.java28
-rw-r--r--services/core/java/com/android/server/am/BroadcastRecord.java19
-rw-r--r--services/core/java/com/android/server/am/ComponentAliasResolver.java6
-rw-r--r--services/core/java/com/android/server/am/PreBootBroadcaster.java2
-rw-r--r--services/core/java/com/android/server/am/UserController.java4
-rw-r--r--services/core/java/com/android/server/apphibernation/AppHibernationService.java2
-rw-r--r--services/core/java/com/android/server/appop/AppOpsService.java23
-rw-r--r--services/core/java/com/android/server/appop/DiscreteRegistry.java3
-rw-r--r--services/core/java/com/android/server/audio/AudioService.java22
-rw-r--r--services/core/java/com/android/server/audio/SpatializerHelper.java38
-rw-r--r--services/core/java/com/android/server/biometrics/sensors/face/aidl/FaceResetLockoutClient.java4
-rw-r--r--services/core/java/com/android/server/biometrics/sensors/face/hidl/FaceResetLockoutClient.java4
-rw-r--r--services/core/java/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintResetLockoutClient.java4
-rw-r--r--services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/FingerprintResetLockoutClient.java4
-rw-r--r--services/core/java/com/android/server/clipboard/EmulatorClipboardMonitor.java155
-rw-r--r--services/core/java/com/android/server/connectivity/Vpn.java247
-rw-r--r--services/core/java/com/android/server/connectivity/VpnIkev2Utils.java10
-rw-r--r--services/core/java/com/android/server/display/color/ColorDisplayService.java20
-rw-r--r--services/core/java/com/android/server/dreams/DreamManagerService.java12
-rw-r--r--services/core/java/com/android/server/hdmi/HdmiCecLocalDeviceTv.java45
-rw-r--r--services/core/java/com/android/server/hdmi/HdmiControlService.java13
-rw-r--r--services/core/java/com/android/server/hdmi/RequestArcAction.java2
-rw-r--r--services/core/java/com/android/server/hdmi/RequestArcInitiationAction.java2
-rw-r--r--services/core/java/com/android/server/hdmi/RequestSadAction.java27
-rw-r--r--services/core/java/com/android/server/hdmi/SetArcTransmissionStateAction.java58
-rw-r--r--services/core/java/com/android/server/location/gnss/GnssLocationProvider.java1
-rw-r--r--services/core/java/com/android/server/location/gnss/GnssNetworkConnectivityHandler.java27
-rwxr-xr-xservices/core/java/com/android/server/notification/NotificationManagerService.java15
-rw-r--r--services/core/java/com/android/server/notification/PermissionHelper.java31
-rw-r--r--services/core/java/com/android/server/notification/PreferencesHelper.java68
-rw-r--r--services/core/java/com/android/server/pm/ApexManager.java9
-rw-r--r--services/core/java/com/android/server/pm/BackgroundDexOptService.java231
-rw-r--r--services/core/java/com/android/server/pm/BroadcastHelper.java8
-rw-r--r--services/core/java/com/android/server/pm/Computer.java5
-rw-r--r--services/core/java/com/android/server/pm/ComputerEngine.java13
-rw-r--r--services/core/java/com/android/server/pm/ComputerLocked.java2
-rw-r--r--services/core/java/com/android/server/pm/DeletePackageHelper.java5
-rw-r--r--services/core/java/com/android/server/pm/DexOptHelper.java52
-rw-r--r--services/core/java/com/android/server/pm/FileInstallArgs.java19
-rw-r--r--services/core/java/com/android/server/pm/InstallPackageHelper.java5
-rw-r--r--services/core/java/com/android/server/pm/Installer.java30
-rw-r--r--services/core/java/com/android/server/pm/IntentResolverInterceptor.java104
-rw-r--r--services/core/java/com/android/server/pm/PackageManagerInternalBase.java13
-rw-r--r--services/core/java/com/android/server/pm/PackageManagerService.java130
-rw-r--r--services/core/java/com/android/server/pm/PackageManagerServiceUtils.java57
-rw-r--r--services/core/java/com/android/server/pm/PackageManagerShellCommand.java32
-rw-r--r--services/core/java/com/android/server/pm/ProtectedPackages.java43
-rw-r--r--services/core/java/com/android/server/pm/ReconcilePackageUtils.java10
-rw-r--r--services/core/java/com/android/server/pm/ResolveIntentHelper.java34
-rw-r--r--services/core/java/com/android/server/pm/ThreadComputer.java52
-rw-r--r--services/core/java/com/android/server/pm/UserDataPreparer.java18
-rw-r--r--services/core/java/com/android/server/pm/dex/ArtStatsLogUtils.java29
-rw-r--r--services/core/java/com/android/server/pm/permission/DefaultPermissionGrantPolicy.java17
-rw-r--r--services/core/java/com/android/server/pm/permission/LegacyPermissionManagerInternal.java15
-rw-r--r--services/core/java/com/android/server/pm/permission/LegacyPermissionManagerService.java18
-rw-r--r--services/core/java/com/android/server/pm/permission/PermissionManagerService.java22
-rw-r--r--services/core/java/com/android/server/pm/permission/PermissionManagerServiceImpl.java51
-rw-r--r--services/core/java/com/android/server/pm/permission/PermissionManagerServiceInternal.java11
-rw-r--r--services/core/java/com/android/server/pm/pkg/component/ParsedPermissionUtils.java34
-rw-r--r--services/core/java/com/android/server/pm/pkg/parsing/ParsingPackageUtils.java2
-rw-r--r--services/core/java/com/android/server/policy/AppOpsPolicy.java8
-rw-r--r--services/core/java/com/android/server/policy/PermissionPolicyService.java63
-rw-r--r--services/core/java/com/android/server/sensorprivacy/CameraPrivacyLightController.java186
-rw-r--r--services/core/java/com/android/server/sensorprivacy/SensorPrivacyService.java5
-rw-r--r--services/core/java/com/android/server/soundtrigger_middleware/SoundTriggerMiddlewarePermission.java31
-rw-r--r--services/core/java/com/android/server/stats/pull/StatsPullAtomService.java3
-rw-r--r--services/core/java/com/android/server/vcn/util/PersistableBundleUtils.java26
-rw-r--r--services/core/java/com/android/server/wm/ActivityClientController.java12
-rw-r--r--services/core/java/com/android/server/wm/ActivityInterceptorCallback.java6
-rw-r--r--services/core/java/com/android/server/wm/ActivityRecord.java133
-rw-r--r--services/core/java/com/android/server/wm/ActivityStartController.java2
-rw-r--r--services/core/java/com/android/server/wm/ActivityStarter.java3
-rw-r--r--services/core/java/com/android/server/wm/AppTransitionController.java15
-rw-r--r--services/core/java/com/android/server/wm/Dimmer.java9
-rw-r--r--services/core/java/com/android/server/wm/DisplayContent.java24
-rw-r--r--services/core/java/com/android/server/wm/DisplayPolicy.java32
-rw-r--r--services/core/java/com/android/server/wm/DisplayRotation.java109
-rw-r--r--services/core/java/com/android/server/wm/InputMonitor.java16
-rw-r--r--services/core/java/com/android/server/wm/InsetsPolicy.java19
-rw-r--r--services/core/java/com/android/server/wm/InsetsSourceProvider.java6
-rw-r--r--services/core/java/com/android/server/wm/KeyguardController.java4
-rw-r--r--services/core/java/com/android/server/wm/Letterbox.java12
-rw-r--r--services/core/java/com/android/server/wm/LetterboxConfiguration.java371
-rw-r--r--services/core/java/com/android/server/wm/LetterboxUiController.java92
-rw-r--r--services/core/java/com/android/server/wm/LockTaskController.java24
-rw-r--r--services/core/java/com/android/server/wm/PhysicalDisplaySwitchTransitionLauncher.java53
-rw-r--r--services/core/java/com/android/server/wm/RecentsAnimationController.java5
-rw-r--r--services/core/java/com/android/server/wm/RemoteDisplayChangeController.java185
-rw-r--r--services/core/java/com/android/server/wm/RootWindowContainer.java5
-rw-r--r--services/core/java/com/android/server/wm/SafeActivityOptions.java15
-rw-r--r--services/core/java/com/android/server/wm/ScreenRotationAnimation.java1
-rw-r--r--services/core/java/com/android/server/wm/SimpleSurfaceAnimatable.java22
-rw-r--r--services/core/java/com/android/server/wm/SurfaceAnimator.java14
-rw-r--r--services/core/java/com/android/server/wm/Task.java102
-rw-r--r--services/core/java/com/android/server/wm/TaskDisplayArea.java12
-rw-r--r--services/core/java/com/android/server/wm/TaskFragment.java33
-rw-r--r--services/core/java/com/android/server/wm/TaskFragmentOrganizerController.java5
-rw-r--r--services/core/java/com/android/server/wm/Transition.java9
-rw-r--r--services/core/java/com/android/server/wm/WindowContainer.java5
-rw-r--r--services/core/java/com/android/server/wm/WindowContainerThumbnail.java5
-rw-r--r--services/core/java/com/android/server/wm/WindowManagerService.java45
-rw-r--r--services/core/java/com/android/server/wm/WindowManagerShellCommand.java184
-rw-r--r--services/core/java/com/android/server/wm/WindowOrganizerController.java12
-rw-r--r--services/core/java/com/android/server/wm/WindowProcessController.java107
-rw-r--r--services/core/jni/com_android_server_am_CachedAppOptimizer.cpp249
-rw-r--r--services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java87
-rw-r--r--services/java/com/android/server/SystemServer.java1
-rw-r--r--services/tests/mockingservicestests/src/com/android/server/alarm/AlarmManagerServiceTest.java17
-rw-r--r--services/tests/mockingservicestests/src/com/android/server/am/BackgroundRestrictionTest.java20
-rw-r--r--services/tests/mockingservicestests/src/com/android/server/job/controllers/PrefetchControllerTest.java46
-rw-r--r--services/tests/mockingservicestests/src/com/android/server/pm/BackgroundDexOptServiceUnitTest.java201
-rw-r--r--services/tests/mockingservicestests/src/com/android/server/pm/DeletePackageHelperTest.kt44
-rw-r--r--services/tests/mockingservicestests/src/com/android/server/sensorprivacy/CameraPrivacyLightControllerTest.java208
-rw-r--r--services/tests/servicestests/src/com/android/server/am/BroadcastRecordTest.java1
-rw-r--r--services/tests/servicestests/src/com/android/server/apphibernation/AppHibernationServiceTest.java2
-rw-r--r--services/tests/servicestests/src/com/android/server/companion/virtual/InputControllerTest.java7
-rw-r--r--services/tests/servicestests/src/com/android/server/companion/virtual/VirtualDeviceManagerServiceTest.java4
-rw-r--r--services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java15
-rw-r--r--services/tests/servicestests/src/com/android/server/hdmi/HdmiCecLocalDeviceTvTest.java13
-rw-r--r--services/tests/servicestests/src/com/android/server/hdmi/RequestSadActionTest.java135
-rw-r--r--services/tests/servicestests/src/com/android/server/pm/ApexManagerTest.java12
-rwxr-xr-xservices/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java10
-rw-r--r--services/tests/uiservicestests/src/com/android/server/notification/PermissionHelperTest.java100
-rw-r--r--services/tests/uiservicestests/src/com/android/server/notification/PreferencesHelperTest.java140
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java19
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/AppTransitionControllerTest.java43
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/DimmerTests.java10
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/DisplayContentTests.java44
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/InsetsStateControllerTest.java30
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/LetterboxTest.java2
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/LockTaskControllerTest.java17
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/RecentsAnimationControllerTest.java25
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/SizeCompatTests.java151
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/SurfaceAnimatorTest.java5
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/TaskFragmentOrganizerControllerTest.java5
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/TransitionTests.java5
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/WindowProcessControllerTests.java40
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/WindowTestsBase.java19
-rw-r--r--services/usb/java/com/android/server/usb/UsbDirectMidiDevice.java28
-rw-r--r--services/usb/java/com/android/server/usb/UsbMidiDevice.java32
-rw-r--r--services/voiceinteraction/java/com/android/server/voiceinteraction/HotwordDetectionConnection.java71
-rw-r--r--telecomm/java/android/telecom/Call.java14
-rw-r--r--telephony/common/android/telephony/LocationAccessPolicy.java38
-rw-r--r--telephony/common/com/android/internal/telephony/CellBroadcastUtils.java14
-rw-r--r--telephony/common/com/android/internal/telephony/SmsApplication.java10
-rw-r--r--telephony/java/android/telephony/NetworkRegistrationInfo.java52
-rw-r--r--telephony/java/android/telephony/TelephonyManager.java58
-rw-r--r--telephony/java/android/telephony/euicc/EuiccManager.java25
-rw-r--r--telephony/java/android/telephony/ims/feature/RcsFeature.java6
-rw-r--r--telephony/java/com/android/internal/telephony/ITelephony.aidl14
-rw-r--r--tests/TelephonyCommonTests/src/com/android/internal/telephony/tests/SmsApplicationTest.java3
-rw-r--r--tests/vcn/java/com/android/server/vcn/util/PersistableBundleUtilsTest.java9
689 files changed, 16042 insertions, 9011 deletions
diff --git a/.prebuilt_info/prebuilt_info_packages_CtsShim_apk__arm_CtsShimPriv_apk.asciipb b/.prebuilt_info/prebuilt_info_packages_CtsShim_apk__arm_CtsShimPriv_apk.asciipb
index 0ccd9511d945..6b3278fc6925 100644
--- a/.prebuilt_info/prebuilt_info_packages_CtsShim_apk__arm_CtsShimPriv_apk.asciipb
+++ b/.prebuilt_info/prebuilt_info_packages_CtsShim_apk__arm_CtsShimPriv_apk.asciipb
@@ -1,6 +1,6 @@
drops {
android_build_drop {
- build_id: "7552332"
+ build_id: "8572644"
target: "CtsShim"
source_file: "aosp_arm64/CtsShimPriv.apk"
}
@@ -8,7 +8,7 @@ drops {
version: ""
version_group: ""
git_project: "platform/frameworks/base"
- git_branch: "sc-dev"
+ git_branch: "tm-dev"
transform: TRANSFORM_NONE
transform_options {
}
diff --git a/.prebuilt_info/prebuilt_info_packages_CtsShim_apk__arm_CtsShim_apk.asciipb b/.prebuilt_info/prebuilt_info_packages_CtsShim_apk__arm_CtsShim_apk.asciipb
index 7e85c8f6697d..34c9c4d4fe08 100644
--- a/.prebuilt_info/prebuilt_info_packages_CtsShim_apk__arm_CtsShim_apk.asciipb
+++ b/.prebuilt_info/prebuilt_info_packages_CtsShim_apk__arm_CtsShim_apk.asciipb
@@ -1,6 +1,6 @@
drops {
android_build_drop {
- build_id: "7552332"
+ build_id: "8572644"
target: "CtsShim"
source_file: "aosp_arm64/CtsShim.apk"
}
@@ -8,7 +8,7 @@ drops {
version: ""
version_group: ""
git_project: "platform/frameworks/base"
- git_branch: "sc-dev"
+ git_branch: "tm-dev"
transform: TRANSFORM_NONE
transform_options {
}
diff --git a/.prebuilt_info/prebuilt_info_packages_CtsShim_apk__x86_CtsShimPriv_apk.asciipb b/.prebuilt_info/prebuilt_info_packages_CtsShim_apk__x86_CtsShimPriv_apk.asciipb
index 20c27858e9ab..6897a027705f 100644
--- a/.prebuilt_info/prebuilt_info_packages_CtsShim_apk__x86_CtsShimPriv_apk.asciipb
+++ b/.prebuilt_info/prebuilt_info_packages_CtsShim_apk__x86_CtsShimPriv_apk.asciipb
@@ -1,6 +1,6 @@
drops {
android_build_drop {
- build_id: "7552332"
+ build_id: "8572644"
target: "CtsShim"
source_file: "aosp_x86_64/CtsShimPriv.apk"
}
@@ -8,7 +8,7 @@ drops {
version: ""
version_group: ""
git_project: "platform/frameworks/base"
- git_branch: "sc-dev"
+ git_branch: "tm-dev"
transform: TRANSFORM_NONE
transform_options {
}
diff --git a/.prebuilt_info/prebuilt_info_packages_CtsShim_apk__x86_CtsShim_apk.asciipb b/.prebuilt_info/prebuilt_info_packages_CtsShim_apk__x86_CtsShim_apk.asciipb
index 13e3ae5b121b..6dfa7810f22d 100644
--- a/.prebuilt_info/prebuilt_info_packages_CtsShim_apk__x86_CtsShim_apk.asciipb
+++ b/.prebuilt_info/prebuilt_info_packages_CtsShim_apk__x86_CtsShim_apk.asciipb
@@ -1,6 +1,6 @@
drops {
android_build_drop {
- build_id: "7552332"
+ build_id: "8572644"
target: "CtsShim"
source_file: "aosp_x86_64/CtsShim.apk"
}
@@ -8,7 +8,7 @@ drops {
version: ""
version_group: ""
git_project: "platform/frameworks/base"
- git_branch: "sc-dev"
+ git_branch: "tm-dev"
transform: TRANSFORM_NONE
transform_options {
}
diff --git a/apex/jobscheduler/framework/java/android/app/AlarmManager.java b/apex/jobscheduler/framework/java/android/app/AlarmManager.java
index 1b9cf2648a3f..7393bcde13b6 100644
--- a/apex/jobscheduler/framework/java/android/app/AlarmManager.java
+++ b/apex/jobscheduler/framework/java/android/app/AlarmManager.java
@@ -27,7 +27,7 @@ import android.annotation.SystemApi;
import android.annotation.SystemService;
import android.annotation.TestApi;
import android.compat.annotation.ChangeId;
-import android.compat.annotation.EnabledAfter;
+import android.compat.annotation.Disabled;
import android.compat.annotation.EnabledSince;
import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
@@ -282,15 +282,14 @@ public class AlarmManager {
public static final long ENABLE_USE_EXACT_ALARM = 218533173L;
/**
- * For apps targeting {@link Build.VERSION_CODES#TIRAMISU} or above, the permission
- * {@link Manifest.permission#SCHEDULE_EXACT_ALARM} will be denied, unless the user explicitly
- * allows it from Settings.
+ * The permission {@link Manifest.permission#SCHEDULE_EXACT_ALARM} will be denied, unless the
+ * user explicitly allows it from Settings.
*
- * TODO (b/226439802): change to EnabledSince(T) after SDK finalization.
+ * TODO (b/226439802): Either enable it in the next SDK or replace it with a better alternative.
* @hide
*/
@ChangeId
- @EnabledAfter(targetSdkVersion = Build.VERSION_CODES.S_V2)
+ @Disabled
public static final long SCHEDULE_EXACT_ALARM_DENIED_BY_DEFAULT = 226439802L;
@UnsupportedAppUsage
diff --git a/apex/jobscheduler/service/java/com/android/server/alarm/AlarmManagerService.java b/apex/jobscheduler/service/java/com/android/server/alarm/AlarmManagerService.java
index 2ea8592e883e..4aa9e84c10a9 100644
--- a/apex/jobscheduler/service/java/com/android/server/alarm/AlarmManagerService.java
+++ b/apex/jobscheduler/service/java/com/android/server/alarm/AlarmManagerService.java
@@ -30,6 +30,8 @@ import static android.app.AlarmManager.INTERVAL_HOUR;
import static android.app.AlarmManager.RTC;
import static android.app.AlarmManager.RTC_WAKEUP;
import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
+import static android.os.PowerExemptionManager.REASON_ALARM_MANAGER_ALARM_CLOCK;
+import static android.os.PowerExemptionManager.REASON_DENIED;
import static android.os.PowerExemptionManager.REASON_SCHEDULE_EXACT_ALARM_PERMISSION_STATE_CHANGED;
import static android.os.PowerExemptionManager.TEMPORARY_ALLOW_LIST_TYPE_FOREGROUND_SERVICE_ALLOWED;
import static android.os.PowerWhitelistManager.REASON_ALARM_MANAGER_WHILE_IDLE;
@@ -329,6 +331,7 @@ public class AlarmManagerService extends SystemService {
});
BroadcastOptions mOptsWithFgs = BroadcastOptions.makeBasic();
+ BroadcastOptions mOptsWithFgsForAlarmClock = BroadcastOptions.makeBasic();
BroadcastOptions mOptsWithoutFgs = BroadcastOptions.makeBasic();
BroadcastOptions mOptsTimeBroadcast = BroadcastOptions.makeBasic();
ActivityOptions mActivityOptsRestrictBal = ActivityOptions.makeBasic();
@@ -565,9 +568,6 @@ public class AlarmManagerService extends SystemService {
@VisibleForTesting
static final String KEY_KILL_ON_SCHEDULE_EXACT_ALARM_REVOKED =
"kill_on_schedule_exact_alarm_revoked";
- @VisibleForTesting
- static final String KEY_SCHEDULE_EXACT_ALARM_DENIED_BY_DEFAULT =
- "schedule_exact_alarm_denied_by_default";
private static final long DEFAULT_MIN_FUTURITY = 5 * 1000;
private static final long DEFAULT_MIN_INTERVAL = 60 * 1000;
@@ -612,8 +612,6 @@ public class AlarmManagerService extends SystemService {
private static final boolean DEFAULT_KILL_ON_SCHEDULE_EXACT_ALARM_REVOKED = true;
- private static final boolean DEFAULT_SCHEDULE_EXACT_ALARM_DENIED_BY_DEFAULT = true;
-
// Minimum futurity of a new alarm
public long MIN_FUTURITY = DEFAULT_MIN_FUTURITY;
@@ -701,14 +699,6 @@ public class AlarmManagerService extends SystemService {
public boolean KILL_ON_SCHEDULE_EXACT_ALARM_REVOKED =
DEFAULT_KILL_ON_SCHEDULE_EXACT_ALARM_REVOKED;
- /**
- * When this is {@code true}, apps with the change
- * {@link AlarmManager#SCHEDULE_EXACT_ALARM_DENIED_BY_DEFAULT} enabled will not get
- * {@link Manifest.permission#SCHEDULE_EXACT_ALARM} unless the user grants it to them.
- */
- public volatile boolean SCHEDULE_EXACT_ALARM_DENIED_BY_DEFAULT =
- DEFAULT_SCHEDULE_EXACT_ALARM_DENIED_BY_DEFAULT;
-
public boolean USE_TARE_POLICY = Settings.Global.DEFAULT_ENABLE_TARE == 1;
private long mLastAllowWhileIdleWhitelistDuration = -1;
@@ -743,9 +733,12 @@ public class AlarmManagerService extends SystemService {
mOptsWithFgs.setTemporaryAppAllowlist(ALLOW_WHILE_IDLE_WHITELIST_DURATION,
TEMPORARY_ALLOWLIST_TYPE_FOREGROUND_SERVICE_ALLOWED,
REASON_ALARM_MANAGER_WHILE_IDLE, "");
+ mOptsWithFgsForAlarmClock.setTemporaryAppAllowlist(
+ ALLOW_WHILE_IDLE_WHITELIST_DURATION,
+ TEMPORARY_ALLOWLIST_TYPE_FOREGROUND_SERVICE_ALLOWED,
+ REASON_ALARM_MANAGER_ALARM_CLOCK, "");
mOptsWithoutFgs.setTemporaryAppAllowlist(ALLOW_WHILE_IDLE_WHITELIST_DURATION,
- TEMPORARY_ALLOWLIST_TYPE_FOREGROUND_SERVICE_NOT_ALLOWED,
- REASON_ALARM_MANAGER_WHILE_IDLE, "");
+ TEMPORARY_ALLOWLIST_TYPE_FOREGROUND_SERVICE_NOT_ALLOWED, REASON_DENIED, "");
}
}
@@ -892,15 +885,6 @@ public class AlarmManagerService extends SystemService {
KEY_KILL_ON_SCHEDULE_EXACT_ALARM_REVOKED,
DEFAULT_KILL_ON_SCHEDULE_EXACT_ALARM_REVOKED);
break;
- case KEY_SCHEDULE_EXACT_ALARM_DENIED_BY_DEFAULT:
- final boolean oldValue = SCHEDULE_EXACT_ALARM_DENIED_BY_DEFAULT;
-
- SCHEDULE_EXACT_ALARM_DENIED_BY_DEFAULT = properties.getBoolean(
- KEY_SCHEDULE_EXACT_ALARM_DENIED_BY_DEFAULT,
- DEFAULT_SCHEDULE_EXACT_ALARM_DENIED_BY_DEFAULT);
- handleScheduleExactAlarmDeniedByDefaultChange(oldValue,
- SCHEDULE_EXACT_ALARM_DENIED_BY_DEFAULT);
- break;
default:
if (name.startsWith(KEY_PREFIX_STANDBY_QUOTA) && !standbyQuotaUpdated) {
// The quotas need to be updated in order, so we can't just rely
@@ -971,15 +955,6 @@ public class AlarmManagerService extends SystemService {
}
}
- private void handleScheduleExactAlarmDeniedByDefaultChange(boolean oldValue,
- boolean newValue) {
- if (oldValue == newValue) {
- return;
- }
- mHandler.obtainMessage(AlarmHandler.CHECK_EXACT_ALARM_PERMISSION_ON_FEATURE_TOGGLE,
- newValue).sendToTarget();
- }
-
private void migrateAlarmsToNewStoreLocked() {
final AlarmStore newStore = LAZY_BATCHING ? new LazyAlarmStore()
: new BatchingAlarmStore();
@@ -1156,9 +1131,6 @@ public class AlarmManagerService extends SystemService {
pw.print(KEY_KILL_ON_SCHEDULE_EXACT_ALARM_REVOKED,
KILL_ON_SCHEDULE_EXACT_ALARM_REVOKED);
pw.println();
- pw.print(KEY_SCHEDULE_EXACT_ALARM_DENIED_BY_DEFAULT,
- SCHEDULE_EXACT_ALARM_DENIED_BY_DEFAULT);
- pw.println();
pw.print(Settings.Global.ENABLE_TARE, USE_TARE_POLICY);
pw.println();
@@ -1744,6 +1716,7 @@ public class AlarmManagerService extends SystemService {
public void onStart() {
mInjector.init();
mOptsWithFgs.setPendingIntentBackgroundActivityLaunchAllowed(false);
+ mOptsWithFgsForAlarmClock.setPendingIntentBackgroundActivityLaunchAllowed(false);
mOptsWithoutFgs.setPendingIntentBackgroundActivityLaunchAllowed(false);
mOptsTimeBroadcast.setPendingIntentBackgroundActivityLaunchAllowed(false);
mActivityOptsRestrictBal.setPendingIntentBackgroundActivityLaunchAllowed(false);
@@ -2741,7 +2714,12 @@ public class AlarmManagerService extends SystemService {
if (isExactAlarmChangeEnabled(callingPackage, callingUserId)) {
needsPermission = exact;
lowerQuota = !exact;
- idleOptions = exact ? mOptsWithFgs.toBundle() : mOptsWithoutFgs.toBundle();
+ if (exact) {
+ idleOptions = (alarmClock != null) ? mOptsWithFgsForAlarmClock.toBundle()
+ : mOptsWithFgs.toBundle();
+ } else {
+ idleOptions = mOptsWithoutFgs.toBundle();
+ }
} else {
changeDisabled = true;
needsPermission = false;
@@ -2928,10 +2906,8 @@ public class AlarmManagerService extends SystemService {
}
private boolean isScheduleExactAlarmDeniedByDefault(String packageName, int userId) {
- return mConstants.SCHEDULE_EXACT_ALARM_DENIED_BY_DEFAULT
- && CompatChanges.isChangeEnabled(
- AlarmManager.SCHEDULE_EXACT_ALARM_DENIED_BY_DEFAULT, packageName,
- UserHandle.of(userId));
+ return CompatChanges.isChangeEnabled(AlarmManager.SCHEDULE_EXACT_ALARM_DENIED_BY_DEFAULT,
+ packageName, UserHandle.of(userId));
}
@NeverCompile // Avoid size overhead of debugging code.
@@ -4707,7 +4683,6 @@ public class AlarmManagerService extends SystemService {
public static final int REFRESH_EXACT_ALARM_CANDIDATES = 11;
public static final int TARE_AFFORDABILITY_CHANGED = 12;
public static final int CHECK_EXACT_ALARM_PERMISSION_ON_UPDATE = 13;
- public static final int CHECK_EXACT_ALARM_PERMISSION_ON_FEATURE_TOGGLE = 14;
AlarmHandler() {
super(Looper.myLooper());
@@ -4827,32 +4802,6 @@ public class AlarmManagerService extends SystemService {
removeExactAlarmsOnPermissionRevoked(uid, packageName, /*killUid = */false);
}
break;
- case CHECK_EXACT_ALARM_PERMISSION_ON_FEATURE_TOGGLE:
- final boolean defaultDenied = (Boolean) msg.obj;
-
- final int[] startedUserIds = mActivityManagerInternal.getStartedUserIds();
- for (int appId : mExactAlarmCandidates) {
- for (int userId : startedUserIds) {
- uid = UserHandle.getUid(userId, appId);
-
- final AndroidPackage packageForUid =
- mPackageManagerInternal.getPackage(uid);
- if (packageForUid == null) {
- continue;
- }
- final String pkg = packageForUid.getPackageName();
- if (defaultDenied) {
- if (!hasScheduleExactAlarmInternal(pkg, uid)
- && !hasUseExactAlarmInternal(pkg, uid)) {
- removeExactAlarmsOnPermissionRevoked(uid, pkg, true);
- }
- } else if (hasScheduleExactAlarmInternal(pkg, uid)) {
- sendScheduleExactAlarmPermissionStateChangedBroadcast(pkg,
- UserHandle.getUserId(uid));
- }
- }
- }
- break;
default:
// nope, just ignore it
break;
diff --git a/apex/jobscheduler/service/java/com/android/server/job/JobConcurrencyManager.java b/apex/jobscheduler/service/java/com/android/server/job/JobConcurrencyManager.java
index afe36b5fa25a..d5a7f2851d03 100644
--- a/apex/jobscheduler/service/java/com/android/server/job/JobConcurrencyManager.java
+++ b/apex/jobscheduler/service/java/com/android/server/job/JobConcurrencyManager.java
@@ -959,7 +959,7 @@ class JobConcurrencyManager {
for (int i = 0; i < mActiveServices.size(); i++) {
JobServiceContext jsc = mActiveServices.get(i);
final JobStatus executing = jsc.getRunningJobLocked();
- if (executing != null && executing.matches(job.getUid(), job.getJobId())) {
+ if (executing == job) {
jsc.cancelExecutingJobLocked(reason, internalReasonCode, debugReason);
return true;
}
diff --git a/apex/jobscheduler/service/java/com/android/server/job/controllers/PrefetchController.java b/apex/jobscheduler/service/java/com/android/server/job/controllers/PrefetchController.java
index 428f2cbaefc2..0f385efae5cc 100644
--- a/apex/jobscheduler/service/java/com/android/server/job/controllers/PrefetchController.java
+++ b/apex/jobscheduler/service/java/com/android/server/job/controllers/PrefetchController.java
@@ -17,6 +17,7 @@
package com.android.server.job.controllers;
import static android.text.format.DateUtils.HOUR_IN_MILLIS;
+import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
import static com.android.server.job.JobSchedulerService.sElapsedRealtimeClock;
import static com.android.server.job.JobSchedulerService.sSystemClock;
@@ -90,6 +91,14 @@ public class PrefetchController extends StateController {
@CurrentTimeMillisLong
private long mLaunchTimeThresholdMs = PcConstants.DEFAULT_LAUNCH_TIME_THRESHOLD_MS;
+ /**
+ * The additional time we'll add to a launch time estimate before considering it obsolete and
+ * try to get a new estimate. This will help make prefetch jobs more viable in case an estimate
+ * is a few minutes early.
+ */
+ @GuardedBy("mLock")
+ private long mLaunchTimeAllowanceMs = PcConstants.DEFAULT_LAUNCH_TIME_ALLOWANCE_MS;
+
@SuppressWarnings("FieldCanBeLocal")
private final EstimatedLaunchTimeChangedListener mEstimatedLaunchTimeChangedListener =
new EstimatedLaunchTimeChangedListener() {
@@ -204,7 +213,8 @@ public class PrefetchController extends StateController {
private long getNextEstimatedLaunchTimeLocked(int userId, @NonNull String pkgName,
@CurrentTimeMillisLong long now) {
final Long nextEstimatedLaunchTime = mEstimatedLaunchTimes.get(userId, pkgName);
- if (nextEstimatedLaunchTime == null || nextEstimatedLaunchTime < now) {
+ if (nextEstimatedLaunchTime == null
+ || nextEstimatedLaunchTime < now - mLaunchTimeAllowanceMs) {
// Don't query usage stats here because it may have to read from disk.
mHandler.obtainMessage(MSG_RETRIEVE_ESTIMATED_LAUNCH_TIME, userId, 0, pkgName)
.sendToTarget();
@@ -335,7 +345,9 @@ public class PrefetchController extends StateController {
}
final long nextEstimatedLaunchTime = getNextEstimatedLaunchTimeLocked(userId, pkgName, now);
- if (nextEstimatedLaunchTime - now > mLaunchTimeThresholdMs) {
+ // Avoid setting an alarm for the end of time.
+ if (nextEstimatedLaunchTime != Long.MAX_VALUE
+ && nextEstimatedLaunchTime - now > mLaunchTimeThresholdMs) {
// Set alarm to be notified when this crosses the threshold.
final long timeToCrossThresholdMs =
nextEstimatedLaunchTime - (now + mLaunchTimeThresholdMs);
@@ -354,7 +366,7 @@ public class PrefetchController extends StateController {
private boolean willBeLaunchedSoonLocked(int userId, @NonNull String pkgName,
@CurrentTimeMillisLong long now) {
return getNextEstimatedLaunchTimeLocked(userId, pkgName, now)
- <= now + mLaunchTimeThresholdMs;
+ <= now + mLaunchTimeThresholdMs - mLaunchTimeAllowanceMs;
}
@Override
@@ -494,16 +506,37 @@ public class PrefetchController extends StateController {
@VisibleForTesting
static final String KEY_LAUNCH_TIME_THRESHOLD_MS =
PC_CONSTANT_PREFIX + "launch_time_threshold_ms";
+ @VisibleForTesting
+ static final String KEY_LAUNCH_TIME_ALLOWANCE_MS =
+ PC_CONSTANT_PREFIX + "launch_time_allowance_ms";
private static final long DEFAULT_LAUNCH_TIME_THRESHOLD_MS = 7 * HOUR_IN_MILLIS;
+ private static final long DEFAULT_LAUNCH_TIME_ALLOWANCE_MS = 20 * MINUTE_IN_MILLIS;
/** How much time each app will have to run jobs within their standby bucket window. */
public long LAUNCH_TIME_THRESHOLD_MS = DEFAULT_LAUNCH_TIME_THRESHOLD_MS;
+ /**
+ * How much additional time to add to an estimated launch time before considering it
+ * unusable.
+ */
+ public long LAUNCH_TIME_ALLOWANCE_MS = DEFAULT_LAUNCH_TIME_ALLOWANCE_MS;
+
@GuardedBy("mLock")
public void processConstantLocked(@NonNull DeviceConfig.Properties properties,
@NonNull String key) {
switch (key) {
+ case KEY_LAUNCH_TIME_ALLOWANCE_MS:
+ LAUNCH_TIME_ALLOWANCE_MS =
+ properties.getLong(key, DEFAULT_LAUNCH_TIME_ALLOWANCE_MS);
+ // Limit the allowance to the range [0 minutes, 2 hours].
+ long newLaunchTimeAllowanceMs = Math.min(2 * HOUR_IN_MILLIS,
+ Math.max(0, LAUNCH_TIME_ALLOWANCE_MS));
+ if (mLaunchTimeAllowanceMs != newLaunchTimeAllowanceMs) {
+ mLaunchTimeAllowanceMs = newLaunchTimeAllowanceMs;
+ mShouldReevaluateConstraints = true;
+ }
+ break;
case KEY_LAUNCH_TIME_THRESHOLD_MS:
LAUNCH_TIME_THRESHOLD_MS =
properties.getLong(key, DEFAULT_LAUNCH_TIME_THRESHOLD_MS);
@@ -528,6 +561,7 @@ public class PrefetchController extends StateController {
pw.increaseIndent();
pw.print(KEY_LAUNCH_TIME_THRESHOLD_MS, LAUNCH_TIME_THRESHOLD_MS).println();
+ pw.print(KEY_LAUNCH_TIME_ALLOWANCE_MS, LAUNCH_TIME_ALLOWANCE_MS).println();
pw.decreaseIndent();
}
@@ -536,6 +570,11 @@ public class PrefetchController extends StateController {
//////////////////////// TESTING HELPERS /////////////////////////////
@VisibleForTesting
+ long getLaunchTimeAllowanceMs() {
+ return mLaunchTimeAllowanceMs;
+ }
+
+ @VisibleForTesting
long getLaunchTimeThresholdMs() {
return mLaunchTimeThresholdMs;
}
diff --git a/core/api/test-current.txt b/core/api/test-current.txt
index 4669ee1b25af..0354ae6d9f8b 100644
--- a/core/api/test-current.txt
+++ b/core/api/test-current.txt
@@ -320,7 +320,6 @@ package android.app {
method public void setDemoted(boolean);
method public void setFgServiceShown(boolean);
method public void setImportanceLockedByCriticalDeviceFunction(boolean);
- method public void setImportanceLockedByOEM(boolean);
method public void setImportantConversation(boolean);
method public void setOriginalImportance(int);
}
diff --git a/core/java/android/app/ActivityClient.java b/core/java/android/app/ActivityClient.java
index 668dc6b8ec63..73678d9f2dda 100644
--- a/core/java/android/app/ActivityClient.java
+++ b/core/java/android/app/ActivityClient.java
@@ -98,6 +98,15 @@ public class ActivityClient {
}
}
+ /** Reports the activity starts local relaunch. */
+ public void activityLocalRelaunch(IBinder token) {
+ try {
+ getActivityClientController().activityLocalRelaunch(token);
+ } catch (RemoteException e) {
+ e.rethrowFromSystemServer();
+ }
+ }
+
/** Reports the activity has completed relaunched. */
public void activityRelaunched(IBinder token) {
try {
diff --git a/core/java/android/app/ActivityManager.java b/core/java/android/app/ActivityManager.java
index 661f0292603b..e25e374122cf 100644
--- a/core/java/android/app/ActivityManager.java
+++ b/core/java/android/app/ActivityManager.java
@@ -4616,8 +4616,8 @@ public class ActivityManager {
try {
getService().broadcastIntentWithFeature(
null, null, intent, null, null, Activity.RESULT_OK, null, null,
- null /*requiredPermissions*/, null /*excludedPermissions*/, appOp, null, false,
- true, userId);
+ null /*requiredPermissions*/, null /*excludedPermissions*/,
+ null /*excludedPackages*/, appOp, null, false, true, userId);
} catch (RemoteException ex) {
}
}
diff --git a/core/java/android/app/ActivityOptions.java b/core/java/android/app/ActivityOptions.java
index 2eebc01ccc04..d6441a2b629b 100644
--- a/core/java/android/app/ActivityOptions.java
+++ b/core/java/android/app/ActivityOptions.java
@@ -16,6 +16,7 @@
package android.app;
+import static android.Manifest.permission.CONTROL_KEYGUARD;
import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
@@ -362,9 +363,8 @@ public class ActivityOptions extends ComponentOptions {
private static final String KEY_LAUNCH_INTO_PIP_PARAMS =
"android.activity.launchIntoPipParams";
- /** See {@link #setDismissKeyguardIfInsecure()}. */
- private static final String KEY_DISMISS_KEYGUARD_IF_INSECURE =
- "android.activity.dismissKeyguardIfInsecure";
+ /** See {@link #setDismissKeyguard()}. */
+ private static final String KEY_DISMISS_KEYGUARD = "android.activity.dismissKeyguard";
private static final String KEY_IGNORE_PENDING_INTENT_CREATOR_FOREGROUND_STATE =
"android.activity.ignorePendingIntentCreatorForegroundState";
@@ -465,7 +465,7 @@ public class ActivityOptions extends ComponentOptions {
private boolean mLaunchedFromBubble;
private boolean mTransientLaunch;
private PictureInPictureParams mLaunchIntoPipParams;
- private boolean mDismissKeyguardIfInsecure;
+ private boolean mDismissKeyguard;
private boolean mIgnorePendingIntentCreatorForegroundState;
/**
@@ -1270,7 +1270,7 @@ public class ActivityOptions extends ComponentOptions {
mLaunchIntoPipParams = opts.getParcelable(KEY_LAUNCH_INTO_PIP_PARAMS);
mIsEligibleForLegacyPermissionPrompt =
opts.getBoolean(KEY_LEGACY_PERMISSION_PROMPT_ELIGIBLE);
- mDismissKeyguardIfInsecure = opts.getBoolean(KEY_DISMISS_KEYGUARD_IF_INSECURE);
+ mDismissKeyguard = opts.getBoolean(KEY_DISMISS_KEYGUARD);
mIgnorePendingIntentCreatorForegroundState = opts.getBoolean(
KEY_IGNORE_PENDING_INTENT_CREATOR_FOREGROUND_STATE);
}
@@ -1869,24 +1869,24 @@ public class ActivityOptions extends ComponentOptions {
}
/**
- * Sets whether the insecure keyguard should go away when this activity launches. In case the
- * keyguard is secure, this option will be ignored.
+ * Sets whether the keyguard should go away when this activity launches.
*
* @see Activity#setShowWhenLocked(boolean)
* @see android.R.attr#showWhenLocked
* @hide
*/
- public void setDismissKeyguardIfInsecure() {
- mDismissKeyguardIfInsecure = true;
+ @RequiresPermission(CONTROL_KEYGUARD)
+ public void setDismissKeyguard() {
+ mDismissKeyguard = true;
}
/**
- * @see #setDismissKeyguardIfInsecure()
+ * @see #setDismissKeyguard()
* @return whether the insecure keyguard should go away when the activity launches.
* @hide
*/
- public boolean getDismissKeyguardIfInsecure() {
- return mDismissKeyguardIfInsecure;
+ public boolean getDismissKeyguard() {
+ return mDismissKeyguard;
}
/**
@@ -2167,8 +2167,8 @@ public class ActivityOptions extends ComponentOptions {
b.putBoolean(KEY_LEGACY_PERMISSION_PROMPT_ELIGIBLE,
mIsEligibleForLegacyPermissionPrompt);
}
- if (mDismissKeyguardIfInsecure) {
- b.putBoolean(KEY_DISMISS_KEYGUARD_IF_INSECURE, mDismissKeyguardIfInsecure);
+ if (mDismissKeyguard) {
+ b.putBoolean(KEY_DISMISS_KEYGUARD, mDismissKeyguard);
}
if (mIgnorePendingIntentCreatorForegroundState) {
b.putBoolean(KEY_IGNORE_PENDING_INTENT_CREATOR_FOREGROUND_STATE,
diff --git a/core/java/android/app/ActivityThread.java b/core/java/android/app/ActivityThread.java
index b4cabada0522..681be7e14f71 100644
--- a/core/java/android/app/ActivityThread.java
+++ b/core/java/android/app/ActivityThread.java
@@ -3410,26 +3410,12 @@ public final class ActivityThread extends ClientTransactionHandler
}
}
- /**
- * Returns {@code true} if the {@link android.app.ActivityManager.ProcessState} of the current
- * process is cached.
- */
- @Override
- @VisibleForTesting
- public boolean isCachedProcessState() {
- synchronized (mAppThread) {
- return mLastProcessState >= ActivityManager.PROCESS_STATE_CACHED_ACTIVITY;
- }
- }
-
@Override
public void updateProcessState(int processState, boolean fromIpc) {
- final boolean wasCached;
synchronized (mAppThread) {
if (mLastProcessState == processState) {
return;
}
- wasCached = isCachedProcessState();
mLastProcessState = processState;
// Defer the top state for VM to avoid aggressive JIT compilation affecting activity
// launch time.
@@ -3446,22 +3432,6 @@ public final class ActivityThread extends ClientTransactionHandler
+ (fromIpc ? " (from ipc" : ""));
}
}
-
- // Handle the pending configuration if the process state is changed from cached to
- // non-cached. Except the case where there is a launching activity because the
- // LaunchActivityItem will handle it.
- if (wasCached && !isCachedProcessState() && mNumLaunchingActivities.get() == 0) {
- final Configuration pendingConfig =
- mConfigurationController.getPendingConfiguration(false /* clearPending */);
- if (pendingConfig == null) {
- return;
- }
- if (Looper.myLooper() == mH.getLooper()) {
- handleConfigurationChanged(pendingConfig);
- } else {
- sendMessage(H.CONFIGURATION_CHANGED, pendingConfig);
- }
- }
}
/** Update VM state based on ActivityManager.PROCESS_STATE_* constants. */
@@ -5728,6 +5698,7 @@ public final class ActivityThread extends ClientTransactionHandler
return;
}
+ ActivityClient.getInstance().activityLocalRelaunch(r.token);
// Initialize a relaunch request.
final MergedConfiguration mergedConfiguration = new MergedConfiguration(
r.createdConfig != null
diff --git a/core/java/android/app/ActivityThreadInternal.java b/core/java/android/app/ActivityThreadInternal.java
index b9ad5c337813..72506b9fcdbb 100644
--- a/core/java/android/app/ActivityThreadInternal.java
+++ b/core/java/android/app/ActivityThreadInternal.java
@@ -32,8 +32,6 @@ interface ActivityThreadInternal {
boolean isInDensityCompatMode();
- boolean isCachedProcessState();
-
Application getApplication();
ArrayList<ComponentCallbacks2> collectComponentCallbacks(boolean includeUiContexts);
diff --git a/core/java/android/app/AppOpsManager.java b/core/java/android/app/AppOpsManager.java
index 3b1943bf86f6..cb64173b7809 100644
--- a/core/java/android/app/AppOpsManager.java
+++ b/core/java/android/app/AppOpsManager.java
@@ -1335,9 +1335,17 @@ public class AppOpsManager {
public static final int OP_ACCESS_RESTRICTED_SETTINGS =
AppProtoEnums.APP_OP_ACCESS_RESTRICTED_SETTINGS;
+ /**
+ * Receive microphone audio from an ambient sound detection event
+ *
+ * @hide
+ */
+ public static final int OP_RECEIVE_AMBIENT_TRIGGER_AUDIO =
+ AppProtoEnums.APP_OP_RECEIVE_AMBIENT_TRIGGER_AUDIO;
+
/** @hide */
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public static final int _NUM_OP = 120;
+ public static final int _NUM_OP = 121;
/** Access to coarse location information. */
public static final String OPSTR_COARSE_LOCATION = "android:coarse_location";
@@ -1800,6 +1808,14 @@ public class AppOpsManager {
public static final String OPSTR_ACCESS_RESTRICTED_SETTINGS =
"android:access_restricted_settings";
+ /**
+ * Receive microphone audio from an ambient sound detection event
+ *
+ * @hide
+ */
+ public static final String OPSTR_RECEIVE_AMBIENT_TRIGGER_AUDIO =
+ "android:receive_ambient_trigger_audio";
+
/** {@link #sAppOpsToNote} not initialized yet for this op */
private static final byte SHOULD_COLLECT_NOTE_OP_NOT_INITIALIZED = 0;
/** Should not collect noting of this app-op in {@link #sAppOpsToNote} */
@@ -2021,6 +2037,7 @@ public class AppOpsManager {
OP_ESTABLISH_VPN_SERVICE, // OP_ESTABLISH_VPN_SERVICE
OP_ESTABLISH_VPN_MANAGER, // OP_ESTABLISH_VPN_MANAGER
OP_ACCESS_RESTRICTED_SETTINGS, // OP_ACCESS_RESTRICTED_SETTINGS
+ OP_RECEIVE_AMBIENT_TRIGGER_AUDIO, // RECEIVE_SOUNDTRIGGER_AUDIO
};
/**
@@ -2147,6 +2164,7 @@ public class AppOpsManager {
OPSTR_ESTABLISH_VPN_SERVICE,
OPSTR_ESTABLISH_VPN_MANAGER,
OPSTR_ACCESS_RESTRICTED_SETTINGS,
+ OPSTR_RECEIVE_AMBIENT_TRIGGER_AUDIO,
};
/**
@@ -2274,6 +2292,7 @@ public class AppOpsManager {
"ESTABLISH_VPN_SERVICE",
"ESTABLISH_VPN_MANAGER",
"ACCESS_RESTRICTED_SETTINGS",
+ "RECEIVE_SOUNDTRIGGER_AUDIO",
};
/**
@@ -2402,6 +2421,7 @@ public class AppOpsManager {
null, // no permission for OP_ESTABLISH_VPN_SERVICE
null, // no permission for OP_ESTABLISH_VPN_MANAGER
null, // no permission for OP_ACCESS_RESTRICTED_SETTINGS,
+ null, // no permission for OP_RECEIVE_SOUNDTRIGGER_AUDIO
};
/**
@@ -2529,7 +2549,8 @@ public class AppOpsManager {
null, // NEARBY_WIFI_DEVICES
null, // ESTABLISH_VPN_SERVICE
null, // ESTABLISH_VPN_MANAGER
- null, // ACCESS_RESTRICTED_SETTINGS,
+ null, // ACCESS_RESTRICTED_SETTINGS
+ null, // RECEIVE_SOUNDTRIGGER_AUDIO
};
/**
@@ -2656,7 +2677,8 @@ public class AppOpsManager {
null, // NEARBY_WIFI_DEVICES
null, // ESTABLISH_VPN_SERVICE
null, // ESTABLISH_VPN_MANAGER
- null, // ACCESS_RESTRICTED_SETTINGS,
+ null, // ACCESS_RESTRICTED_SETTINGS
+ null, // RECEIVE_SOUNDTRIGGER_AUDIO
};
/**
@@ -2687,7 +2709,7 @@ public class AppOpsManager {
AppOpsManager.MODE_ALLOWED, // READ_ICC_SMS
AppOpsManager.MODE_ALLOWED, // WRITE_ICC_SMS
AppOpsManager.MODE_DEFAULT, // WRITE_SETTINGS
- AppOpsManager.MODE_DEFAULT, // SYSTEM_ALERT_WINDOW /*Overridden in opToDefaultMode()*/
+ getSystemAlertWindowDefault(), // SYSTEM_ALERT_WINDOW
AppOpsManager.MODE_ALLOWED, // ACCESS_NOTIFICATIONS
AppOpsManager.MODE_ALLOWED, // CAMERA
AppOpsManager.MODE_ALLOWED, // RECORD_AUDIO
@@ -2765,7 +2787,7 @@ public class AppOpsManager {
AppOpsManager.MODE_ERRORED, // OP_NO_ISOLATED_STORAGE
AppOpsManager.MODE_ALLOWED, // PHONE_CALL_MICROPHONE
AppOpsManager.MODE_ALLOWED, // PHONE_CALL_CAMERA
- AppOpsManager.MODE_ALLOWED, // OP_RECORD_AUDIO_HOTWORD
+ AppOpsManager.MODE_ALLOWED, // RECORD_AUDIO_HOTWORD
AppOpsManager.MODE_DEFAULT, // MANAGE_ONGOING_CALLS
AppOpsManager.MODE_DEFAULT, // MANAGE_CREDENTIALS
AppOpsManager.MODE_DEFAULT, // USE_ICC_AUTH_WITH_DEVICE_IDENTIFIER
@@ -2783,6 +2805,7 @@ public class AppOpsManager {
AppOpsManager.MODE_ALLOWED, // ESTABLISH_VPN_SERVICE
AppOpsManager.MODE_ALLOWED, // ESTABLISH_VPN_MANAGER
AppOpsManager.MODE_ALLOWED, // ACCESS_RESTRICTED_SETTINGS,
+ AppOpsManager.MODE_ALLOWED, // RECEIVE_SOUNDTRIGGER_AUDIO
};
/**
@@ -2913,6 +2936,7 @@ public class AppOpsManager {
false, // OP_ESTABLISH_VPN_SERVICE
false, // OP_ESTABLISH_VPN_MANAGER
true, // ACCESS_RESTRICTED_SETTINGS
+ false, // RECEIVE_SOUNDTRIGGER_AUDIO
};
/**
@@ -3040,6 +3064,7 @@ public class AppOpsManager {
false, // OP_ESTABLISH_VPN_SERVICE
false, // OP_ESTABLISH_VPN_MANAGER
true, // ACCESS_RESTRICTED_SETTINGS
+ false, // RECEIVE_SOUNDTRIGGER_AUDIO
};
/**
@@ -3138,8 +3163,6 @@ public class AppOpsManager {
private static final String DEBUG_LOGGING_OPS_PROP = "appops.logging_ops";
private static final String DEBUG_LOGGING_TAG = "AppOpsManager";
- private static volatile Integer sOpSystemAlertWindowDefaultMode;
-
/**
* Retrieve the op switch that controls the given operation.
* @hide
@@ -3238,9 +3261,6 @@ public class AppOpsManager {
* @hide
*/
public static @Mode int opToDefaultMode(int op) {
- if (op == OP_SYSTEM_ALERT_WINDOW) {
- return getSystemAlertWindowDefault();
- }
return sOpDefaultMode[op];
}
@@ -10258,11 +10278,6 @@ public class AppOpsManager {
}
private static int getSystemAlertWindowDefault() {
- // This is indeed racy but we aren't expecting the result to change so it's not worth
- // the synchronization.
- if (sOpSystemAlertWindowDefaultMode != null) {
- return sOpSystemAlertWindowDefaultMode;
- }
final Context context = ActivityThread.currentApplication();
if (context == null) {
return AppOpsManager.MODE_DEFAULT;
@@ -10273,11 +10288,10 @@ public class AppOpsManager {
// TVs are constantly plugged in and has less concern for memory/power
if (ActivityManager.isLowRamDeviceStatic()
&& !pm.hasSystemFeature(PackageManager.FEATURE_LEANBACK, 0)) {
- sOpSystemAlertWindowDefaultMode = AppOpsManager.MODE_IGNORED;
- } else {
- sOpSystemAlertWindowDefaultMode = AppOpsManager.MODE_DEFAULT;
+ return AppOpsManager.MODE_IGNORED;
}
- return sOpSystemAlertWindowDefaultMode;
+
+ return AppOpsManager.MODE_DEFAULT;
}
/**
diff --git a/core/java/android/app/ConfigurationController.java b/core/java/android/app/ConfigurationController.java
index 1a77b65c8ef6..18dc1ce18baf 100644
--- a/core/java/android/app/ConfigurationController.java
+++ b/core/java/android/app/ConfigurationController.java
@@ -124,12 +124,6 @@ class ConfigurationController {
* @param config The new configuration.
*/
void handleConfigurationChanged(@NonNull Configuration config) {
- if (mActivityThread.isCachedProcessState()) {
- updatePendingConfiguration(config);
- // If the process is in a cached state, delay the handling until the process is no
- // longer cached.
- return;
- }
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "configChanged");
handleConfigurationChanged(config, null /* compat */);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
diff --git a/core/java/android/app/ContextImpl.java b/core/java/android/app/ContextImpl.java
index ac46066997ff..6d982ced385c 100644
--- a/core/java/android/app/ContextImpl.java
+++ b/core/java/android/app/ContextImpl.java
@@ -1193,7 +1193,7 @@ class ContextImpl extends Context {
ActivityManager.getService().broadcastIntentWithFeature(
mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
null, Activity.RESULT_OK, null, null, null, null /*excludedPermissions=*/,
- AppOpsManager.OP_NONE, null, false, false, getUserId());
+ null, AppOpsManager.OP_NONE, null, false, false, getUserId());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -1210,7 +1210,7 @@ class ContextImpl extends Context {
ActivityManager.getService().broadcastIntentWithFeature(
mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
null, Activity.RESULT_OK, null, null, receiverPermissions,
- null /*excludedPermissions=*/, AppOpsManager.OP_NONE, null, false, false,
+ null /*excludedPermissions=*/, null, AppOpsManager.OP_NONE, null, false, false,
getUserId());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
@@ -1226,7 +1226,7 @@ class ContextImpl extends Context {
ActivityManager.getService().broadcastIntentWithFeature(
mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
null, Activity.RESULT_OK, null, null, receiverPermissions,
- null /*excludedPermissions=*/, AppOpsManager.OP_NONE, null, false, false,
+ null /*excludedPermissions=*/, null, AppOpsManager.OP_NONE, null, false, false,
getUserId());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
@@ -1243,8 +1243,8 @@ class ContextImpl extends Context {
ActivityManager.getService().broadcastIntentWithFeature(
mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
null, Activity.RESULT_OK, null, null, receiverPermissions,
- null /*excludedPermissions=*/, AppOpsManager.OP_NONE, options, false, false,
- getUserId());
+ null /*excludedPermissions=*/, null /*excludedPackages*/,
+ AppOpsManager.OP_NONE, options, false, false, getUserId());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -1259,7 +1259,7 @@ class ContextImpl extends Context {
ActivityManager.getService().broadcastIntentWithFeature(
mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
null, Activity.RESULT_OK, null, null, receiverPermissions,
- null /*excludedPermissions=*/, AppOpsManager.OP_NONE, null, false, false,
+ null /*excludedPermissions=*/, null, AppOpsManager.OP_NONE, null, false, false,
user.getIdentifier());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
@@ -1268,7 +1268,7 @@ class ContextImpl extends Context {
@Override
public void sendBroadcastMultiplePermissions(Intent intent, String[] receiverPermissions,
- String[] excludedPermissions) {
+ String[] excludedPermissions, String[] excludedPackages) {
warnIfCallingFromSystemProcess();
String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
try {
@@ -1276,7 +1276,7 @@ class ContextImpl extends Context {
ActivityManager.getService().broadcastIntentWithFeature(
mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
null, Activity.RESULT_OK, null, null, receiverPermissions, excludedPermissions,
- AppOpsManager.OP_NONE, null, false, false, getUserId());
+ excludedPackages, AppOpsManager.OP_NONE, null, false, false, getUserId());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -1303,7 +1303,7 @@ class ContextImpl extends Context {
ActivityManager.getService().broadcastIntentWithFeature(
mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
null, Activity.RESULT_OK, null, null, receiverPermissions,
- excludedPermissions, AppOpsManager.OP_NONE, options, false, false,
+ excludedPermissions, null, AppOpsManager.OP_NONE, options, false, false,
getUserId());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
@@ -1321,7 +1321,7 @@ class ContextImpl extends Context {
ActivityManager.getService().broadcastIntentWithFeature(
mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
null, Activity.RESULT_OK, null, null, receiverPermissions,
- null /*excludedPermissions=*/, appOp, null, false, false, getUserId());
+ null /*excludedPermissions=*/, null, appOp, null, false, false, getUserId());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -1338,7 +1338,7 @@ class ContextImpl extends Context {
ActivityManager.getService().broadcastIntentWithFeature(
mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
null, Activity.RESULT_OK, null, null, receiverPermissions,
- null /*excludedPermissions=*/, AppOpsManager.OP_NONE, null, true, false,
+ null /*excludedPermissions=*/, null, AppOpsManager.OP_NONE, null, true, false,
getUserId());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
@@ -1402,7 +1402,7 @@ class ContextImpl extends Context {
ActivityManager.getService().broadcastIntentWithFeature(
mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
rd, initialCode, initialData, initialExtras, receiverPermissions,
- null /*excludedPermissions=*/, appOp, options, true, false, getUserId());
+ null /*excludedPermissions=*/, null, appOp, options, true, false, getUserId());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -1416,7 +1416,7 @@ class ContextImpl extends Context {
ActivityManager.getService().broadcastIntentWithFeature(
mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
null, Activity.RESULT_OK, null, null, null, null /*excludedPermissions=*/,
- AppOpsManager.OP_NONE, null, false, false, user.getIdentifier());
+ null, AppOpsManager.OP_NONE, null, false, false, user.getIdentifier());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -1439,8 +1439,8 @@ class ContextImpl extends Context {
ActivityManager.getService().broadcastIntentWithFeature(
mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
null, Activity.RESULT_OK, null, null, receiverPermissions,
- null /*excludedPermissions=*/, AppOpsManager.OP_NONE, options, false, false,
- user.getIdentifier());
+ null /*excludedPermissions=*/, null, AppOpsManager.OP_NONE, options, false,
+ false, user.getIdentifier());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -1457,7 +1457,8 @@ class ContextImpl extends Context {
ActivityManager.getService().broadcastIntentWithFeature(
mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
null, Activity.RESULT_OK, null, null, receiverPermissions,
- null /*excludedPermissions=*/, appOp, null, false, false, user.getIdentifier());
+ null /*excludedPermissions=*/, null, appOp, null, false, false,
+ user.getIdentifier());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -1508,7 +1509,7 @@ class ContextImpl extends Context {
ActivityManager.getService().broadcastIntentWithFeature(
mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
rd, initialCode, initialData, initialExtras, receiverPermissions,
- null /*excludedPermissions=*/, appOp, options, true, false,
+ null /*excludedPermissions=*/, null, appOp, options, true, false,
user.getIdentifier());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
@@ -1550,7 +1551,7 @@ class ContextImpl extends Context {
ActivityManager.getService().broadcastIntentWithFeature(
mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
null, Activity.RESULT_OK, null, null, null, null /*excludedPermissions=*/,
- AppOpsManager.OP_NONE, null, false, true, getUserId());
+ null, AppOpsManager.OP_NONE, null, false, true, getUserId());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -1589,7 +1590,7 @@ class ContextImpl extends Context {
ActivityManager.getService().broadcastIntentWithFeature(
mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
null, Activity.RESULT_OK, null, null, null, null /*excludedPermissions=*/,
- AppOpsManager.OP_NONE, options, false, true, getUserId());
+ null, AppOpsManager.OP_NONE, options, false, true, getUserId());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -1625,7 +1626,7 @@ class ContextImpl extends Context {
ActivityManager.getService().broadcastIntentWithFeature(
mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
rd, initialCode, initialData, initialExtras, null,
- null /*excludedPermissions=*/, AppOpsManager.OP_NONE, null, true, true,
+ null /*excludedPermissions=*/, null, AppOpsManager.OP_NONE, null, true, true,
getUserId());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
@@ -1658,7 +1659,7 @@ class ContextImpl extends Context {
ActivityManager.getService().broadcastIntentWithFeature(
mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
null, Activity.RESULT_OK, null, null, null, null /*excludedPermissions=*/,
- AppOpsManager.OP_NONE, null, false, true, user.getIdentifier());
+ null, AppOpsManager.OP_NONE, null, false, true, user.getIdentifier());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -1673,7 +1674,7 @@ class ContextImpl extends Context {
ActivityManager.getService().broadcastIntentWithFeature(
mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
null, Activity.RESULT_OK, null, null, null, null /*excludedPermissions=*/,
- AppOpsManager.OP_NONE, options, false, true, user.getIdentifier());
+ null, AppOpsManager.OP_NONE, options, false, true, user.getIdentifier());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -1708,7 +1709,7 @@ class ContextImpl extends Context {
ActivityManager.getService().broadcastIntentWithFeature(
mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
rd, initialCode, initialData, initialExtras, null,
- null /*excludedPermissions=*/, AppOpsManager.OP_NONE, null, true, true,
+ null /*excludedPermissions=*/, null, AppOpsManager.OP_NONE, null, true, true,
user.getIdentifier());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
diff --git a/core/java/android/app/IActivityClientController.aidl b/core/java/android/app/IActivityClientController.aidl
index 130716122ed2..0138186974a6 100644
--- a/core/java/android/app/IActivityClientController.aidl
+++ b/core/java/android/app/IActivityClientController.aidl
@@ -53,6 +53,7 @@ interface IActivityClientController {
oneway void activityStopped(in IBinder token, in Bundle state,
in PersistableBundle persistentState, in CharSequence description);
oneway void activityDestroyed(in IBinder token);
+ oneway void activityLocalRelaunch(in IBinder token);
oneway void activityRelaunched(in IBinder token);
oneway void reportSizeConfigurations(in IBinder token,
diff --git a/core/java/android/app/IActivityManager.aidl b/core/java/android/app/IActivityManager.aidl
index 4efe9dfe7185..8367441b1b95 100644
--- a/core/java/android/app/IActivityManager.aidl
+++ b/core/java/android/app/IActivityManager.aidl
@@ -141,7 +141,7 @@ interface IActivityManager {
int broadcastIntentWithFeature(in IApplicationThread caller, in String callingFeatureId,
in Intent intent, in String resolvedType, in IIntentReceiver resultTo, int resultCode,
in String resultData, in Bundle map, in String[] requiredPermissions, in String[] excludePermissions,
- int appOp, in Bundle options, boolean serialized, boolean sticky, int userId);
+ in String[] excludePackages, int appOp, in Bundle options, boolean serialized, boolean sticky, int userId);
void unbroadcastIntent(in IApplicationThread caller, in Intent intent, int userId);
@UnsupportedAppUsage
oneway void finishReceiver(in IBinder who, int resultCode, in String resultData, in Bundle map,
diff --git a/core/java/android/app/INotificationManager.aidl b/core/java/android/app/INotificationManager.aidl
index df9f2a3cbb25..da6a551175e3 100644
--- a/core/java/android/app/INotificationManager.aidl
+++ b/core/java/android/app/INotificationManager.aidl
@@ -77,6 +77,7 @@ interface INotificationManager
boolean areNotificationsEnabledForPackage(String pkg, int uid);
boolean areNotificationsEnabled(String pkg);
int getPackageImportance(String pkg);
+ boolean isImportanceLocked(String pkg, int uid);
List<String> getAllowedAssistantAdjustments(String pkg);
void allowAssistantAdjustment(String adjustmentType);
diff --git a/core/java/android/app/NotificationChannel.java b/core/java/android/app/NotificationChannel.java
index 6f0b03aeb6f3..c9cc1a179102 100644
--- a/core/java/android/app/NotificationChannel.java
+++ b/core/java/android/app/NotificationChannel.java
@@ -253,7 +253,6 @@ public final class NotificationChannel implements Parcelable {
// If this is a blockable system notification channel.
private boolean mBlockableSystem = false;
private int mAllowBubbles = DEFAULT_ALLOW_BUBBLE;
- private boolean mImportanceLockedByOEM;
private boolean mImportanceLockedDefaultApp;
private String mParentId = null;
private String mConversationId = null;
@@ -322,13 +321,13 @@ public final class NotificationChannel implements Parcelable {
mLightColor = in.readInt();
mBlockableSystem = in.readBoolean();
mAllowBubbles = in.readInt();
- mImportanceLockedByOEM = in.readBoolean();
mOriginalImportance = in.readInt();
mParentId = in.readString();
mConversationId = in.readString();
mDemoted = in.readBoolean();
mImportantConvo = in.readBoolean();
mDeletedTime = in.readLong();
+ mImportanceLockedDefaultApp = in.readBoolean();
}
@Override
@@ -382,13 +381,13 @@ public final class NotificationChannel implements Parcelable {
dest.writeInt(mLightColor);
dest.writeBoolean(mBlockableSystem);
dest.writeInt(mAllowBubbles);
- dest.writeBoolean(mImportanceLockedByOEM);
dest.writeInt(mOriginalImportance);
dest.writeString(mParentId);
dest.writeString(mConversationId);
dest.writeBoolean(mDemoted);
dest.writeBoolean(mImportantConvo);
dest.writeLong(mDeletedTime);
+ dest.writeBoolean(mImportanceLockedDefaultApp);
}
/**
@@ -851,14 +850,6 @@ public final class NotificationChannel implements Parcelable {
* @hide
*/
@TestApi
- public void setImportanceLockedByOEM(boolean locked) {
- mImportanceLockedByOEM = locked;
- }
-
- /**
- * @hide
- */
- @TestApi
public void setImportanceLockedByCriticalDeviceFunction(boolean locked) {
mImportanceLockedDefaultApp = locked;
}
@@ -1107,8 +1098,8 @@ public final class NotificationChannel implements Parcelable {
out.attributeBoolean(null, ATT_IMP_CONVERSATION, isImportantConversation());
}
- // mImportanceLockedDefaultApp and mImportanceLockedByOEM have a different source of
- // truth and so aren't written to this xml file
+ // mImportanceLockedDefaultApp has a different source of truth and so isn't written to
+ // this xml file
out.endTag(null, TAG_CHANNEL);
}
@@ -1251,7 +1242,6 @@ public final class NotificationChannel implements Parcelable {
&& Arrays.equals(mVibration, that.mVibration)
&& Objects.equals(getGroup(), that.getGroup())
&& Objects.equals(getAudioAttributes(), that.getAudioAttributes())
- && mImportanceLockedByOEM == that.mImportanceLockedByOEM
&& mImportanceLockedDefaultApp == that.mImportanceLockedDefaultApp
&& mOriginalImportance == that.mOriginalImportance
&& Objects.equals(getParentChannelId(), that.getParentChannelId())
@@ -1267,7 +1257,7 @@ public final class NotificationChannel implements Parcelable {
getUserLockedFields(),
isFgServiceShown(), mVibrationEnabled, mShowBadge, isDeleted(), getDeletedTimeMs(),
getGroup(), getAudioAttributes(), isBlockable(), mAllowBubbles,
- mImportanceLockedByOEM, mImportanceLockedDefaultApp, mOriginalImportance,
+ mImportanceLockedDefaultApp, mOriginalImportance,
mParentId, mConversationId, mDemoted, mImportantConvo);
result = 31 * result + Arrays.hashCode(mVibration);
return result;
@@ -1312,7 +1302,6 @@ public final class NotificationChannel implements Parcelable {
+ ", mAudioAttributes=" + mAudioAttributes
+ ", mBlockableSystem=" + mBlockableSystem
+ ", mAllowBubbles=" + mAllowBubbles
- + ", mImportanceLockedByOEM=" + mImportanceLockedByOEM
+ ", mImportanceLockedDefaultApp=" + mImportanceLockedDefaultApp
+ ", mOriginalImp=" + mOriginalImportance
+ ", mParent=" + mParentId
diff --git a/core/java/android/app/ResourcesManager.java b/core/java/android/app/ResourcesManager.java
index 2a1883d5e0bb..d275c8336251 100644
--- a/core/java/android/app/ResourcesManager.java
+++ b/core/java/android/app/ResourcesManager.java
@@ -365,8 +365,8 @@ public class ResourcesManager {
@NonNull Configuration config) {
config.touchscreen = Configuration.TOUCHSCREEN_NOTOUCH;
config.densityDpi = dm.densityDpi;
- config.screenWidthDp = (int) (dm.widthPixels / dm.density);
- config.screenHeightDp = (int) (dm.heightPixels / dm.density);
+ config.screenWidthDp = (int) (dm.widthPixels / dm.density + 0.5f);
+ config.screenHeightDp = (int) (dm.heightPixels / dm.density + 0.5f);
int sl = Configuration.resetScreenLayout(config.screenLayout);
if (dm.widthPixels > dm.heightPixels) {
config.orientation = Configuration.ORIENTATION_LANDSCAPE;
diff --git a/core/java/android/app/admin/DevicePolicyManager.java b/core/java/android/app/admin/DevicePolicyManager.java
index 0a2b42121545..8647b9a2967c 100644
--- a/core/java/android/app/admin/DevicePolicyManager.java
+++ b/core/java/android/app/admin/DevicePolicyManager.java
@@ -11210,7 +11210,9 @@ public class DevicePolicyManager {
* for enterprise use.
*
* An example of a supported preferential network service is the Enterprise
- * slice on 5G networks.
+ * slice on 5G networks. For devices on 4G networks, the profile owner needs to additionally
+ * configure enterprise APN to set up data call for the preferential network service.
+ * These APNs can be added using {@link #addOverrideApn}.
*
* By default, preferential network service is disabled on the work profile and
* fully managed devices, on supported carriers and devices.
@@ -11260,7 +11262,9 @@ public class DevicePolicyManager {
* {@see PreferentialNetworkServiceConfig}
*
* An example of a supported preferential network service is the Enterprise
- * slice on 5G networks.
+ * slice on 5G networks. For devices on 4G networks, the profile owner needs to additionally
+ * configure enterprise APN to set up data call for the preferential network service.
+ * These APNs can be added using {@link #addOverrideApn}.
*
* By default, preferential network service is disabled on the work profile and fully managed
* devices, on supported carriers and devices. Admins can explicitly enable it with this API.
@@ -13782,18 +13786,13 @@ public class DevicePolicyManager {
}
/**
- * Called by device owner or profile owner to add an override APN.
+ * Called by device owner or managed profile owner to add an override APN.
*
* <p>This method may returns {@code -1} if {@code apnSetting} conflicts with an existing
* override APN. Update the existing conflicted APN with
* {@link #updateOverrideApn(ComponentName, int, ApnSetting)} instead of adding a new entry.
* <p>Two override APNs are considered to conflict when all the following APIs return
* the same values on both override APNs:
- * <p> Before Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
- * Only device owners can add APNs.
- * <p> Starting from Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
- * Device and profile owners can add enterprise APNs
- * ({@link ApnSetting#TYPE_ENTERPRISE}), while only device owners can add other type of APNs.
* <ul>
* <li>{@link ApnSetting#getOperatorNumeric()}</li>
* <li>{@link ApnSetting#getApnName()}</li>
@@ -13808,6 +13807,15 @@ public class DevicePolicyManager {
* <li>{@link ApnSetting#getRoamingProtocol()}</li>
* </ul>
*
+ * <p> Before Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
+ * Only device owners can add APNs.
+ * <p> Starting from Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
+ * Both device owners and managed profile owners can add enterprise APNs
+ * ({@link ApnSetting#TYPE_ENTERPRISE}), while only device owners can add other type of APNs.
+ * Enterprise APNs are specific to the managed profile and do not override any user-configured
+ * VPNs. They are prerequisites for enabling preferential network service on the managed
+ * profile on 4G networks ({@link #setPreferentialNetworkServiceConfigs}).
+ *
* @param admin which {@link DeviceAdminReceiver} this request is associated with
* @param apnSetting the override APN to insert
* @return The {@code id} of inserted override APN. Or {@code -1} when failed to insert into
@@ -13830,7 +13838,7 @@ public class DevicePolicyManager {
}
/**
- * Called by device owner or profile owner to update an override APN.
+ * Called by device owner or managed profile owner to update an override APN.
*
* <p>This method may returns {@code false} if there is no override APN with the given
* {@code apnId}.
@@ -13840,7 +13848,7 @@ public class DevicePolicyManager {
* <p> Before Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
* Only device owners can update APNs.
* <p> Starting from Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
- * Device and profile owners can update enterprise APNs
+ * Both device owners and managed profile owners can update enterprise APNs
* ({@link ApnSetting#TYPE_ENTERPRISE}), while only device owners can update other type of APNs.
*
* @param admin which {@link DeviceAdminReceiver} this request is associated with
@@ -13867,14 +13875,14 @@ public class DevicePolicyManager {
}
/**
- * Called by device owner or profile owner to remove an override APN.
+ * Called by device owner or managed profile owner to remove an override APN.
*
* <p>This method may returns {@code false} if there is no override APN with the given
* {@code apnId}.
* <p> Before Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
* Only device owners can remove APNs.
* <p> Starting from Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
- * Device and profile owners can remove enterprise APNs
+ * Both device owners and managed profile owners can remove enterprise APNs
* ({@link ApnSetting#TYPE_ENTERPRISE}), while only device owners can remove other type of APNs.
*
* @param admin which {@link DeviceAdminReceiver} this request is associated with
@@ -13899,7 +13907,8 @@ public class DevicePolicyManager {
}
/**
- * Called by device owner to get all override APNs inserted by device owner.
+ * Called by device owner or managed profile owner to get all override APNs inserted by
+ * device owner or managed profile owner previously using {@link #addOverrideApn}.
*
* @param admin which {@link DeviceAdminReceiver} this request is associated with
* @return A list of override APNs inserted by device owner.
@@ -13924,6 +13933,9 @@ public class DevicePolicyManager {
* <p> Override APNs are separated from other APNs on the device, and can only be inserted or
* modified by the device owner. When enabled, only override APNs are in use, any other APNs
* are ignored.
+ * <p>Note: Enterprise APNs added by managed profile owners do not need to be enabled by
+ * this API. They are part of the preferential network service config and is controlled by
+ * {@link #setPreferentialNetworkServiceConfigs}.
*
* @param admin which {@link DeviceAdminReceiver} this request is associated with
* @param enabled {@code true} if override APNs should be enabled, {@code false} otherwise
@@ -14569,12 +14581,13 @@ public class DevicePolicyManager {
}
/**
- * Called by Device owner to disable user control over apps. User will not be able to clear
- * app data or force-stop packages.
+ * Called by a device owner or a profile owner to disable user control over apps. User will not
+ * be able to clear app data or force-stop packages. When called by a device owner, applies to
+ * all users on the device.
*
* @param admin which {@link DeviceAdminReceiver} this request is associated with
* @param packages The package names for the apps.
- * @throws SecurityException if {@code admin} is not a device owner.
+ * @throws SecurityException if {@code admin} is not a device owner or a profile owner.
*/
public void setUserControlDisabledPackages(@NonNull ComponentName admin,
@NonNull List<String> packages) {
@@ -14589,12 +14602,14 @@ public class DevicePolicyManager {
}
/**
- * Returns the list of packages over which user control is disabled by the device owner.
+ * Returns the list of packages over which user control is disabled by a device or profile
+ * owner.
*
* @param admin which {@link DeviceAdminReceiver} this request is associated with
- * @throws SecurityException if {@code admin} is not a device owner.
+ * @throws SecurityException if {@code admin} is not a device or profile owner.
*/
- public @NonNull List<String> getUserControlDisabledPackages(@NonNull ComponentName admin) {
+ @NonNull
+ public List<String> getUserControlDisabledPackages(@NonNull ComponentName admin) {
throwIfParentInstance("getUserControlDisabledPackages");
if (mService != null) {
try {
diff --git a/core/java/android/app/admin/DevicePolicyResources.java b/core/java/android/app/admin/DevicePolicyResources.java
index c8033fafbc4e..11b840fd4ad4 100644
--- a/core/java/android/app/admin/DevicePolicyResources.java
+++ b/core/java/android/app/admin/DevicePolicyResources.java
@@ -184,6 +184,12 @@ public final class DevicePolicyResources {
PREFIX + "WORK_PROFILE_IT_ADMIN_CANT_RESET_SCREEN_LOCK";
/**
+ * Text shown on the CTA link shown to user to set a separate lock for work apps
+ */
+ public static final String WORK_PROFILE_IT_ADMIN_CANT_RESET_SCREEN_LOCK_ACTION =
+ PREFIX + "WORK_PROFILE_IT_ADMIN_CANT_RESET_SCREEN_LOCK_ACTION";
+
+ /**
* Message shown in screen lock picker for setting up a work profile screen lock
*/
public static final String WORK_PROFILE_SCREEN_LOCK_SETUP_MESSAGE =
@@ -1492,6 +1498,45 @@ public final class DevicePolicyResources {
* Content description for the work profile lock screen.
*/
public static final String WORK_LOCK_ACCESSIBILITY = PREFIX + "WORK_LOCK_ACCESSIBILITY";
+
+ /**
+ * Notification text displayed when screenshots are blocked by an IT admin.
+ */
+ public static final String SCREENSHOT_BLOCKED_BY_ADMIN =
+ PREFIX + "SCREENSHOT_BLOCKED_BY_ADMIN";
+
+ /**
+ * Message shown when user is almost at the limit of password attempts where the
+ * profile will be removed. Accepts number of failed attempts and remaining failed
+ * attempts as params.
+ */
+ public static final String KEYGUARD_DIALOG_FAILED_ATTEMPTS_ALMOST_ERASING_PROFILE =
+ PREFIX + "KEYGUARD_DIALOG_FAILED_ATTEMPTS_ALMOST_ERASING_PROFILE";
+
+ /**
+ * Message shown in dialog when user has exceeded the maximum attempts and the profile
+ * will be removed. Accepts number of failed attempts as a param.
+ */
+ public static final String KEYGUARD_DIALOG_FAILED_ATTEMPTS_ERASING_PROFILE =
+ PREFIX + "KEYGUARD_DIALOG_FAILED_ATTEMPTS_ERASING_PROFILE";
+
+ /**
+ * Monitoring dialog subtitle for the section describing VPN.
+ */
+ public static final String QS_DIALOG_MONITORING_VPN_SUBTITLE =
+ PREFIX + "QS_DIALOG_MONITORING_VPN_SUBTITLE";
+
+ /**
+ * Monitoring dialog subtitle for the section describing network logging.
+ */
+ public static final String QS_DIALOG_MONITORING_NETWORK_SUBTITLE =
+ PREFIX + "QS_DIALOG_MONITORING_NETWORK_SUBTITLE";
+
+ /**
+ * Monitoring dialog subtitle for the section describing certificate authorities.
+ */
+ public static final String QS_DIALOG_MONITORING_CA_CERT_SUBTITLE =
+ PREFIX + "QS_DIALOG_MONITORING_CA_CERT_SUBTITLE";
}
/**
diff --git a/core/java/android/app/admin/DevicePolicyResourcesManager.java b/core/java/android/app/admin/DevicePolicyResourcesManager.java
index e8eb792f7fd7..2cc189f87ced 100644
--- a/core/java/android/app/admin/DevicePolicyResourcesManager.java
+++ b/core/java/android/app/admin/DevicePolicyResourcesManager.java
@@ -26,6 +26,7 @@ import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.Icon;
import android.os.RemoteException;
+import android.provider.DeviceConfig;
import android.util.DisplayMetrics;
import android.util.Log;
@@ -40,6 +41,9 @@ import java.util.function.Supplier;
public class DevicePolicyResourcesManager {
private static String TAG = "DevicePolicyResourcesManager";
+ private static String DISABLE_RESOURCES_UPDATABILITY_FLAG = "disable_resources_updatability";
+ private static boolean DEFAULT_DISABLE_RESOURCES_UPDATABILITY = false;
+
private final Context mContext;
private final IDevicePolicyManager mService;
@@ -194,16 +198,20 @@ public class DevicePolicyResourcesManager {
Objects.requireNonNull(drawableSource, "drawableSource can't be null");
Objects.requireNonNull(defaultDrawableLoader, "defaultDrawableLoader can't be null");
- if (drawableId.equals(DevicePolicyResources.UNDEFINED)) {
+ if (drawableId.equals(DevicePolicyResources.UNDEFINED)
+ || DeviceConfig.getBoolean(
+ DeviceConfig.NAMESPACE_DEVICE_POLICY_MANAGER,
+ DISABLE_RESOURCES_UPDATABILITY_FLAG,
+ DEFAULT_DISABLE_RESOURCES_UPDATABILITY)) {
return ParcelableResource.loadDefaultDrawable(defaultDrawableLoader);
}
+
if (mService != null) {
try {
ParcelableResource resource = mService.getDrawable(
drawableId, drawableStyle, drawableSource);
if (resource == null) {
- return ParcelableResource.loadDefaultDrawable(
- defaultDrawableLoader);
+ return ParcelableResource.loadDefaultDrawable(defaultDrawableLoader);
}
return resource.getDrawable(
mContext,
@@ -287,16 +295,20 @@ public class DevicePolicyResourcesManager {
Objects.requireNonNull(drawableSource, "drawableSource can't be null");
Objects.requireNonNull(defaultDrawableLoader, "defaultDrawableLoader can't be null");
- if (drawableId.equals(DevicePolicyResources.UNDEFINED)) {
+ if (drawableId.equals(DevicePolicyResources.UNDEFINED)
+ || DeviceConfig.getBoolean(
+ DeviceConfig.NAMESPACE_DEVICE_POLICY_MANAGER,
+ DISABLE_RESOURCES_UPDATABILITY_FLAG,
+ DEFAULT_DISABLE_RESOURCES_UPDATABILITY)) {
return ParcelableResource.loadDefaultDrawable(defaultDrawableLoader);
}
+
if (mService != null) {
try {
ParcelableResource resource = mService.getDrawable(
drawableId, drawableStyle, drawableSource);
if (resource == null) {
- return ParcelableResource.loadDefaultDrawable(
- defaultDrawableLoader);
+ return ParcelableResource.loadDefaultDrawable(defaultDrawableLoader);
}
return resource.getDrawable(mContext, density, defaultDrawableLoader);
} catch (RemoteException e) {
@@ -330,9 +342,14 @@ public class DevicePolicyResourcesManager {
Objects.requireNonNull(drawableSource, "drawableSource can't be null");
Objects.requireNonNull(defaultIcon, "defaultIcon can't be null");
- if (drawableId.equals(DevicePolicyResources.UNDEFINED)) {
+ if (drawableId.equals(DevicePolicyResources.UNDEFINED)
+ || DeviceConfig.getBoolean(
+ DeviceConfig.NAMESPACE_DEVICE_POLICY_MANAGER,
+ DISABLE_RESOURCES_UPDATABILITY_FLAG,
+ DEFAULT_DISABLE_RESOURCES_UPDATABILITY)) {
return defaultIcon;
}
+
if (mService != null) {
try {
ParcelableResource resource = mService.getDrawable(
@@ -463,7 +480,10 @@ public class DevicePolicyResourcesManager {
Objects.requireNonNull(stringId, "stringId can't be null");
Objects.requireNonNull(defaultStringLoader, "defaultStringLoader can't be null");
- if (stringId.equals(DevicePolicyResources.UNDEFINED)) {
+ if (stringId.equals(DevicePolicyResources.UNDEFINED) || DeviceConfig.getBoolean(
+ DeviceConfig.NAMESPACE_DEVICE_POLICY_MANAGER,
+ DISABLE_RESOURCES_UPDATABILITY_FLAG,
+ DEFAULT_DISABLE_RESOURCES_UPDATABILITY)) {
return ParcelableResource.loadDefaultString(defaultStringLoader);
}
if (mService != null) {
@@ -508,7 +528,10 @@ public class DevicePolicyResourcesManager {
Objects.requireNonNull(stringId, "stringId can't be null");
Objects.requireNonNull(defaultStringLoader, "defaultStringLoader can't be null");
- if (stringId.equals(DevicePolicyResources.UNDEFINED)) {
+ if (stringId.equals(DevicePolicyResources.UNDEFINED) || DeviceConfig.getBoolean(
+ DeviceConfig.NAMESPACE_DEVICE_POLICY_MANAGER,
+ DISABLE_RESOURCES_UPDATABILITY_FLAG,
+ DEFAULT_DISABLE_RESOURCES_UPDATABILITY)) {
return ParcelableResource.loadDefaultString(defaultStringLoader);
}
if (mService != null) {
diff --git a/core/java/android/app/backup/BackupTransport.java b/core/java/android/app/backup/BackupTransport.java
index 9bb048d7a75f..f6de72b43de6 100644
--- a/core/java/android/app/backup/BackupTransport.java
+++ b/core/java/android/app/backup/BackupTransport.java
@@ -665,184 +665,292 @@ public class BackupTransport {
@Override
public void name(AndroidFuture<String> resultFuture) throws RemoteException {
- String result = BackupTransport.this.name();
- resultFuture.complete(result);
+ try {
+ String result = BackupTransport.this.name();
+ resultFuture.complete(result);
+ } catch (RuntimeException e) {
+ resultFuture.cancel(/* mayInterruptIfRunning */ true);
+ }
}
@Override
public void configurationIntent(AndroidFuture<Intent> resultFuture)
throws RemoteException {
- Intent result = BackupTransport.this.configurationIntent();
- resultFuture.complete(result);
+ try {
+ Intent result = BackupTransport.this.configurationIntent();
+ resultFuture.complete(result);
+ } catch (RuntimeException e) {
+ resultFuture.cancel(/* mayInterruptIfRunning */ true);
+ }
}
@Override
public void currentDestinationString(AndroidFuture<String> resultFuture)
throws RemoteException {
- String result = BackupTransport.this.currentDestinationString();
- resultFuture.complete(result);
+ try {
+ String result = BackupTransport.this.currentDestinationString();
+ resultFuture.complete(result);
+ } catch (RuntimeException e) {
+ resultFuture.cancel(/* mayInterruptIfRunning */ true);
+ }
}
@Override
public void dataManagementIntent(AndroidFuture<Intent> resultFuture)
throws RemoteException {
- Intent result = BackupTransport.this.dataManagementIntent();
- resultFuture.complete(result);
+ try {
+ Intent result = BackupTransport.this.dataManagementIntent();
+ resultFuture.complete(result);
+ } catch (RuntimeException e) {
+ resultFuture.cancel(/* mayInterruptIfRunning */ true);
+ }
}
@Override
public void dataManagementIntentLabel(AndroidFuture<CharSequence> resultFuture)
throws RemoteException {
- CharSequence result = BackupTransport.this.dataManagementIntentLabel();
- resultFuture.complete(result);
+ try {
+ CharSequence result = BackupTransport.this.dataManagementIntentLabel();
+ resultFuture.complete(result);
+ } catch (RuntimeException e) {
+ resultFuture.cancel(/* mayInterruptIfRunning */ true);
+ }
}
@Override
public void transportDirName(AndroidFuture<String> resultFuture) throws RemoteException {
- String result = BackupTransport.this.transportDirName();
- resultFuture.complete(result);
+ try {
+ String result = BackupTransport.this.transportDirName();
+ resultFuture.complete(result);
+ } catch (RuntimeException e) {
+ resultFuture.cancel(/* mayInterruptIfRunning */ true);
+ }
}
@Override
public void requestBackupTime(AndroidFuture<Long> resultFuture) throws RemoteException {
- long result = BackupTransport.this.requestBackupTime();
- resultFuture.complete(result);
+ try {
+ long result = BackupTransport.this.requestBackupTime();
+ resultFuture.complete(result);
+ } catch (RuntimeException e) {
+ resultFuture.cancel(/* mayInterruptIfRunning */ true);
+ }
}
@Override
public void initializeDevice(ITransportStatusCallback callback) throws RemoteException {
- int result = BackupTransport.this.initializeDevice();
- callback.onOperationCompleteWithStatus(result);
+ try {
+ int result = BackupTransport.this.initializeDevice();
+ callback.onOperationCompleteWithStatus(result);
+ } catch (RuntimeException e) {
+ callback.onOperationCompleteWithStatus(BackupTransport.TRANSPORT_ERROR);
+ }
}
@Override
public void performBackup(PackageInfo packageInfo, ParcelFileDescriptor inFd, int flags,
ITransportStatusCallback callback) throws RemoteException {
- int result = BackupTransport.this.performBackup(packageInfo, inFd, flags);
- callback.onOperationCompleteWithStatus(result);
+ try {
+ int result = BackupTransport.this.performBackup(packageInfo, inFd, flags);
+ callback.onOperationCompleteWithStatus(result);
+ } catch (RuntimeException e) {
+ callback.onOperationCompleteWithStatus(BackupTransport.TRANSPORT_ERROR);
+ }
}
@Override
public void clearBackupData(PackageInfo packageInfo, ITransportStatusCallback callback)
throws RemoteException {
- int result = BackupTransport.this.clearBackupData(packageInfo);
- callback.onOperationCompleteWithStatus(result);
+ try {
+ int result = BackupTransport.this.clearBackupData(packageInfo);
+ callback.onOperationCompleteWithStatus(result);
+ } catch (RuntimeException e) {
+ callback.onOperationCompleteWithStatus(BackupTransport.TRANSPORT_ERROR);
+ }
}
@Override
public void finishBackup(ITransportStatusCallback callback) throws RemoteException {
- int result = BackupTransport.this.finishBackup();
- callback.onOperationCompleteWithStatus(result);
+ try {
+ int result = BackupTransport.this.finishBackup();
+ callback.onOperationCompleteWithStatus(result);
+ } catch (RuntimeException e) {
+ callback.onOperationCompleteWithStatus(BackupTransport.TRANSPORT_ERROR);
+ }
}
@Override
public void getAvailableRestoreSets(AndroidFuture<List<RestoreSet>> resultFuture)
throws RemoteException {
- RestoreSet[] result = BackupTransport.this.getAvailableRestoreSets();
- resultFuture.complete(Arrays.asList(result));
+ try {
+ RestoreSet[] result = BackupTransport.this.getAvailableRestoreSets();
+ resultFuture.complete(Arrays.asList(result));
+ } catch (RuntimeException e) {
+ resultFuture.cancel(/* mayInterruptIfRunning */ true);
+ }
}
@Override
public void getCurrentRestoreSet(AndroidFuture<Long> resultFuture)
throws RemoteException {
- long result = BackupTransport.this.getCurrentRestoreSet();
- resultFuture.complete(result);
+ try {
+ long result = BackupTransport.this.getCurrentRestoreSet();
+ resultFuture.complete(result);
+ } catch (RuntimeException e) {
+ resultFuture.cancel(/* mayInterruptIfRunning */ true);
+ }
}
@Override
public void startRestore(long token, PackageInfo[] packages,
ITransportStatusCallback callback) throws RemoteException {
- int result = BackupTransport.this.startRestore(token, packages);
- callback.onOperationCompleteWithStatus(result);
+ try {
+ int result = BackupTransport.this.startRestore(token, packages);
+ callback.onOperationCompleteWithStatus(result);
+ } catch (RuntimeException e) {
+ callback.onOperationCompleteWithStatus(BackupTransport.TRANSPORT_ERROR);
+ }
}
@Override
public void nextRestorePackage(AndroidFuture<RestoreDescription> resultFuture)
throws RemoteException {
- RestoreDescription result = BackupTransport.this.nextRestorePackage();
- resultFuture.complete(result);
+ try {
+ RestoreDescription result = BackupTransport.this.nextRestorePackage();
+ resultFuture.complete(result);
+ } catch (RuntimeException e) {
+ resultFuture.cancel(/* mayInterruptIfRunning */ true);
+ }
}
@Override
public void getRestoreData(ParcelFileDescriptor outFd,
ITransportStatusCallback callback) throws RemoteException {
- int result = BackupTransport.this.getRestoreData(outFd);
- callback.onOperationCompleteWithStatus(result);
+ try {
+ int result = BackupTransport.this.getRestoreData(outFd);
+ callback.onOperationCompleteWithStatus(result);
+ } catch (RuntimeException e) {
+ callback.onOperationCompleteWithStatus(BackupTransport.TRANSPORT_ERROR);
+ }
}
@Override
public void finishRestore(ITransportStatusCallback callback)
throws RemoteException {
- BackupTransport.this.finishRestore();
- callback.onOperationComplete();
+ try {
+ BackupTransport.this.finishRestore();
+ callback.onOperationComplete();
+ } catch (RuntimeException e) {
+ callback.onOperationCompleteWithStatus(BackupTransport.TRANSPORT_ERROR);
+ }
}
@Override
public void requestFullBackupTime(AndroidFuture<Long> resultFuture)
throws RemoteException {
- long result = BackupTransport.this.requestFullBackupTime();
- resultFuture.complete(result);
+ try {
+ long result = BackupTransport.this.requestFullBackupTime();
+ resultFuture.complete(result);
+ } catch (RuntimeException e) {
+ resultFuture.cancel(/* mayInterruptIfRunning */ true);
+ }
}
@Override
public void performFullBackup(PackageInfo targetPackage, ParcelFileDescriptor socket,
int flags, ITransportStatusCallback callback) throws RemoteException {
- int result = BackupTransport.this.performFullBackup(targetPackage, socket, flags);
- callback.onOperationCompleteWithStatus(result);
+ try {
+ int result = BackupTransport.this.performFullBackup(targetPackage, socket, flags);
+ callback.onOperationCompleteWithStatus(result);
+ } catch (RuntimeException e) {
+ callback.onOperationCompleteWithStatus(BackupTransport.TRANSPORT_ERROR);
+ }
}
@Override
public void checkFullBackupSize(long size, ITransportStatusCallback callback)
throws RemoteException {
- int result = BackupTransport.this.checkFullBackupSize(size);
- callback.onOperationCompleteWithStatus(result);
+ try {
+ int result = BackupTransport.this.checkFullBackupSize(size);
+ callback.onOperationCompleteWithStatus(result);
+ } catch (RuntimeException e) {
+ callback.onOperationCompleteWithStatus(BackupTransport.TRANSPORT_ERROR);
+ }
}
@Override
public void sendBackupData(int numBytes, ITransportStatusCallback callback)
throws RemoteException {
- int result = BackupTransport.this.sendBackupData(numBytes);
- callback.onOperationCompleteWithStatus(result);
+ try {
+ int result = BackupTransport.this.sendBackupData(numBytes);
+ callback.onOperationCompleteWithStatus(result);
+ } catch (RuntimeException e) {
+ callback.onOperationCompleteWithStatus(BackupTransport.TRANSPORT_ERROR);
+ }
}
@Override
public void cancelFullBackup(ITransportStatusCallback callback) throws RemoteException {
- BackupTransport.this.cancelFullBackup();
- callback.onOperationComplete();
+ try {
+ BackupTransport.this.cancelFullBackup();
+ callback.onOperationComplete();
+ } catch (RuntimeException e) {
+ callback.onOperationCompleteWithStatus(BackupTransport.TRANSPORT_ERROR);
+ }
}
@Override
public void isAppEligibleForBackup(PackageInfo targetPackage, boolean isFullBackup,
AndroidFuture<Boolean> resultFuture) throws RemoteException {
- boolean result = BackupTransport.this.isAppEligibleForBackup(targetPackage,
- isFullBackup);
- resultFuture.complete(result);
+ try {
+ boolean result = BackupTransport.this.isAppEligibleForBackup(targetPackage,
+ isFullBackup);
+ resultFuture.complete(result);
+ } catch (RuntimeException e) {
+ resultFuture.cancel(/* mayInterruptIfRunning */ true);
+ }
}
@Override
public void getBackupQuota(String packageName, boolean isFullBackup,
AndroidFuture<Long> resultFuture) throws RemoteException {
- long result = BackupTransport.this.getBackupQuota(packageName, isFullBackup);
- resultFuture.complete(result);
+ try {
+ long result = BackupTransport.this.getBackupQuota(packageName, isFullBackup);
+ resultFuture.complete(result);
+ } catch (RuntimeException e) {
+ resultFuture.cancel(/* mayInterruptIfRunning */ true);
+ }
}
@Override
public void getTransportFlags(AndroidFuture<Integer> resultFuture) throws RemoteException {
- int result = BackupTransport.this.getTransportFlags();
- resultFuture.complete(result);
+ try {
+ int result = BackupTransport.this.getTransportFlags();
+ resultFuture.complete(result);
+ } catch (RuntimeException e) {
+ resultFuture.cancel(/* mayInterruptIfRunning */ true);
+ }
}
@Override
public void getNextFullRestoreDataChunk(ParcelFileDescriptor socket,
ITransportStatusCallback callback) throws RemoteException {
- int result = BackupTransport.this.getNextFullRestoreDataChunk(socket);
- callback.onOperationCompleteWithStatus(result);
+ try {
+ int result = BackupTransport.this.getNextFullRestoreDataChunk(socket);
+ callback.onOperationCompleteWithStatus(result);
+ } catch (RuntimeException e) {
+ callback.onOperationCompleteWithStatus(BackupTransport.TRANSPORT_ERROR);
+ }
}
@Override
public void abortFullRestore(ITransportStatusCallback callback) throws RemoteException {
- int result = BackupTransport.this.abortFullRestore();
- callback.onOperationCompleteWithStatus(result);
+ try {
+ int result = BackupTransport.this.abortFullRestore();
+ callback.onOperationCompleteWithStatus(result);
+ } catch (RuntimeException e) {
+ callback.onOperationCompleteWithStatus(BackupTransport.TRANSPORT_ERROR);
+ }
}
}
}
diff --git a/core/java/android/app/smartspace/SmartspaceTarget.java b/core/java/android/app/smartspace/SmartspaceTarget.java
index c5982fc27358..79d7b216628f 100644
--- a/core/java/android/app/smartspace/SmartspaceTarget.java
+++ b/core/java/android/app/smartspace/SmartspaceTarget.java
@@ -174,7 +174,7 @@ public final class SmartspaceTarget implements Parcelable {
public static final int FEATURE_MEDIA_HEADS_UP = 36;
public static final int FEATURE_STEP_COUNTING = 37;
public static final int FEATURE_EARTHQUAKE_ALERT = 38;
- public static final int FEATURE_STEP_DATE = 39;
+ public static final int FEATURE_STEP_DATE = 39; // This represents a DATE. "STEP" is a typo.
public static final int FEATURE_BLAZE_BUILD_PROGRESS = 40;
public static final int FEATURE_EARTHQUAKE_OCCURRED = 41;
diff --git a/core/java/android/companion/virtual/OWNERS b/core/java/android/companion/virtual/OWNERS
new file mode 100644
index 000000000000..29681045ac4a
--- /dev/null
+++ b/core/java/android/companion/virtual/OWNERS
@@ -0,0 +1 @@
+include /services/companion/java/com/android/server/companion/virtual/OWNERS
diff --git a/core/java/android/content/Context.java b/core/java/android/content/Context.java
index 907db7df68d5..836bff598ede 100644
--- a/core/java/android/content/Context.java
+++ b/core/java/android/content/Context.java
@@ -2269,6 +2269,19 @@ public abstract class Context {
*/
public void sendBroadcastMultiplePermissions(@NonNull Intent intent,
@NonNull String[] receiverPermissions, @Nullable String[] excludedPermissions) {
+ sendBroadcastMultiplePermissions(intent, receiverPermissions, excludedPermissions, null);
+ }
+
+
+ /**
+ * Like {@link #sendBroadcastMultiplePermissions(Intent, String[], String[])}, but also allows
+ * specification of a list of excluded packages.
+ *
+ * @hide
+ */
+ public void sendBroadcastMultiplePermissions(@NonNull Intent intent,
+ @NonNull String[] receiverPermissions, @Nullable String[] excludedPermissions,
+ @Nullable String[] excludedPackages) {
throw new RuntimeException("Not implemented. Must override in a subclass.");
}
diff --git a/core/java/android/content/ContextWrapper.java b/core/java/android/content/ContextWrapper.java
index 4ecd7761ac4f..e6549187e5c5 100644
--- a/core/java/android/content/ContextWrapper.java
+++ b/core/java/android/content/ContextWrapper.java
@@ -515,8 +515,10 @@ public class ContextWrapper extends Context {
/** @hide */
@Override
public void sendBroadcastMultiplePermissions(@NonNull Intent intent,
- @NonNull String[] receiverPermissions, @Nullable String[] excludedPermissions) {
- mBase.sendBroadcastMultiplePermissions(intent, receiverPermissions, excludedPermissions);
+ @NonNull String[] receiverPermissions, @Nullable String[] excludedPermissions,
+ @Nullable String[] excludedPackages) {
+ mBase.sendBroadcastMultiplePermissions(intent, receiverPermissions, excludedPermissions,
+ excludedPackages);
}
/** @hide */
diff --git a/core/java/android/content/pm/AppSearchShortcutInfo.java b/core/java/android/content/pm/AppSearchShortcutInfo.java
index 1b84686bbfcf..fb41b890ce9c 100644
--- a/core/java/android/content/pm/AppSearchShortcutInfo.java
+++ b/core/java/android/content/pm/AppSearchShortcutInfo.java
@@ -413,7 +413,10 @@ public class AppSearchShortcutInfo extends GenericDocument {
final int iconResId = (int) getPropertyLong(KEY_ICON_RES_ID);
final String iconResName = getPropertyString(KEY_ICON_RES_NAME);
final String iconUri = getPropertyString(KEY_ICON_URI);
- final int disabledReason = Integer.parseInt(getPropertyString(KEY_DISABLED_REASON));
+ final String disabledReasonString = getPropertyString(KEY_DISABLED_REASON);
+ final int disabledReason = !TextUtils.isEmpty(disabledReasonString)
+ ? Integer.parseInt(getPropertyString(KEY_DISABLED_REASON))
+ : ShortcutInfo.DISABLED_REASON_NOT_DISABLED;
final Map<String, Map<String, List<String>>> capabilityBindings =
parseCapabilityBindings(getPropertyStringArray(KEY_CAPABILITY_BINDINGS));
return new ShortcutInfo(
diff --git a/core/java/android/content/res/AssetFileDescriptor.java b/core/java/android/content/res/AssetFileDescriptor.java
index dd00c3abd251..ac65933db136 100644
--- a/core/java/android/content/res/AssetFileDescriptor.java
+++ b/core/java/android/content/res/AssetFileDescriptor.java
@@ -21,8 +21,6 @@ import android.os.Bundle;
import android.os.Parcel;
import android.os.ParcelFileDescriptor;
import android.os.Parcelable;
-import android.system.ErrnoException;
-import android.system.Os;
import java.io.Closeable;
import java.io.FileDescriptor;
@@ -54,11 +52,11 @@ public class AssetFileDescriptor implements Parcelable, Closeable {
/**
* Create a new AssetFileDescriptor from the given values.
*
- * @param fd The underlying file descriptor.
+ * @param fd The underlying file descriptor.
* @param startOffset The location within the file that the asset starts.
- * This must be 0 if length is UNKNOWN_LENGTH.
- * @param length The number of bytes of the asset, or
- * {@link #UNKNOWN_LENGTH} if it extends to the end of the file.
+ * This must be 0 if length is UNKNOWN_LENGTH.
+ * @param length The number of bytes of the asset, or
+ * {@link #UNKNOWN_LENGTH} if it extends to the end of the file.
*/
public AssetFileDescriptor(ParcelFileDescriptor fd, long startOffset,
long length) {
@@ -68,13 +66,13 @@ public class AssetFileDescriptor implements Parcelable, Closeable {
/**
* Create a new AssetFileDescriptor from the given values.
*
- * @param fd The underlying file descriptor.
+ * @param fd The underlying file descriptor.
* @param startOffset The location within the file that the asset starts.
- * This must be 0 if length is UNKNOWN_LENGTH.
- * @param length The number of bytes of the asset, or
- * {@link #UNKNOWN_LENGTH} if it extends to the end of the file.
- * @param extras additional details that can be used to interpret the
- * underlying file descriptor. May be null.
+ * This must be 0 if length is UNKNOWN_LENGTH.
+ * @param length The number of bytes of the asset, or
+ * {@link #UNKNOWN_LENGTH} if it extends to the end of the file.
+ * @param extras additional details that can be used to interpret the
+ * underlying file descriptor. May be null.
*/
public AssetFileDescriptor(ParcelFileDescriptor fd, long startOffset,
long length, Bundle extras) {
@@ -205,24 +203,19 @@ public class AssetFileDescriptor implements Parcelable, Closeable {
*/
public static class AutoCloseInputStream
extends ParcelFileDescriptor.AutoCloseInputStream {
- private final long mSizeFromStartOffset;
- private final long mStartOffset;
- private long mPosFromStartOffset;
+ private long mRemaining;
public AutoCloseInputStream(AssetFileDescriptor fd) throws IOException {
super(fd.getParcelFileDescriptor());
- // this skip is necessary if getChannel() is called
super.skip(fd.getStartOffset());
- mSizeFromStartOffset = fd.getLength();
- mStartOffset = fd.getStartOffset();
+ mRemaining = (int) fd.getLength();
}
@Override
public int available() throws IOException {
- long available = mSizeFromStartOffset - mPosFromStartOffset;
- return available >= 0
- ? (available < 0x7fffffff ? (int) available : 0x7fffffff)
- : 0;
+ return mRemaining >= 0
+ ? (mRemaining < 0x7fffffff ? (int) mRemaining : 0x7fffffff)
+ : super.available();
}
@Override
@@ -234,24 +227,15 @@ public class AssetFileDescriptor implements Parcelable, Closeable {
@Override
public int read(byte[] buffer, int offset, int count) throws IOException {
- int available = available();
-
- if (available <= 0) {
- return -1;
- } else {
- if (count > available) count = available;
- try {
- int res = Os.pread(getFD(), buffer, offset, count,
- mStartOffset + mPosFromStartOffset);
- // pread returns 0 at end of file, while java's InputStream interface
- // requires -1
- if (res == 0) res = -1;
- if (res >= 0) mPosFromStartOffset += res;
- return res;
- } catch (ErrnoException e) {
- throw new IOException(e);
- }
+ if (mRemaining >= 0) {
+ if (mRemaining == 0) return -1;
+ if (count > mRemaining) count = (int) mRemaining;
+ int res = super.read(buffer, offset, count);
+ if (res >= 0) mRemaining -= res;
+ return res;
}
+
+ return super.read(buffer, offset, count);
}
@Override
@@ -261,31 +245,41 @@ public class AssetFileDescriptor implements Parcelable, Closeable {
@Override
public long skip(long count) throws IOException {
- int available = available();
- if (available <= 0) {
- return -1;
- } else {
- if (count > available) count = available;
- mPosFromStartOffset += count;
- return count;
+ if (mRemaining >= 0) {
+ if (mRemaining == 0) return -1;
+ if (count > mRemaining) count = mRemaining;
+ long res = super.skip(count);
+ if (res >= 0) mRemaining -= res;
+ return res;
}
+
+ return super.skip(count);
}
@Override
public void mark(int readlimit) {
- // Not supported.
- return;
+ if (mRemaining >= 0) {
+ // Not supported.
+ return;
+ }
+ super.mark(readlimit);
}
@Override
public boolean markSupported() {
- return false;
+ if (mRemaining >= 0) {
+ return false;
+ }
+ return super.markSupported();
}
@Override
public synchronized void reset() throws IOException {
- // Not supported.
- return;
+ if (mRemaining >= 0) {
+ // Not supported.
+ return;
+ }
+ super.reset();
}
}
@@ -381,7 +375,6 @@ public class AssetFileDescriptor implements Parcelable, Closeable {
public AssetFileDescriptor createFromParcel(Parcel in) {
return new AssetFileDescriptor(in);
}
-
public AssetFileDescriptor[] newArray(int size) {
return new AssetFileDescriptor[size];
}
diff --git a/core/java/android/hardware/Sensor.java b/core/java/android/hardware/Sensor.java
index 0d3aaf575729..10c37301b0b0 100644
--- a/core/java/android/hardware/Sensor.java
+++ b/core/java/android/hardware/Sensor.java
@@ -712,14 +712,16 @@ public final class Sensor {
public static final String STRING_TYPE_HINGE_ANGLE = "android.sensor.hinge_angle";
/**
- * A constant describing a head tracker sensor.
+ * A constant describing a head tracker sensor. Note that this sensor type is typically not
+ * available for apps to use.
*
* See {@link android.hardware.SensorEvent#values SensorEvent.values} for more details.
*/
public static final int TYPE_HEAD_TRACKER = 37;
/**
- * A constant string describing a head tracker sensor.
+ * A constant string describing a head tracker sensor. Note that this sensor type is typically
+ * not available for apps to use.
*
* See {@link android.hardware.SensorEvent#values SensorEvent.values} for more details.
*/
diff --git a/core/java/android/hardware/camera2/params/OutputConfiguration.java b/core/java/android/hardware/camera2/params/OutputConfiguration.java
index 204e6b60d3dc..9e8703779863 100644
--- a/core/java/android/hardware/camera2/params/OutputConfiguration.java
+++ b/core/java/android/hardware/camera2/params/OutputConfiguration.java
@@ -166,7 +166,16 @@ public final class OutputConfiguration implements Parcelable {
* {@link #TIMESTAMP_BASE_MONOTONIC}, which is roughly the same time base as
* {@link android.os.SystemClock#uptimeMillis}.</li>
* <li> For all other cases, the timestamp base is {@link #TIMESTAMP_BASE_SENSOR}, the same
- * as what's specified by {@link CameraCharacteristics#SENSOR_INFO_TIMESTAMP_SOURCE}.</li>
+ * as what's specified by {@link CameraCharacteristics#SENSOR_INFO_TIMESTAMP_SOURCE}.
+ * <ul><li> For a SurfaceTexture output surface, the camera system re-spaces the delivery
+ * of output frames based on image readout intervals, reducing viewfinder jitter. The timestamps
+ * of images remain to be {@link #TIMESTAMP_BASE_SENSOR}.</li></ul></li>
+ *
+ * <p>Note that the reduction of frame jitter for SurfaceView and SurfaceTexture comes with
+ * slight increase in photon-to-photon latency, which is the time from when photons hit the
+ * scene to when the corresponding pixels show up on the screen. If the photon-to-photon latency
+ * is more important than the smoothness of viewfinder, {@link #TIMESTAMP_BASE_SENSOR} should be
+ * used instead.</p>
*
* @see #TIMESTAMP_BASE_CHOREOGRAPHER_SYNCED
* @see #TIMESTAMP_BASE_MONOTONIC
diff --git a/core/java/android/hardware/display/AmbientDisplayConfiguration.java b/core/java/android/hardware/display/AmbientDisplayConfiguration.java
index 7d8f2ff92200..8c71b363eb7b 100644
--- a/core/java/android/hardware/display/AmbientDisplayConfiguration.java
+++ b/core/java/android/hardware/display/AmbientDisplayConfiguration.java
@@ -89,7 +89,8 @@ public class AmbientDisplayConfiguration {
/** @hide */
public boolean pulseOnNotificationAvailable() {
- return ambientDisplayAvailable();
+ return mContext.getResources().getBoolean(R.bool.config_pulseOnNotificationsAvailable)
+ && ambientDisplayAvailable();
}
/** @hide */
diff --git a/core/java/android/inputmethodservice/InputMethodService.java b/core/java/android/inputmethodservice/InputMethodService.java
index 25296bc0a8b9..21ecf8b0888c 100644
--- a/core/java/android/inputmethodservice/InputMethodService.java
+++ b/core/java/android/inputmethodservice/InputMethodService.java
@@ -592,7 +592,7 @@ public class InputMethodService extends AbstractInputMethodService {
private InlineSuggestionSessionController mInlineSuggestionSessionController;
- private boolean mAutomotiveHideNavBarForKeyboard;
+ private boolean mHideNavBarForKeyboard;
private boolean mIsAutomotive;
private @NonNull OptionalInt mHandwritingRequestId = OptionalInt.empty();
private InputEventReceiver mHandwritingEventReceiver;
@@ -1498,9 +1498,8 @@ public class InputMethodService extends AbstractInputMethodService {
// shown the first time (cold start).
mSettingsObserver.shouldShowImeWithHardKeyboard();
- mIsAutomotive = isAutomotive();
- mAutomotiveHideNavBarForKeyboard = getApplicationContext().getResources().getBoolean(
- com.android.internal.R.bool.config_automotiveHideNavBarForKeyboard);
+ mHideNavBarForKeyboard = getApplicationContext().getResources().getBoolean(
+ com.android.internal.R.bool.config_hideNavBarForKeyboard);
// TODO(b/111364446) Need to address context lifecycle issue if need to re-create
// for update resources & configuration correctly when show soft input
@@ -1539,11 +1538,11 @@ public class InputMethodService extends AbstractInputMethodService {
window.setFlags(windowFlags, windowFlagsMask);
// Automotive devices may request the navigation bar to be hidden when the IME shows up
- // (controlled via config_automotiveHideNavBarForKeyboard) in order to maximize the
- // visible screen real estate. When this happens, the IME window should animate from the
+ // (controlled via config_hideNavBarForKeyboard) in order to maximize the visible
+ // screen real estate. When this happens, the IME window should animate from the
// bottom of the screen to reduce the jank that happens from the lack of synchronization
// between the bottom system window and the IME window.
- if (mIsAutomotive && mAutomotiveHideNavBarForKeyboard) {
+ if (mHideNavBarForKeyboard) {
window.setDecorFitsSystemWindows(false);
}
}
@@ -1625,7 +1624,6 @@ public class InputMethodService extends AbstractInputMethodService {
// when IME developers are doing something unsupported.
InputMethodPrivilegedOperationsRegistry.remove(mToken);
}
- unregisterCompatOnBackInvokedCallback();
mImeDispatcher = null;
}
@@ -2788,6 +2786,11 @@ public class InputMethodService extends AbstractInputMethodService {
if (mInkWindow != null) {
finishStylusHandwriting();
}
+ // Back callback is typically unregistered in {@link #hideWindow()}, but it's possible
+ // for {@link #doFinishInput()} to be called without {@link #hideWindow()} so we also
+ // unregister here.
+ // TODO(b/232341407): Add CTS to verify back behavior after screen on / off.
+ unregisterCompatOnBackInvokedCallback();
}
void doStartInput(InputConnection ic, EditorInfo attribute, boolean restarting) {
diff --git a/core/java/android/net/IVpnManager.aidl b/core/java/android/net/IVpnManager.aidl
index b4647cabe1bc..f30237853a3e 100644
--- a/core/java/android/net/IVpnManager.aidl
+++ b/core/java/android/net/IVpnManager.aidl
@@ -42,6 +42,8 @@ interface IVpnManager {
String startVpnProfile(String packageName);
void stopVpnProfile(String packageName);
VpnProfileState getProvisionedVpnProfileState(String packageName);
+ boolean setAppExclusionList(int userId, String vpnPackage, in List<String> excludedApps);
+ List<String> getAppExclusionList(int userId, String vpnPackage);
/** Always-on VPN APIs */
boolean isAlwaysOnVpnPackageSupported(int userId, String packageName);
diff --git a/core/java/android/net/VpnManager.java b/core/java/android/net/VpnManager.java
index ae7d91f92cb7..f62d7c4a698d 100644
--- a/core/java/android/net/VpnManager.java
+++ b/core/java/android/net/VpnManager.java
@@ -187,14 +187,24 @@ public class VpnManager {
/**
* The network that was underlying the VPN when the event occurred, as a {@link Network}.
*
- * This extra will be null if there was no underlying network at the time of the event.
+ * <p>This extra will be null if there was no underlying network at the time of the event, or
+ * the underlying network has no bearing on the event, as in the case of:
+ * <ul>
+ * <li>CATEGORY_EVENT_DEACTIVATED_BY_USER
+ * <li>CATEGORY_EVENT_ALWAYS_ON_STATE_CHANGED
+ * </ul>
*/
public static final String EXTRA_UNDERLYING_NETWORK = "android.net.extra.UNDERLYING_NETWORK";
/**
* The {@link NetworkCapabilities} of the underlying network when the event occurred.
*
- * This extra will be null if there was no underlying network at the time of the event.
+ * <p>This extra will be null if there was no underlying network at the time of the event, or
+ * the underlying network has no bearing on the event, as in the case of:
+ * <ul>
+ * <li>CATEGORY_EVENT_DEACTIVATED_BY_USER
+ * <li>CATEGORY_EVENT_ALWAYS_ON_STATE_CHANGED
+ * </ul>
*/
public static final String EXTRA_UNDERLYING_NETWORK_CAPABILITIES =
"android.net.extra.UNDERLYING_NETWORK_CAPABILITIES";
@@ -202,7 +212,12 @@ public class VpnManager {
/**
* The {@link LinkProperties} of the underlying network when the event occurred.
*
- * This extra will be null if there was no underlying network at the time of the event.
+ * <p>This extra will be null if there was no underlying network at the time of the event, or
+ * the underlying network has no bearing on the event, as in the case of:
+ * <ul>
+ * <li>CATEGORY_EVENT_DEACTIVATED_BY_USER
+ * <li>CATEGORY_EVENT_ALWAYS_ON_STATE_CHANGED
+ * </ul>
*/
public static final String EXTRA_UNDERLYING_LINK_PROPERTIES =
"android.net.extra.UNDERLYING_LINK_PROPERTIES";
@@ -580,6 +595,63 @@ public class VpnManager {
}
/**
+ * Sets the application exclusion list for the specified VPN profile.
+ *
+ * <p>If an app in the set of excluded apps is not installed for the given user, it will be
+ * skipped in the list of app exclusions. If apps are installed or removed, any active VPN will
+ * have its UID set updated automatically. If the caller is not {@code userId},
+ * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
+ *
+ * <p>This will ONLY affect VpnManager profiles. As such, the NETWORK_SETTINGS provider MUST NOT
+ * allow configuration of these options if the application has not provided a VPN profile.
+ *
+ * @param userId the identifier of the user to set app exclusion list
+ * @param vpnPackage The package name for an installed VPN app on the device
+ * @param excludedApps the app exclusion list
+ * @throws IllegalStateException exception if vpn for the @code userId} is not ready yet.
+ *
+ * @return whether setting the list is successful or not
+ * @hide
+ */
+ @RequiresPermission(anyOf = {
+ android.Manifest.permission.NETWORK_SETTINGS,
+ NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
+ android.Manifest.permission.NETWORK_STACK})
+ public boolean setAppExclusionList(int userId, @NonNull String vpnPackage,
+ @NonNull List<String> excludedApps) {
+ try {
+ return mService.setAppExclusionList(userId, vpnPackage, excludedApps);
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
+ /**
+ * Gets the application exclusion list for the specified VPN profile. If the caller is not
+ * {@code userId}, {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission
+ * is required.
+ *
+ * @param userId the identifier of the user to set app exclusion list
+ * @param vpnPackage The package name for an installed VPN app on the device
+ * @return the list of packages for the specified VPN profile or null if no corresponding VPN
+ * profile configured.
+ *
+ * @hide
+ */
+ @RequiresPermission(anyOf = {
+ android.Manifest.permission.NETWORK_SETTINGS,
+ NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
+ android.Manifest.permission.NETWORK_STACK})
+ @Nullable
+ public List<String> getAppExclusionList(int userId, @NonNull String vpnPackage) {
+ try {
+ return mService.getAppExclusionList(userId, vpnPackage);
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
+ /**
* @return the list of packages that are allowed to access network when always-on VPN is in
* lockdown mode but not connected. Returns {@code null} when VPN lockdown is not active.
*
diff --git a/core/java/android/net/VpnProfileState.java b/core/java/android/net/VpnProfileState.java
index c69ea1a8c220..552a2c171f21 100644
--- a/core/java/android/net/VpnProfileState.java
+++ b/core/java/android/net/VpnProfileState.java
@@ -24,6 +24,8 @@ import android.os.Parcelable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
+import java.util.Objects;
+import java.util.StringJoiner;
/**
* Describe the state of VPN.
@@ -150,4 +152,44 @@ public final class VpnProfileState implements Parcelable {
mAlwaysOn = in.readBoolean();
mLockdown = in.readBoolean();
}
+
+ private String convertStateToString(@State int state) {
+ switch (state) {
+ case STATE_CONNECTED:
+ return "CONNECTED";
+ case STATE_CONNECTING:
+ return "CONNECTING";
+ case STATE_DISCONNECTED:
+ return "DISCONNECTED";
+ case STATE_FAILED:
+ return "FAILED";
+ default:
+ return "UNKNOWN";
+ }
+ }
+
+ @Override
+ public String toString() {
+ final StringJoiner resultJoiner = new StringJoiner(", ", "{", "}");
+ resultJoiner.add("State: " + convertStateToString(getState()));
+ resultJoiner.add("SessionId: " + getSessionId());
+ resultJoiner.add("Always-on: " + isAlwaysOn());
+ resultJoiner.add("Lockdown: " + isLockdownEnabled());
+ return resultJoiner.toString();
+ }
+
+ @Override
+ public boolean equals(@Nullable Object obj) {
+ if (!(obj instanceof VpnProfileState)) return false;
+ final VpnProfileState that = (VpnProfileState) obj;
+ return (getState() == that.getState()
+ && Objects.equals(getSessionId(), that.getSessionId())
+ && isAlwaysOn() == that.isAlwaysOn()
+ && isLockdownEnabled() == that.isLockdownEnabled());
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(getState(), getSessionId(), isAlwaysOn(), isLockdownEnabled());
+ }
}
diff --git a/core/java/android/permission/PermissionControllerManager.java b/core/java/android/permission/PermissionControllerManager.java
index 3c2c7f03761b..b494c7f4026a 100644
--- a/core/java/android/permission/PermissionControllerManager.java
+++ b/core/java/android/permission/PermissionControllerManager.java
@@ -860,7 +860,7 @@ public final class PermissionControllerManager {
Binder.restoreCallingIdentity(token);
}
}
- });
+ }, executor);
}
/**
diff --git a/core/java/android/permission/PermissionUsageHelper.java b/core/java/android/permission/PermissionUsageHelper.java
index 4ed939c48bd7..f5f1c374b636 100644
--- a/core/java/android/permission/PermissionUsageHelper.java
+++ b/core/java/android/permission/PermissionUsageHelper.java
@@ -30,6 +30,7 @@ import static android.app.AppOpsManager.OPSTR_COARSE_LOCATION;
import static android.app.AppOpsManager.OPSTR_FINE_LOCATION;
import static android.app.AppOpsManager.OPSTR_PHONE_CALL_CAMERA;
import static android.app.AppOpsManager.OPSTR_PHONE_CALL_MICROPHONE;
+import static android.app.AppOpsManager.OPSTR_RECEIVE_AMBIENT_TRIGGER_AUDIO;
import static android.app.AppOpsManager.OPSTR_RECORD_AUDIO;
import static android.app.AppOpsManager.OP_CAMERA;
import static android.app.AppOpsManager.OP_FLAGS_ALL_TRUSTED;
@@ -137,6 +138,7 @@ public class PermissionUsageHelper implements AppOpsManager.OnOpActiveChangedLis
private static final List<String> MIC_OPS = List.of(
OPSTR_PHONE_CALL_MICROPHONE,
+ OPSTR_RECEIVE_AMBIENT_TRIGGER_AUDIO,
OPSTR_RECORD_AUDIO
);
@@ -147,6 +149,7 @@ public class PermissionUsageHelper implements AppOpsManager.OnOpActiveChangedLis
private static @NonNull String getGroupForOp(String op) {
switch (op) {
+ case OPSTR_RECEIVE_AMBIENT_TRIGGER_AUDIO:
case OPSTR_RECORD_AUDIO:
return MICROPHONE;
case OPSTR_CAMERA:
diff --git a/core/java/android/provider/DeviceConfig.java b/core/java/android/provider/DeviceConfig.java
index 9a2f7baa7265..13a3ec8c0562 100644
--- a/core/java/android/provider/DeviceConfig.java
+++ b/core/java/android/provider/DeviceConfig.java
@@ -607,6 +607,14 @@ public final class DeviceConfig {
public static final String NAMESPACE_VOICE_INTERACTION = "voice_interaction";
/**
+ * Namespace for DevicePolicyManager related features.
+ *
+ * @hide
+ */
+ public static final String NAMESPACE_DEVICE_POLICY_MANAGER =
+ "device_policy_manager";
+
+ /**
* List of namespaces which can be read without READ_DEVICE_CONFIG permission
*
* @hide
@@ -614,7 +622,8 @@ public final class DeviceConfig {
@NonNull
private static final List<String> PUBLIC_NAMESPACES =
Arrays.asList(NAMESPACE_TEXTCLASSIFIER, NAMESPACE_RUNTIME, NAMESPACE_STATSD_JAVA,
- NAMESPACE_STATSD_JAVA_BOOT, NAMESPACE_SELECTION_TOOLBAR, NAMESPACE_AUTOFILL);
+ NAMESPACE_STATSD_JAVA_BOOT, NAMESPACE_SELECTION_TOOLBAR, NAMESPACE_AUTOFILL,
+ NAMESPACE_DEVICE_POLICY_MANAGER);
/**
* Privacy related properties definitions.
*
@@ -738,14 +747,6 @@ public final class DeviceConfig {
*/
public static final String NAMESPACE_VENDOR_SYSTEM_NATIVE = "vendor_system_native";
- /**
- * Namespace for DevicePolicyManager related features.
- *
- * @hide
- */
- public static final String NAMESPACE_DEVICE_POLICY_MANAGER =
- "device_policy_manager";
-
private static final Object sLock = new Object();
@GuardedBy("sLock")
private static ArrayMap<OnPropertiesChangedListener, Pair<String, Executor>> sListeners =
diff --git a/core/java/android/service/voice/AbstractHotwordDetector.java b/core/java/android/service/voice/AbstractHotwordDetector.java
index 01d5638461af..b2bf9bc2ddd4 100644
--- a/core/java/android/service/voice/AbstractHotwordDetector.java
+++ b/core/java/android/service/voice/AbstractHotwordDetector.java
@@ -189,5 +189,14 @@ abstract class AbstractHotwordDetector implements HotwordDetector {
.setHotwordDetectedResult(hotwordDetectedResult)
.build()));
}
+
+ /** Called when the detection fails due to an error. */
+ @Override
+ public void onError() {
+ Slog.v(TAG, "BinderCallback#onError");
+ mHandler.sendMessage(obtainMessage(
+ HotwordDetector.Callback::onError,
+ mCallback));
+ }
}
}
diff --git a/core/java/android/service/voice/IMicrophoneHotwordDetectionVoiceInteractionCallback.aidl b/core/java/android/service/voice/IMicrophoneHotwordDetectionVoiceInteractionCallback.aidl
index 80f20fe405b1..e8650894ac14 100644
--- a/core/java/android/service/voice/IMicrophoneHotwordDetectionVoiceInteractionCallback.aidl
+++ b/core/java/android/service/voice/IMicrophoneHotwordDetectionVoiceInteractionCallback.aidl
@@ -33,4 +33,9 @@ oneway interface IMicrophoneHotwordDetectionVoiceInteractionCallback {
in HotwordDetectedResult hotwordDetectedResult,
in AudioFormat audioFormat,
in ParcelFileDescriptor audioStream);
+
+ /**
+ * Called when the detection fails due to an error.
+ */
+ void onError();
}
diff --git a/core/java/android/service/voice/SoftwareHotwordDetector.java b/core/java/android/service/voice/SoftwareHotwordDetector.java
index 2d662eaf0a4f..f5a0c66f7b1b 100644
--- a/core/java/android/service/voice/SoftwareHotwordDetector.java
+++ b/core/java/android/service/voice/SoftwareHotwordDetector.java
@@ -155,6 +155,15 @@ class SoftwareHotwordDetector extends AbstractHotwordDetector {
.setHotwordDetectedResult(hotwordDetectedResult)
.build()));
}
+
+ /** Called when the detection fails due to an error. */
+ @Override
+ public void onError() {
+ Slog.v(TAG, "BinderCallback#onError");
+ mHandler.sendMessage(obtainMessage(
+ HotwordDetector.Callback::onError,
+ mCallback));
+ }
}
private static class InitializationStateListener
diff --git a/core/java/android/service/wallpaper/WallpaperService.java b/core/java/android/service/wallpaper/WallpaperService.java
index 0ec95c687090..d598017dacaa 100644
--- a/core/java/android/service/wallpaper/WallpaperService.java
+++ b/core/java/android/service/wallpaper/WallpaperService.java
@@ -888,7 +888,6 @@ public abstract class WallpaperService extends Service {
if (mShouldDimByDefault != mShouldDim && mWallpaperDimAmount == 0f) {
mShouldDim = mShouldDimByDefault;
updateSurfaceDimming();
- updateSurface(false, false, true);
}
}
@@ -898,6 +897,10 @@ public abstract class WallpaperService extends Service {
* @param dimAmount Float amount between [0.0, 1.0] to dim the wallpaper.
*/
private void updateWallpaperDimming(float dimAmount) {
+ if (dimAmount == mWallpaperDimAmount) {
+ return;
+ }
+
// Custom dim amount cannot be less than the default dim amount.
mWallpaperDimAmount = Math.max(mDefaultDimAmount, dimAmount);
// If dim amount is 0f (additional dimming is removed), then the wallpaper should dim
@@ -1195,7 +1198,6 @@ public abstract class WallpaperService extends Service {
.setParent(mSurfaceControl)
.setCallsite("Wallpaper#relayout")
.build();
- updateSurfaceDimming();
}
// Propagate transform hint from WM, so we can use the right hint for the
// first frame.
@@ -1366,7 +1368,6 @@ public abstract class WallpaperService extends Service {
mSession.finishDrawing(mWindow, null /* postDrawTransaction */,
Integer.MAX_VALUE);
processLocalColors(mPendingXOffset, mPendingXOffsetStep);
- notifyColorsChanged();
}
reposition();
reportEngineShown(shouldWaitForEngineShown());
diff --git a/core/java/android/speech/RecognitionService.java b/core/java/android/speech/RecognitionService.java
index 6a65efb891ca..6b59f5480e04 100644
--- a/core/java/android/speech/RecognitionService.java
+++ b/core/java/android/speech/RecognitionService.java
@@ -129,8 +129,9 @@ public abstract class RecognitionService extends Service {
@NonNull AttributionSource attributionSource) {
try {
if (mCurrentCallback == null) {
- boolean preflightPermissionCheckPassed = checkPermissionForPreflightNotHardDenied(
- attributionSource);
+ boolean preflightPermissionCheckPassed =
+ intent.hasExtra(RecognizerIntent.EXTRA_AUDIO_SOURCE)
+ || checkPermissionForPreflightNotHardDenied(attributionSource);
if (preflightPermissionCheckPassed) {
if (DBG) {
Log.d(TAG, "created new mCurrentCallback, listener = "
diff --git a/core/java/android/view/IDisplayWindowRotationCallback.aidl b/core/java/android/view/IDisplayChangeWindowCallback.aidl
index 1ffe2dde40f1..00a5b7b831ca 100644
--- a/core/java/android/view/IDisplayWindowRotationCallback.aidl
+++ b/core/java/android/view/IDisplayChangeWindowCallback.aidl
@@ -17,13 +17,15 @@
package android.view;
import android.window.WindowContainerTransaction;
+import android.window.DisplayAreaInfo;
/**
- * Interface to be invoked by the controller when it has finished preparing for a display rotation.
+ * Interface to be invoked by the controller when it has finished preparing for a display
+ * size change.
*
- * @see IDisplayWindowRotationController
+ * @see IDisplayChangeWindowController
* @hide
*/
-interface IDisplayWindowRotationCallback {
- void continueRotateDisplay(int targetRotation, in WindowContainerTransaction t);
+interface IDisplayChangeWindowCallback {
+ void continueDisplayChange(in WindowContainerTransaction t);
}
diff --git a/core/java/android/view/IDisplayWindowRotationController.aidl b/core/java/android/view/IDisplayChangeWindowController.aidl
index c1c7464c3168..8c0bb6a54528 100644
--- a/core/java/android/view/IDisplayWindowRotationController.aidl
+++ b/core/java/android/view/IDisplayChangeWindowController.aidl
@@ -16,11 +16,12 @@
package android.view;
-import android.view.IDisplayWindowRotationCallback;
+import android.view.IDisplayChangeWindowCallback;
+import android.window.DisplayAreaInfo;
/**
- * Singular controller of a "remote" display rotation. When a display rotation is started, WM
- * freezes the screen. It will then call into this controller and wait for a response via the
+ * Singular controller of a "remote" display change. When a display rotation or change is started,
+ * WM freezes the screen. It will then call into this controller and wait for a response via the
* callback.
*
* This needs to provide configuration changes because those changes need to be applied in sync
@@ -36,17 +37,18 @@ import android.view.IDisplayWindowRotationCallback;
*
* @hide
*/
-oneway interface IDisplayWindowRotationController {
+oneway interface IDisplayChangeWindowController {
/**
- * Called when WM needs to know how to update tasks in response to a display rotation.
- * If this isn't called, a timeout will continue the rotation in WM.
+ * Called when WM needs to know how to update tasks in response to a display change.
+ * If this isn't called, a timeout will continue the change in WM.
*
- * @param displayId the display that is rotating.
- * @param fromRotation the rotation the display is rotating from.
- * @param toRotation the rotation the display is rotating to.
+ * @param fromRotation the old rotation
+ * @param newRotation the new rotation
+ * @param newDisplayAreaInfo the new display area info after the change
* @param callback A callback to be called when this has calculated updated configs.
*/
- void onRotateDisplay(int displayId, int fromRotation, int toRotation,
- in IDisplayWindowRotationCallback callback);
+ void onDisplayChange(int displayId, int fromRotation, int toRotation,
+ in DisplayAreaInfo newDisplayAreaInfo, in IDisplayChangeWindowCallback callback);
+
}
diff --git a/core/java/android/view/IWindowManager.aidl b/core/java/android/view/IWindowManager.aidl
index ee49d7bf5c28..ebdb79ce19e8 100644
--- a/core/java/android/view/IWindowManager.aidl
+++ b/core/java/android/view/IWindowManager.aidl
@@ -40,7 +40,7 @@ import android.view.ICrossWindowBlurEnabledListener;
import android.view.IDisplayWindowInsetsController;
import android.view.IDisplayWindowListener;
import android.view.IDisplayFoldListener;
-import android.view.IDisplayWindowRotationController;
+import android.view.IDisplayChangeWindowController;
import android.view.IOnKeyguardExitResult;
import android.view.IPinnedTaskListener;
import android.view.IScrollCaptureResponseListener;
@@ -146,7 +146,7 @@ interface IWindowManager
* controller is called after the display has "frozen" for a rotation and display rotation will
* only continue once the controller has finished calculating associated configurations.
*/
- void setDisplayWindowRotationController(IDisplayWindowRotationController controller);
+ void setDisplayChangeWindowController(IDisplayChangeWindowController controller);
/**
* Adds a root container that a client shell can populate with its own windows (usually via
diff --git a/core/java/android/view/Surface.java b/core/java/android/view/Surface.java
index e5ec260907df..691452f51ee8 100644
--- a/core/java/android/view/Surface.java
+++ b/core/java/android/view/Surface.java
@@ -341,10 +341,12 @@ public class Surface implements Parcelable {
*/
@UnsupportedAppUsage
public void destroy() {
- if (mNativeObject != 0) {
- nativeDestroy(mNativeObject);
+ synchronized (mLock) {
+ if (mNativeObject != 0) {
+ nativeDestroy(mNativeObject);
+ }
+ release();
}
- release();
}
/**
diff --git a/core/java/android/view/View.java b/core/java/android/view/View.java
index d04b07c13b41..38ca2481726b 100644
--- a/core/java/android/view/View.java
+++ b/core/java/android/view/View.java
@@ -11941,7 +11941,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback,
@NonNull
public final List<Rect> getUnrestrictedPreferKeepClearRects() {
final ListenerInfo info = mListenerInfo;
- if (info != null && info.mKeepClearRects != null) {
+ if (info != null && info.mUnrestrictedKeepClearRects != null) {
return new ArrayList(info.mUnrestrictedKeepClearRects);
}
@@ -21170,6 +21170,11 @@ public class View implements Drawable.Callback, KeyEvent.Callback,
}
AccessibilityNodeIdManager.getInstance().unregisterViewWithId(getAccessibilityViewId());
+
+ if (mBackgroundRenderNode != null) {
+ mBackgroundRenderNode.forceEndAnimators();
+ }
+ mRenderNode.forceEndAnimators();
}
private void cleanupDraw() {
diff --git a/core/java/android/window/ImeOnBackInvokedDispatcher.java b/core/java/android/window/ImeOnBackInvokedDispatcher.java
index d5763aa25884..8bdf233b81c8 100644
--- a/core/java/android/window/ImeOnBackInvokedDispatcher.java
+++ b/core/java/android/window/ImeOnBackInvokedDispatcher.java
@@ -158,6 +158,12 @@ public class ImeOnBackInvokedDispatcher implements OnBackInvokedDispatcher, Parc
/** Clears all registered callbacks on the instance. */
public void clear() {
+ // Unregister previously registered callbacks if there's any.
+ if (getReceivingDispatcher() != null) {
+ for (OnBackInvokedCallback callback : mImeCallbackMap.values()) {
+ getReceivingDispatcher().unregisterOnBackInvokedCallback(callback);
+ }
+ }
mImeCallbackMap.clear();
}
diff --git a/core/java/android/window/TransitionInfo.java b/core/java/android/window/TransitionInfo.java
index 51da61ffb9c9..c81184fb2383 100644
--- a/core/java/android/window/TransitionInfo.java
+++ b/core/java/android/window/TransitionInfo.java
@@ -107,8 +107,11 @@ public final class TransitionInfo implements Parcelable {
*/
public static final int FLAG_DISPLAY_HAS_ALERT_WINDOWS = 1 << 7;
+ /** The container is an input-method window. */
+ public static final int FLAG_IS_INPUT_METHOD = 1 << 8;
+
/** The first unused bit. This can be used by remotes to attach custom flags to this change. */
- public static final int FLAG_FIRST_CUSTOM = 1 << 8;
+ public static final int FLAG_FIRST_CUSTOM = 1 << 9;
/** @hide */
@IntDef(prefix = { "FLAG_" }, value = {
@@ -121,6 +124,7 @@ public final class TransitionInfo implements Parcelable {
FLAG_IS_DISPLAY,
FLAG_OCCLUDES_KEYGUARD,
FLAG_DISPLAY_HAS_ALERT_WINDOWS,
+ FLAG_IS_INPUT_METHOD,
FLAG_FIRST_CUSTOM
})
public @interface ChangeFlags {}
@@ -300,6 +304,9 @@ public final class TransitionInfo implements Parcelable {
if ((flags & FLAG_IS_WALLPAPER) != 0) {
sb.append("IS_WALLPAPER");
}
+ if ((flags & FLAG_IS_INPUT_METHOD) != 0) {
+ sb.append("IS_INPUT_METHOD");
+ }
if ((flags & FLAG_TRANSLUCENT) != 0) {
sb.append((sb.length() == 0 ? "" : "|") + "TRANSLUCENT");
}
diff --git a/core/java/com/android/internal/app/AppLocaleStore.java b/core/java/com/android/internal/app/AppLocaleStore.java
index 599e6d24600c..f3a322cac79a 100644
--- a/core/java/com/android/internal/app/AppLocaleStore.java
+++ b/core/java/com/android/internal/app/AppLocaleStore.java
@@ -20,12 +20,15 @@ import static com.android.internal.app.AppLocaleStore.AppLocaleResult.LocaleStat
import android.app.LocaleConfig;
import android.content.Context;
+import android.content.pm.ApplicationInfo;
+import android.content.pm.InstallSourceInfo;
import android.content.pm.PackageManager;
import android.os.LocaleList;
import android.util.Log;
-import java.util.ArrayList;
+import java.util.HashSet;
import java.util.Locale;
+import java.util.stream.Collectors;
class AppLocaleStore {
private static final String TAG = AppLocaleStore.class.getSimpleName();
@@ -34,7 +37,8 @@ class AppLocaleStore {
Context context, String packageName) {
LocaleConfig localeConfig = null;
AppLocaleResult.LocaleStatus localeStatus = LocaleStatus.UNKNOWN_FAILURE;
- ArrayList<Locale> appSupportedLocales = new ArrayList<>();
+ HashSet<Locale> appSupportedLocales = new HashSet<>();
+ HashSet<Locale> assetLocale = getAssetLocales(context, packageName);
try {
localeConfig = new LocaleConfig(context.createPackageContext(packageName, 0));
@@ -45,32 +49,43 @@ class AppLocaleStore {
if (localeConfig != null) {
if (localeConfig.getStatus() == LocaleConfig.STATUS_SUCCESS) {
LocaleList packageLocaleList = localeConfig.getSupportedLocales();
- if (packageLocaleList.size() > 0) {
+ boolean shouldFilterNotMatchingLocale = !hasInstallerInfo(context, packageName) &&
+ isSystemApp(context, packageName);
+
+ Log.d(TAG, "filterNonMatchingLocale. " +
+ ", shouldFilterNotMatchingLocale: " + shouldFilterNotMatchingLocale +
+ ", assetLocale size: " + assetLocale.size() +
+ ", packageLocaleList size: " + packageLocaleList.size());
+
+ for (int i = 0; i < packageLocaleList.size(); i++) {
+ appSupportedLocales.add(packageLocaleList.get(i));
+ }
+ if (shouldFilterNotMatchingLocale) {
+ appSupportedLocales = filterNotMatchingLocale(appSupportedLocales, assetLocale);
+ }
+
+ if (appSupportedLocales.size() > 0) {
localeStatus = LocaleStatus.GET_SUPPORTED_LANGUAGE_FROM_LOCAL_CONFIG;
- for (int i = 0; i < packageLocaleList.size(); i++) {
- appSupportedLocales.add(packageLocaleList.get(i));
- }
} else {
localeStatus = LocaleStatus.NO_SUPPORTED_LANGUAGE_IN_APP;
}
} else if (localeConfig.getStatus() == LocaleConfig.STATUS_NOT_SPECIFIED) {
- String[] languages = getAssetLocales(context, packageName);
- if (languages.length > 0) {
+ if (assetLocale.size() > 0) {
localeStatus = LocaleStatus.GET_SUPPORTED_LANGUAGE_FROM_ASSET;
- for (String language : languages) {
- appSupportedLocales.add(Locale.forLanguageTag(language));
- }
+ appSupportedLocales = assetLocale;
} else {
localeStatus = LocaleStatus.ASSET_LOCALE_IS_EMPTY;
}
}
}
- Log.d(TAG, "getAppSupportedLocales(). status: " + localeStatus
+ Log.d(TAG, "getAppSupportedLocales(). package: " + packageName
+ + ", status: " + localeStatus
+ ", appSupportedLocales:" + appSupportedLocales.size());
return new AppLocaleResult(localeStatus, appSupportedLocales);
}
- private static String[] getAssetLocales(Context context, String packageName) {
+ private static HashSet<Locale> getAssetLocales(Context context, String packageName) {
+ HashSet<Locale> result = new HashSet<>();
try {
PackageManager packageManager = context.getPackageManager();
String[] locales = packageManager.getResourcesForApplication(
@@ -78,16 +93,59 @@ class AppLocaleStore {
.applicationInfo).getAssets().getNonSystemLocales();
if (locales == null) {
Log.i(TAG, "[" + packageName + "] locales are null.");
- return new String[0];
} else if (locales.length <= 0) {
Log.i(TAG, "[" + packageName + "] locales length is 0.");
- return new String[0];
+ } else {
+ for (String language : locales) {
+ result.add(Locale.forLanguageTag(language));
+ }
}
- return locales;
} catch (PackageManager.NameNotFoundException e) {
Log.w(TAG, "Can not found the package name : " + packageName + " / " + e);
}
- return new String[0];
+ return result;
+ }
+
+ private static HashSet<Locale> filterNotMatchingLocale(
+ HashSet<Locale> appSupportedLocales, HashSet<Locale> assetLocale) {
+ return appSupportedLocales.stream()
+ .filter(locale -> matchLanguageInSet(locale, assetLocale))
+ .collect(Collectors.toCollection(HashSet::new));
+ }
+
+ private static boolean matchLanguageInSet(Locale locale, HashSet<Locale> localesSet) {
+ if (localesSet.contains(locale)) {
+ return true;
+ }
+ for (Locale l: localesSet) {
+ if(LocaleList.matchesLanguageAndScript(l, locale)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private static boolean hasInstallerInfo(Context context, String packageName) {
+ InstallSourceInfo installSourceInfo;
+ try {
+ installSourceInfo = context.getPackageManager().getInstallSourceInfo(packageName);
+ return installSourceInfo != null;
+ } catch (PackageManager.NameNotFoundException e) {
+ Log.w(TAG, "Installer info not found for: " + packageName);
+ }
+ return false;
+ }
+
+ private static boolean isSystemApp(Context context, String packageName) {
+ ApplicationInfo applicationInfo;
+ try {
+ applicationInfo = context.getPackageManager()
+ .getApplicationInfoAsUser(packageName, /* flags= */ 0, context.getUserId());
+ return applicationInfo.isSystemApp();
+ } catch (PackageManager.NameNotFoundException e) {
+ Log.w(TAG, "Application info not found for: " + packageName);
+ }
+ return false;
}
static class AppLocaleResult {
@@ -100,9 +158,9 @@ class AppLocaleStore {
}
LocaleStatus mLocaleStatus;
- ArrayList<Locale> mAppSupportedLocales;
+ HashSet<Locale> mAppSupportedLocales;
- public AppLocaleResult(LocaleStatus localeStatus, ArrayList<Locale> appSupportedLocales) {
+ public AppLocaleResult(LocaleStatus localeStatus, HashSet<Locale> appSupportedLocales) {
this.mLocaleStatus = localeStatus;
this.mAppSupportedLocales = appSupportedLocales;
}
diff --git a/core/java/com/android/internal/app/ChooserActivity.java b/core/java/com/android/internal/app/ChooserActivity.java
index 2ad1b3845bdc..7cc37f70f8fa 100644
--- a/core/java/com/android/internal/app/ChooserActivity.java
+++ b/core/java/com/android/internal/app/ChooserActivity.java
@@ -190,6 +190,7 @@ public class ChooserActivity extends ResolverActivity implements
private static final String SHORTCUT_TARGET = "shortcut_target";
private static final int APP_PREDICTION_SHARE_TARGET_QUERY_PACKAGE_LIMIT = 20;
public static final String APP_PREDICTION_INTENT_FILTER_KEY = "intent_filter";
+ private static final String SHARED_TEXT_KEY = "shared_text";
private static final String PLURALS_COUNT = "count";
private static final String PLURALS_FILE_NAME = "file_name";
@@ -2201,6 +2202,7 @@ public class ChooserActivity extends ResolverActivity implements
final IntentFilter filter = getTargetIntentFilter();
Bundle extras = new Bundle();
extras.putParcelable(APP_PREDICTION_INTENT_FILTER_KEY, filter);
+ populateTextContent(extras);
AppPredictionContext appPredictionContext = new AppPredictionContext.Builder(contextAsUser)
.setUiSurface(APP_PREDICTION_SHARE_UI_SURFACE)
.setPredictedTargetCount(APP_PREDICTION_SHARE_TARGET_QUERY_PACKAGE_LIMIT)
@@ -2219,6 +2221,12 @@ public class ChooserActivity extends ResolverActivity implements
return appPredictionSession;
}
+ private void populateTextContent(Bundle extras) {
+ final Intent intent = getTargetIntent();
+ String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
+ extras.putString(SHARED_TEXT_KEY, sharedText);
+ }
+
/**
* This will return an app predictor if it is enabled for direct share sorting
* and if one exists. Otherwise, it returns null.
diff --git a/core/java/com/android/internal/app/ChooserTargetActionsDialogFragment.java b/core/java/com/android/internal/app/ChooserTargetActionsDialogFragment.java
index 4f1f380c3a77..3e1b5f087c10 100644
--- a/core/java/com/android/internal/app/ChooserTargetActionsDialogFragment.java
+++ b/core/java/com/android/internal/app/ChooserTargetActionsDialogFragment.java
@@ -269,7 +269,7 @@ public class ChooserTargetActionsDialogFragment extends DialogFragment
protected CharSequence getItemLabel(DisplayResolveInfo dri) {
final PackageManager pm = getContext().getPackageManager();
return getPinLabel(isPinned(dri),
- isShortcutTarget() ? "" : dri.getResolveInfo().loadLabel(pm));
+ isShortcutTarget() ? mShortcutTitle : dri.getResolveInfo().loadLabel(pm));
}
@Nullable
diff --git a/core/java/com/android/internal/app/LocalePickerWithRegion.java b/core/java/com/android/internal/app/LocalePickerWithRegion.java
index a06ba9be4689..965895f08d6e 100644
--- a/core/java/com/android/internal/app/LocalePickerWithRegion.java
+++ b/core/java/com/android/internal/app/LocalePickerWithRegion.java
@@ -29,13 +29,13 @@ import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
+import android.view.MenuItem.OnActionExpandListener;
import android.view.View;
import android.widget.ListView;
import android.widget.SearchView;
import com.android.internal.R;
-import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Locale;
@@ -64,6 +64,7 @@ public class LocalePickerWithRegion extends ListFragment implements SearchView.O
private int mTopDistance = 0;
private String mAppPackageName;
private CharSequence mTitle = null;
+ private OnActionExpandListener mOnActionExpandListener;
/**
* Other classes can register to be notified when a locale was selected.
@@ -80,8 +81,10 @@ public class LocalePickerWithRegion extends ListFragment implements SearchView.O
private static LocalePickerWithRegion createCountryPicker(Context context,
LocaleSelectedListener listener, LocaleStore.LocaleInfo parent,
- boolean translatedOnly, String appPackageName) {
+ boolean translatedOnly, String appPackageName,
+ OnActionExpandListener onActionExpandListener) {
LocalePickerWithRegion localePicker = new LocalePickerWithRegion();
+ localePicker.setOnActionExpandListener(onActionExpandListener);
boolean shouldShowTheList = localePicker.setListener(context, listener, parent,
translatedOnly, appPackageName);
return shouldShowTheList ? localePicker : null;
@@ -95,8 +98,10 @@ public class LocalePickerWithRegion extends ListFragment implements SearchView.O
}
public static LocalePickerWithRegion createLanguagePicker(Context context,
- LocaleSelectedListener listener, boolean translatedOnly, String appPackageName) {
+ LocaleSelectedListener listener, boolean translatedOnly, String appPackageName,
+ OnActionExpandListener onActionExpandListener) {
LocalePickerWithRegion localePicker = new LocalePickerWithRegion();
+ localePicker.setOnActionExpandListener(onActionExpandListener);
localePicker.setListener(
context, listener, /* parent */ null, translatedOnly, appPackageName);
return localePicker;
@@ -198,13 +203,20 @@ public class LocalePickerWithRegion extends ListFragment implements SearchView.O
}
private Set<LocaleStore.LocaleInfo> filterTheLanguagesNotSupportedInApp(
- boolean shouldShowList, ArrayList<Locale> supportedLocales) {
+ boolean shouldShowList, HashSet<Locale> supportedLocales) {
Set<LocaleStore.LocaleInfo> filteredList = new HashSet<>();
- if (shouldShowList) {
- for(LocaleStore.LocaleInfo li: mLocaleList) {
+ if (!shouldShowList) {
+ return filteredList;
+ }
+
+ for(LocaleStore.LocaleInfo li: mLocaleList) {
+ if (supportedLocales.contains(li.getLocale())) {
+ filteredList.add(li);
+ } else {
for(Locale l: supportedLocales) {
if(LocaleList.matchesLanguageAndScript(li.getLocale(), l)) {
filteredList.add(li);
+ break;
}
}
}
@@ -310,7 +322,7 @@ public class LocalePickerWithRegion extends ListFragment implements SearchView.O
} else {
LocalePickerWithRegion selector = LocalePickerWithRegion.createCountryPicker(
getContext(), mListener, locale, mTranslatedOnly /* translate only */,
- mAppPackageName);
+ mAppPackageName, mOnActionExpandListener);
if (selector != null) {
getFragmentManager().beginTransaction()
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
@@ -328,8 +340,11 @@ public class LocalePickerWithRegion extends ListFragment implements SearchView.O
inflater.inflate(R.menu.language_selection_list, menu);
final MenuItem searchMenuItem = menu.findItem(R.id.locale_search_menu);
- mSearchView = (SearchView) searchMenuItem.getActionView();
+ if (!TextUtils.isEmpty(mAppPackageName) && mOnActionExpandListener != null) {
+ searchMenuItem.setOnActionExpandListener(mOnActionExpandListener);
+ }
+ mSearchView = (SearchView) searchMenuItem.getActionView();
mSearchView.setQueryHint(getText(R.string.search_language_hint));
mSearchView.setOnQueryTextListener(this);
@@ -363,4 +378,11 @@ public class LocalePickerWithRegion extends ListFragment implements SearchView.O
}
return false;
}
+
+ /**
+ * Sets OnActionExpandListener to LocalePickerWithRegion to dectect action of search bar.
+ */
+ public void setOnActionExpandListener(OnActionExpandListener onActionExpandListener) {
+ mOnActionExpandListener = onActionExpandListener;
+ }
}
diff --git a/core/java/com/android/internal/app/ResolverActivity.java b/core/java/com/android/internal/app/ResolverActivity.java
index bd5a73d8194a..7e53a5afc315 100644
--- a/core/java/com/android/internal/app/ResolverActivity.java
+++ b/core/java/com/android/internal/app/ResolverActivity.java
@@ -119,6 +119,11 @@ public class ResolverActivity extends Activity implements
@UnsupportedAppUsage
public ResolverActivity() {
+ mIsIntentPicker = getClass().equals(ResolverActivity.class);
+ }
+
+ protected ResolverActivity(boolean isIntentPicker) {
+ mIsIntentPicker = isIntentPicker;
}
private boolean mSafeForwardingMode;
@@ -135,6 +140,8 @@ public class ResolverActivity extends Activity implements
private String mReferrerPackage;
private CharSequence mTitle;
private int mDefaultTitleResId;
+ // Expected to be true if this object is ResolverActivity or is ResolverWrapperActivity.
+ private final boolean mIsIntentPicker;
// Whether or not this activity supports choosing a default handler for the intent.
@VisibleForTesting
@@ -445,10 +452,6 @@ public class ResolverActivity extends Activity implements
+ (categories != null ? Arrays.toString(categories.toArray()) : ""));
}
- private boolean isIntentPicker() {
- return getClass().equals(ResolverActivity.class);
- }
-
protected AbstractMultiProfilePagerAdapter createMultiProfilePagerAdapter(
Intent[] initialIntents,
List<ResolveInfo> rList,
@@ -637,6 +640,11 @@ public class ResolverActivity extends Activity implements
resetButtonBar();
+ if (shouldUseMiniResolver()) {
+ View buttonContainer = findViewById(R.id.button_bar_container);
+ buttonContainer.setPadding(0, 0, 0, mSystemWindowInsets.bottom);
+ }
+
// Need extra padding so the list can fully scroll up
if (shouldAddFooterView()) {
applyFooterView(mSystemWindowInsets.bottom);
@@ -649,7 +657,8 @@ public class ResolverActivity extends Activity implements
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mMultiProfilePagerAdapter.getActiveListAdapter().handlePackagesChanged();
- if (isIntentPicker() && shouldShowTabs() && !useLayoutWithDefault()) {
+ if (mIsIntentPicker && shouldShowTabs() && !useLayoutWithDefault()
+ && !shouldUseMiniResolver()) {
updateIntentPickerPaddings();
}
@@ -1084,7 +1093,7 @@ public class ResolverActivity extends Activity implements
if (isAutolaunching()) {
return;
}
- if (isIntentPicker()) {
+ if (mIsIntentPicker) {
((ResolverMultiProfilePagerAdapter) mMultiProfilePagerAdapter)
.setUseLayoutWithDefault(useLayoutWithDefault());
}
@@ -1108,7 +1117,7 @@ public class ResolverActivity extends Activity implements
protected void onListRebuilt(ResolverListAdapter listAdapter, boolean rebuildCompleted) {
final ItemClickListener listener = new ItemClickListener();
setupAdapterListView((ListView) mMultiProfilePagerAdapter.getActiveAdapterView(), listener);
- if (shouldShowTabs() && isIntentPicker()) {
+ if (shouldShowTabs() && mIsIntentPicker) {
final ResolverDrawerLayout rdl = findViewById(R.id.contentPanel);
if (rdl != null) {
rdl.setMaxCollapsedHeight(getResources()
@@ -1448,6 +1457,12 @@ public class ResolverActivity extends Activity implements
return postRebuildList(rebuildCompleted);
}
+ /**
+ * Mini resolver is shown when the user is choosing between browser[s] in this profile and a
+ * single app in the other profile (see shouldUseMiniResolver()). It shows the single app icon
+ * and asks the user if they'd like to open that cross-profile app or use the in-profile
+ * browser.
+ */
private void configureMiniResolverContent() {
mLayoutId = R.layout.miniresolver;
setContentView(mLayoutId);
@@ -1456,10 +1471,14 @@ public class ResolverActivity extends Activity implements
mMultiProfilePagerAdapter.getActiveListAdapter().mDisplayList.get(0);
boolean inWorkProfile = getCurrentProfile() == PROFILE_WORK;
- DisplayResolveInfo otherProfileResolveInfo =
- mMultiProfilePagerAdapter.getInactiveListAdapter().mDisplayList.get(0);
+ ResolverListAdapter inactiveAdapter = mMultiProfilePagerAdapter.getInactiveListAdapter();
+ DisplayResolveInfo otherProfileResolveInfo = inactiveAdapter.mDisplayList.get(0);
+
+ // Load the icon asynchronously
ImageView icon = findViewById(R.id.icon);
- // TODO: Set icon drawable to app icon.
+ ResolverListAdapter.LoadIconTask iconTask = inactiveAdapter.new LoadIconTask(
+ otherProfileResolveInfo, new ResolverListAdapter.ViewHolder(icon));
+ iconTask.execute();
((TextView) findViewById(R.id.open_cross_profile)).setText(
getResources().getString(
@@ -1479,12 +1498,20 @@ public class ResolverActivity extends Activity implements
prepareIntentForCrossProfileLaunch(intent);
}
safelyStartActivityAsUser(otherProfileResolveInfo,
- mMultiProfilePagerAdapter.getInactiveListAdapter().mResolverListController
- .getUserHandle());
+ inactiveAdapter.mResolverListController.getUserHandle());
});
}
+ /**
+ * Mini resolver should be used when all of the following are true:
+ * 1. This is the intent picker (ResolverActivity).
+ * 2. This profile only has web browser matches.
+ * 3. The other profile has a single non-browser match.
+ */
private boolean shouldUseMiniResolver() {
+ if (!mIsIntentPicker) {
+ return false;
+ }
if (mMultiProfilePagerAdapter.getActiveListAdapter() == null
|| mMultiProfilePagerAdapter.getInactiveListAdapter() == null) {
return false;
@@ -1790,7 +1817,7 @@ public class ResolverActivity extends Activity implements
void onHorizontalSwipeStateChanged(int state) {}
private void maybeHideDivider() {
- if (!isIntentPicker()) {
+ if (!mIsIntentPicker) {
return;
}
final View divider = findViewById(R.id.divider);
@@ -1807,7 +1834,7 @@ public class ResolverActivity extends Activity implements
protected void onProfileTabSelected() { }
private void resetCheckedItem() {
- if (!isIntentPicker()) {
+ if (!mIsIntentPicker) {
return;
}
mLastSelected = ListView.INVALID_POSITION;
diff --git a/core/java/com/android/internal/app/procstats/ProcessStats.java b/core/java/com/android/internal/app/procstats/ProcessStats.java
index b7abe73a79eb..9fea86e837ca 100644
--- a/core/java/com/android/internal/app/procstats/ProcessStats.java
+++ b/core/java/com/android/internal/app/procstats/ProcessStats.java
@@ -374,14 +374,12 @@ public final class ProcessStats implements Parcelable {
}
}
thisProc.add(otherProc);
- if (thisProc.isActive()) {
- UidState uidState = mUidStates.get(uid);
- if (uidState == null) {
- uidState = new UidState(this, uid);
- mUidStates.put(uid, uidState);
- }
- uidState.addProcess(thisProc);
+ UidState uidState = mUidStates.get(uid);
+ if (uidState == null) {
+ uidState = new UidState(this, uid);
+ mUidStates.put(uid, uidState);
}
+ uidState.addProcess(thisProc);
}
}
@@ -1185,9 +1183,7 @@ public final class ProcessStats implements Parcelable {
+ " " + proc);
mProcesses.put(procName, uid, proc);
- if (proc.isActive()) {
- mUidStates.get(uid).addProcess(proc);
- }
+ mUidStates.get(uid).addProcess(proc);
}
}
diff --git a/core/java/com/android/internal/jank/InteractionJankMonitor.java b/core/java/com/android/internal/jank/InteractionJankMonitor.java
index e466c8866afa..2dcc58564f82 100644
--- a/core/java/com/android/internal/jank/InteractionJankMonitor.java
+++ b/core/java/com/android/internal/jank/InteractionJankMonitor.java
@@ -71,8 +71,10 @@ import static com.android.internal.util.FrameworkStatsLog.UIINTERACTION_FRAME_IN
import static com.android.internal.util.FrameworkStatsLog.UIINTERACTION_FRAME_INFO_REPORTED__INTERACTION_TYPE__SUW_LOADING_TO_NEXT_FLOW;
import static com.android.internal.util.FrameworkStatsLog.UIINTERACTION_FRAME_INFO_REPORTED__INTERACTION_TYPE__SUW_LOADING_TO_SHOW_INFO_WITH_ACTIONS;
import static com.android.internal.util.FrameworkStatsLog.UIINTERACTION_FRAME_INFO_REPORTED__INTERACTION_TYPE__SUW_SHOW_FUNCTION_SCREEN_WITH_ACTIONS;
+import static com.android.internal.util.FrameworkStatsLog.UIINTERACTION_FRAME_INFO_REPORTED__INTERACTION_TYPE__TAKE_SCREENSHOT;
import static com.android.internal.util.FrameworkStatsLog.UIINTERACTION_FRAME_INFO_REPORTED__INTERACTION_TYPE__UNFOLD_ANIM;
import static com.android.internal.util.FrameworkStatsLog.UIINTERACTION_FRAME_INFO_REPORTED__INTERACTION_TYPE__USER_SWITCH;
+import static com.android.internal.util.FrameworkStatsLog.UIINTERACTION_FRAME_INFO_REPORTED__INTERACTION_TYPE__VOLUME_CONTROL;
import static com.android.internal.util.FrameworkStatsLog.UIINTERACTION_FRAME_INFO_REPORTED__INTERACTION_TYPE__WALLPAPER_TRANSITION;
import android.annotation.IntDef;
@@ -194,6 +196,8 @@ public class InteractionJankMonitor {
public static final int CUJ_LOCKSCREEN_LAUNCH_CAMERA = 51; // reserved.
public static final int CUJ_SPLIT_SCREEN_RESIZE = 52;
public static final int CUJ_SETTINGS_SLIDER = 53;
+ public static final int CUJ_TAKE_SCREENSHOT = 54;
+ public static final int CUJ_VOLUME_CONTROL = 55;
private static final int NO_STATSD_LOGGING = -1;
@@ -256,6 +260,8 @@ public class InteractionJankMonitor {
UIINTERACTION_FRAME_INFO_REPORTED__INTERACTION_TYPE__LOCKSCREEN_LAUNCH_CAMERA,
UIINTERACTION_FRAME_INFO_REPORTED__INTERACTION_TYPE__SPLIT_SCREEN_RESIZE,
UIINTERACTION_FRAME_INFO_REPORTED__INTERACTION_TYPE__SETTINGS_SLIDER,
+ UIINTERACTION_FRAME_INFO_REPORTED__INTERACTION_TYPE__TAKE_SCREENSHOT,
+ UIINTERACTION_FRAME_INFO_REPORTED__INTERACTION_TYPE__VOLUME_CONTROL,
};
private static volatile InteractionJankMonitor sInstance;
@@ -330,6 +336,8 @@ public class InteractionJankMonitor {
CUJ_LOCKSCREEN_LAUNCH_CAMERA,
CUJ_SPLIT_SCREEN_RESIZE,
CUJ_SETTINGS_SLIDER,
+ CUJ_TAKE_SCREENSHOT,
+ CUJ_VOLUME_CONTROL,
})
@Retention(RetentionPolicy.SOURCE)
public @interface CujType {
@@ -756,6 +764,10 @@ public class InteractionJankMonitor {
return "CUJ_SPLIT_SCREEN_RESIZE";
case CUJ_SETTINGS_SLIDER:
return "SETTINGS_SLIDER";
+ case CUJ_TAKE_SCREENSHOT:
+ return "TAKE_SCREENSHOT";
+ case CUJ_VOLUME_CONTROL:
+ return "VOLUME_CONTROL";
}
return "UNKNOWN";
}
diff --git a/core/java/com/android/internal/os/BatteryStatsImpl.java b/core/java/com/android/internal/os/BatteryStatsImpl.java
index b03a8cbeb79c..6829f3da5717 100644
--- a/core/java/com/android/internal/os/BatteryStatsImpl.java
+++ b/core/java/com/android/internal/os/BatteryStatsImpl.java
@@ -644,7 +644,7 @@ public class BatteryStatsImpl extends BatteryStats {
/** Schedule removal of UIDs corresponding to a removed user */
Future<?> scheduleCleanupDueToRemovedUser(int userId);
/** Schedule a sync because of a process state change */
- Future<?> scheduleSyncDueToProcessStateChange(long delayMillis);
+ void scheduleSyncDueToProcessStateChange(int flags, long delayMillis);
}
public Handler mHandler;
@@ -6215,9 +6215,7 @@ public class BatteryStatsImpl extends BatteryStats {
long elapsedRealtimeMs, long uptimeMs) {
if (mMobileRadioPowerState != powerState) {
long realElapsedRealtimeMs;
- final boolean active =
- powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
- || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
+ final boolean active = isActiveRadioPowerState(powerState);
if (active) {
if (uid > 0) {
noteMobileRadioApWakeupLocked(elapsedRealtimeMs, uptimeMs, uid);
@@ -6259,6 +6257,11 @@ public class BatteryStatsImpl extends BatteryStats {
return false;
}
+ private static boolean isActiveRadioPowerState(int powerState) {
+ return powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
+ || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
+ }
+
@GuardedBy("this")
public void notePowerSaveModeLocked(boolean enabled) {
notePowerSaveModeLocked(enabled, mClock.elapsedRealtime(), mClock.uptimeMillis());
@@ -12042,7 +12045,13 @@ public class BatteryStatsImpl extends BatteryStats {
return;
}
- mBsi.mExternalSync.scheduleSyncDueToProcessStateChange(
+ int flags = ExternalStatsSync.UPDATE_ON_PROC_STATE_CHANGE;
+ // Skip querying for inactive radio, where power usage is probably negligible.
+ if (!BatteryStatsImpl.isActiveRadioPowerState(mBsi.mMobileRadioPowerState)) {
+ flags &= ~ExternalStatsSync.UPDATE_RADIO;
+ }
+
+ mBsi.mExternalSync.scheduleSyncDueToProcessStateChange(flags,
mBsi.mConstants.PROC_STATE_CHANGE_COLLECTION_DELAY_MS);
}
diff --git a/core/java/com/android/internal/view/ScrollCaptureViewSupport.java b/core/java/com/android/internal/view/ScrollCaptureViewSupport.java
index f2c27a494fc9..d842eb6c4d49 100644
--- a/core/java/com/android/internal/view/ScrollCaptureViewSupport.java
+++ b/core/java/com/android/internal/view/ScrollCaptureViewSupport.java
@@ -395,7 +395,7 @@ public class ScrollCaptureViewSupport<V extends View> implements ScrollCaptureCa
@SyncAndDrawResult
public int renderView(View view, Rect sourceRect) {
HardwareRenderer.FrameRenderRequest request = mRenderer.createRenderRequest();
- request.setVsyncTime(SystemClock.elapsedRealtimeNanos());
+ request.setVsyncTime(System.nanoTime());
if (updateForView(view)) {
setupLighting(view);
}
diff --git a/core/jni/android_view_SurfaceControl.cpp b/core/jni/android_view_SurfaceControl.cpp
index c769da57eecc..4044c579a57f 100644
--- a/core/jni/android_view_SurfaceControl.cpp
+++ b/core/jni/android_view_SurfaceControl.cpp
@@ -1921,6 +1921,7 @@ static void nativeRemoveCurrentInputFocus(JNIEnv* env, jclass clazz, jlong trans
FocusRequest request;
request.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
request.displayId = displayId;
+ request.windowName = "<null>";
transaction->setFocusedWindow(request);
}
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index 0f328b034f38..8db5f9a1f51b 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -6441,11 +6441,11 @@
<!-- @SystemApi Must be required by a safety source to send an update using the
{@link android.safetycenter.SafetyCenterManager}.
- <p>Protection level: signature|privileged
+ <p>Protection level: internal|privileged
@hide
-->
<permission android:name="android.permission.SEND_SAFETY_CENTER_UPDATE"
- android:protectionLevel="signature|privileged" />
+ android:protectionLevel="internal|privileged" />
<!-- @SystemApi Allows an application to launch device manager setup screens.
<p>Not for use by third-party applications.
@@ -7044,7 +7044,7 @@
android:permission="android.permission.BIND_JOB_SERVICE">
</service>
- <service android:name="com.android.server.companion.AssociationCleanUpService"
+ <service android:name="com.android.server.companion.InactiveAssociationsRemovalService"
android:permission="android.permission.BIND_JOB_SERVICE">
</service>
diff --git a/core/res/res/anim-ldrtl/task_fragment_close_enter.xml b/core/res/res/anim-ldrtl/task_fragment_close_enter.xml
new file mode 100644
index 000000000000..e5f5707c9a20
--- /dev/null
+++ b/core/res/res/anim-ldrtl/task_fragment_close_enter.xml
@@ -0,0 +1,38 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ ~ Copyright (C) 2022 The Android Open Source Project
+ ~
+ ~ Licensed under the Apache License, Version 2.0 (the "License");
+ ~ you may not use this file except in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~ http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing, software
+ ~ distributed under the License is distributed on an "AS IS" BASIS,
+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions and
+ ~ limitations under the License.
+ -->
+
+<set xmlns:android="http://schemas.android.com/apk/res/android"
+ android:shareInterpolator="false">
+
+ <alpha
+ android:fromAlpha="1.0"
+ android:toAlpha="1.0"
+ android:fillEnabled="true"
+ android:fillBefore="true"
+ android:fillAfter="true"
+ android:interpolator="@interpolator/linear"
+ android:startOffset="0"
+ android:duration="200" />
+
+ <translate
+ android:fillEnabled="true"
+ android:fillBefore="true"
+ android:fillAfter="true"
+ android:interpolator="@interpolator/fast_out_extra_slow_in"
+ android:startOffset="0"
+ android:duration="200" />
+</set> \ No newline at end of file
diff --git a/core/res/res/anim-ldrtl/task_fragment_close_exit.xml b/core/res/res/anim-ldrtl/task_fragment_close_exit.xml
new file mode 100644
index 000000000000..c5a36542cc7d
--- /dev/null
+++ b/core/res/res/anim-ldrtl/task_fragment_close_exit.xml
@@ -0,0 +1,40 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ ~ Copyright (C) 2022 The Android Open Source Project
+ ~
+ ~ Licensed under the Apache License, Version 2.0 (the "License");
+ ~ you may not use this file except in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~ http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing, software
+ ~ distributed under the License is distributed on an "AS IS" BASIS,
+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions and
+ ~ limitations under the License.
+ -->
+
+<set xmlns:android="http://schemas.android.com/apk/res/android"
+ android:shareInterpolator="false">
+
+ <alpha
+ android:fromAlpha="1.0"
+ android:toAlpha="0.0"
+ android:fillEnabled="true"
+ android:fillBefore="true"
+ android:fillAfter="true"
+ android:interpolator="@interpolator/linear"
+ android:startOffset="35"
+ android:duration="83" />
+
+ <translate
+ android:fromXDelta="0"
+ android:toXDelta="-10%"
+ android:fillEnabled="true"
+ android:fillBefore="true"
+ android:fillAfter="true"
+ android:interpolator="@interpolator/fast_out_extra_slow_in"
+ android:startOffset="0"
+ android:duration="200" />
+</set> \ No newline at end of file
diff --git a/core/res/res/anim-ldrtl/task_fragment_open_enter.xml b/core/res/res/anim-ldrtl/task_fragment_open_enter.xml
new file mode 100644
index 000000000000..b6f1af3e7840
--- /dev/null
+++ b/core/res/res/anim-ldrtl/task_fragment_open_enter.xml
@@ -0,0 +1,40 @@
+<?xml version="1.0" encoding="utf-8"?><!--
+/*
+** Copyright 2022, The Android Open Source Project
+**
+** Licensed under the Apache License, Version 2.0 (the "License");
+** you may not use this file except in compliance with the License.
+** You may obtain a copy of the License at
+**
+** http://www.apache.org/licenses/LICENSE-2.0
+**
+** Unless required by applicable law or agreed to in writing, software
+** distributed under the License is distributed on an "AS IS" BASIS,
+** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+** See the License for the specific language governing permissions and
+** limitations under the License.
+*/
+-->
+
+<set xmlns:android="http://schemas.android.com/apk/res/android"
+ android:shareInterpolator="false">
+
+ <alpha
+ android:fromAlpha="0"
+ android:toAlpha="1.0"
+ android:fillEnabled="true"
+ android:fillBefore="true"
+ android:fillAfter="true"
+ android:interpolator="@interpolator/linear"
+ android:startOffset="50"
+ android:duration="83" />
+
+ <translate
+ android:fromXDelta="-10%"
+ android:toXDelta="0"
+ android:fillEnabled="true"
+ android:fillBefore="true"
+ android:fillAfter="true"
+ android:interpolator="@interpolator/fast_out_extra_slow_in"
+ android:duration="450" />
+</set> \ No newline at end of file
diff --git a/core/res/res/anim-ldrtl/task_fragment_open_exit.xml b/core/res/res/anim-ldrtl/task_fragment_open_exit.xml
new file mode 100644
index 000000000000..6cea53c3e934
--- /dev/null
+++ b/core/res/res/anim-ldrtl/task_fragment_open_exit.xml
@@ -0,0 +1,38 @@
+<?xml version="1.0" encoding="utf-8"?><!--
+/*
+** Copyright 2022, The Android Open Source Project
+**
+** Licensed under the Apache License, Version 2.0 (the "License");
+** you may not use this file except in compliance with the License.
+** You may obtain a copy of the License at
+**
+** http://www.apache.org/licenses/LICENSE-2.0
+**
+** Unless required by applicable law or agreed to in writing, software
+** distributed under the License is distributed on an "AS IS" BASIS,
+** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+** See the License for the specific language governing permissions and
+** limitations under the License.
+*/
+-->
+
+<set xmlns:android="http://schemas.android.com/apk/res/android"
+ android:shareInterpolator="false">
+
+ <alpha
+ android:fromAlpha="1.0"
+ android:toAlpha="1.0"
+ android:fillEnabled="true"
+ android:fillBefore="true"
+ android:fillAfter="true"
+ android:interpolator="@interpolator/standard_accelerate"
+ android:startOffset="0"
+ android:duration="450" />
+
+ <translate
+ android:fillEnabled="true"
+ android:fillBefore="true"
+ android:fillAfter="true"
+ android:interpolator="@interpolator/fast_out_extra_slow_in"
+ android:duration="450" />
+</set> \ No newline at end of file
diff --git a/core/res/res/anim/task_fragment_close_enter.xml b/core/res/res/anim/task_fragment_close_enter.xml
index c940552d53ad..cb6cdbeb71f4 100644
--- a/core/res/res/anim/task_fragment_close_enter.xml
+++ b/core/res/res/anim/task_fragment_close_enter.xml
@@ -17,16 +17,21 @@
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false">
- <scale
- android:fromXScale="1.1"
- android:toXScale="1"
- android:fromYScale="1.1"
- android:toYScale="1"
- android:pivotX="50%"
- android:pivotY="50%"
+ <alpha
+ android:fromAlpha="1.0"
+ android:toAlpha="1.0"
+ android:fillEnabled="true"
+ android:fillBefore="true"
+ android:fillAfter="true"
+ android:interpolator="@interpolator/linear"
+ android:startOffset="0"
+ android:duration="200" />
+
+ <translate
android:fillEnabled="true"
android:fillBefore="true"
android:fillAfter="true"
android:interpolator="@interpolator/fast_out_extra_slow_in"
- android:duration="400"/>
+ android:startOffset="0"
+ android:duration="200" />
</set> \ No newline at end of file
diff --git a/core/res/res/anim/task_fragment_close_exit.xml b/core/res/res/anim/task_fragment_close_exit.xml
index 8998f764ff9b..84d8b7e6b5cd 100644
--- a/core/res/res/anim/task_fragment_close_exit.xml
+++ b/core/res/res/anim/task_fragment_close_exit.xml
@@ -19,24 +19,21 @@
android:shareInterpolator="false"
android:zAdjustment="top">
<alpha
- android:fromAlpha="1"
+ android:fromAlpha="1.0"
android:toAlpha="0.0"
android:fillEnabled="true"
android:fillBefore="true"
android:fillAfter="true"
android:interpolator="@interpolator/linear"
- android:startOffset="33"
- android:duration="50"/>
- <scale
- android:fromXScale="1"
- android:toXScale="0.9"
- android:fromYScale="1"
- android:toYScale="0.9"
- android:pivotX="50%"
- android:pivotY="50%"
+ android:startOffset="0"
+ android:duration="83" />
+
+ <translate
+ android:fromXDelta="0"
+ android:toXDelta="10%"
android:fillEnabled="true"
android:fillBefore="true"
android:fillAfter="true"
android:interpolator="@interpolator/fast_out_extra_slow_in"
- android:duration="400"/>
+ android:duration="200" />
</set>
diff --git a/core/res/res/anim/task_fragment_open_enter.xml b/core/res/res/anim/task_fragment_open_enter.xml
index 6bc47deb2de4..aa61e6f17070 100644
--- a/core/res/res/anim/task_fragment_open_enter.xml
+++ b/core/res/res/anim/task_fragment_open_enter.xml
@@ -25,17 +25,13 @@
android:fillAfter="true"
android:interpolator="@interpolator/linear"
android:startOffset="50"
- android:duration="50"/>
- <scale
- android:fromXScale="0.85"
- android:toXScale="1"
- android:fromYScale="0.85"
- android:toYScale="1"
- android:pivotX="50%"
- android:pivotY="50%"
+ android:duration="83" />
+ <translate
+ android:fromXDelta="10%"
+ android:toXDelta="0"
android:fillEnabled="true"
android:fillBefore="true"
android:fillAfter="true"
android:interpolator="@interpolator/fast_out_extra_slow_in"
- android:duration="400"/>
+ android:duration="400" />
</set>
diff --git a/core/res/res/anim/task_fragment_open_exit.xml b/core/res/res/anim/task_fragment_open_exit.xml
index 160eb84223da..b4914d21d097 100644
--- a/core/res/res/anim/task_fragment_open_exit.xml
+++ b/core/res/res/anim/task_fragment_open_exit.xml
@@ -17,16 +17,20 @@
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false">
- <scale
- android:fromXScale="1"
- android:toXScale="1.05"
- android:fromYScale="1"
- android:toYScale="1.05"
- android:pivotX="50%"
- android:pivotY="50%"
+ <alpha
+ android:fromAlpha="1.0"
+ android:toAlpha="1.0"
+ android:fillEnabled="true"
+ android:fillBefore="true"
+ android:fillAfter="true"
+ android:interpolator="@interpolator/standard_accelerate"
+ android:startOffset="0"
+ android:duration="400" />
+
+ <translate
android:fillEnabled="true"
android:fillBefore="true"
android:fillAfter="true"
android:interpolator="@interpolator/fast_out_extra_slow_in"
- android:duration="400"/>
+ android:duration="400" />
</set> \ No newline at end of file
diff --git a/core/res/res/layout/miniresolver.xml b/core/res/res/layout/miniresolver.xml
index 44ed6f2a0676..85fe2835fd5e 100644
--- a/core/res/res/layout/miniresolver.xml
+++ b/core/res/res/layout/miniresolver.xml
@@ -24,12 +24,11 @@
android:id="@id/contentPanel">
<RelativeLayout
- android:id="@+id/title_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alwaysShow="true"
android:elevation="@dimen/resolver_elevation"
- android:paddingTop="@dimen/resolver_small_margin"
+ android:paddingTop="24dp"
android:paddingStart="@dimen/resolver_edge_margin"
android:paddingEnd="@dimen/resolver_edge_margin"
android:paddingBottom="@dimen/resolver_title_padding_bottom"
@@ -47,8 +46,12 @@
android:id="@+id/open_cross_profile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
+ android:paddingTop="16dp"
android:layout_below="@id/icon"
android:layout_centerHorizontal="true"
+ android:textSize="24sp"
+ android:lineHeight="32sp"
+ android:gravity="center"
android:textColor="?android:textColorPrimary"
/>
</RelativeLayout>
@@ -58,15 +61,11 @@
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alwaysShow="true"
+ android:paddingTop="32dp"
+ android:paddingBottom="@dimen/resolver_button_bar_spacing"
android:orientation="vertical"
android:background="?attr/colorBackground"
android:layout_ignoreOffset="true">
- <View
- android:id="@+id/resolver_button_bar_divider"
- android:layout_width="match_parent"
- android:layout_height="1dp"
- android:background="?attr/colorBackground"
- android:foreground="?attr/dividerVertical" />
<RelativeLayout
style="?attr/buttonBarStyle"
android:layout_width="match_parent"
@@ -77,7 +76,6 @@
android:orientation="horizontal"
android:layoutDirection="locale"
android:measureWithLargestChild="true"
- android:paddingTop="@dimen/resolver_button_bar_spacing"
android:paddingBottom="@dimen/resolver_button_bar_spacing"
android:paddingStart="@dimen/resolver_edge_margin"
android:paddingEnd="@dimen/resolver_small_margin"
diff --git a/core/res/res/values-mcc262/config.xml b/core/res/res/values-mcc262/config.xml
index 79eefb7cecbe..d234061c8fda 100644
--- a/core/res/res/values-mcc262/config.xml
+++ b/core/res/res/values-mcc262/config.xml
@@ -21,5 +21,5 @@
for different hardware and product builds. -->
<resources>
<!-- Set to false to disable emergency alert. -->
- <bool name="config_cellBroadcastAppLinks">false</bool>
+ <bool name="config_cellBroadcastAppLinks">true</bool>
</resources> \ No newline at end of file
diff --git a/core/res/res/values/colors.xml b/core/res/res/values/colors.xml
index 5df3dde82b3e..b515abc4000f 100644
--- a/core/res/res/values/colors.xml
+++ b/core/res/res/values/colors.xml
@@ -448,5 +448,6 @@
<color name="accessibility_color_inversion_background">#546E7A</color>
<!-- Color of camera light when camera is in use -->
- <color name="camera_privacy_light">#FFFFFF</color>
+ <color name="camera_privacy_light_day">#FFFFFF</color>
+ <color name="camera_privacy_light_night">#FFFFFF</color>
</resources>
diff --git a/core/res/res/values/config.xml b/core/res/res/values/config.xml
index e38b5b6fbc39..2d508e6151cb 100644
--- a/core/res/res/values/config.xml
+++ b/core/res/res/values/config.xml
@@ -1869,6 +1869,11 @@
-->
<string name="config_defaultSearchSelectorPackageName" translatable="false"></string>
+ <!-- The package name of the default captive portal login app. Must be granted the
+ POST_NOTIFICATIONS permission.
+ -->
+ <string name="config_defaultCaptivePortalLoginPackageName" translatable="false"></string>
+
<!-- Whether to enable geocoder overlay which allows geocoder to be replaced
by an app at run-time. When disabled, only the
config_geocoderProviderPackageName package will be searched for
@@ -2998,12 +3003,6 @@
</string-array>
- <!-- When migrating notification settings into the permission framework, whether all existing
- apps should be marked as 'user-set' (true) or whether only the apps that have explicitly
- modified notification settings should be marked as 'user-set' (false). Users will not see
- system generated permission prompts for 'user-set' apps. -->
- <bool name="config_notificationForceUserSetOnUpgrade">true</bool>
-
<!-- Default Gravity setting for the system Toast view. Equivalent to: Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM -->
<integer name="config_toastDefaultGravity">0x00000051</integer>
@@ -4898,7 +4897,7 @@
<!-- Whether or not to hide the navigation bar when the soft keyboard is visible in order to
create additional screen real estate outside beyond the keyboard. Note that the user needs
to have a confirmed way to dismiss the keyboard when desired. -->
- <bool name="config_automotiveHideNavBarForKeyboard">false</bool>
+ <bool name="config_hideNavBarForKeyboard">false</bool>
<!-- Whether or not to show the built-in charging animation when the device begins charging
wirelessly. -->
@@ -5133,16 +5132,24 @@
-->
<color name="config_letterboxBackgroundColor">@android:color/system_neutral2_900</color>
- <!-- Horizonal position of a center of the letterboxed app window.
+ <!-- Horizontal position of a center of the letterboxed app window.
0 corresponds to the left side of the screen and 1 to the right side. If given value < 0
- or > 1, it is ignored and central positionis used (0.5). -->
+ or > 1, it is ignored and central position is used (0.5). -->
<item name="config_letterboxHorizontalPositionMultiplier" format="float" type="dimen">0.5</item>
- <!-- Whether reachability repositioning is allowed for letterboxed fullscreen apps in landscape
- device orientation. -->
- <bool name="config_letterboxIsReachabilityEnabled">false</bool>
+ <!-- Vertical position of a center of the letterboxed app window.
+ 0 corresponds to the upper side of the screen and 1 to the lower side. If given value < 0
+ or > 1, it is ignored and central position is used (0.5). -->
+ <item name="config_letterboxVerticalPositionMultiplier" format="float" type="dimen">0.5</item>
+
+ <!-- Whether horizontal reachability repositioning is allowed for letterboxed fullscreen apps.
+ -->
+ <bool name="config_letterboxIsHorizontalReachabilityEnabled">false</bool>
+
+ <!-- Whether vertical reachability repositioning is allowed for letterboxed fullscreen apps. -->
+ <bool name="config_letterboxIsVerticalReachabilityEnabled">false</bool>
- <!-- Default horizonal position of the letterboxed app window when reachability is
+ <!-- Default horizontal position of the letterboxed app window when reachability is
enabled and an app is fullscreen in landscape device orientation. When reachability is
enabled, the position can change between left, center and right. This config defines the
default one:
@@ -5150,7 +5157,17 @@
- Option 1 - Center.
- Option 2 - Right.
If given value is outside of this range, the option 1 (center) is assummed. -->
- <integer name="config_letterboxDefaultPositionForReachability">1</integer>
+ <integer name="config_letterboxDefaultPositionForHorizontalReachability">1</integer>
+
+ <!-- Default vertical position of the letterboxed app window when reachability is
+ enabled and an app is fullscreen in portrait device orientation. When reachability is
+ enabled, the position can change between top, center and bottom. This config defines the
+ default one:
+ - Option 0 - Top.
+ - Option 1 - Center.
+ - Option 2 - Bottom.
+ If given value is outside of this range, the option 1 (center) is assummed. -->
+ <integer name="config_letterboxDefaultPositionForVerticalReachability">1</integer>
<!-- Whether displaying letterbox education is enabled for letterboxed fullscreen apps. -->
<bool name="config_letterboxIsEducationEnabled">false</bool>
@@ -5665,6 +5682,9 @@
<!-- Whether or not to enable the lock screen entry point for the QR code scanner. -->
<bool name="config_enableQrCodeScannerOnLockScreen">false</bool>
+ <!-- Default component for QR code scanner -->
+ <string name="config_defaultQrCodeComponent"></string>
+
<!-- Whether Low Power Standby is supported and can be enabled. -->
<bool name="config_lowPowerStandbySupported">false</bool>
@@ -5755,6 +5775,14 @@
-->
<integer name="config_bg_current_drain_location_min_duration">1800</integer>
+ <!-- The behavior when the system detects it has abusive current drains, whether or not to
+ move the app to the restricted standby bucket level.
+ True - we'll move the app to restricted standby bucket as long as its bg battery usage
+ goes beyond the threshold, False - we'll not move it.
+ Note: This should be only enabled on devices with high confidence on power measurement.
+ -->
+ <bool name="config_bg_current_drain_auto_restrict_abusive_apps">false</bool>
+
<!-- The behavior for an app with a FGS and its notification is still showing, when the system
detects it's abusive and should be put into bg restricted level. True - we'll
show the prompt to user, False - we'll not show it.
@@ -5790,4 +5818,20 @@
<!-- List of the labels of requestable device state config values -->
<string-array name="config_deviceStatesAvailableForAppRequests"/>
+
+ <!-- Interval in milliseconds to average light sensor values for camera light brightness -->
+ <integer name="config_cameraPrivacyLightAlsAveragingIntervalMillis">3000</integer>
+ <!-- Light sensor's lux value to use as the threshold between using day or night brightness -->
+ <integer name="config_cameraPrivacyLightAlsNightThreshold">4</integer>
+
+ <!-- List of system components which are allowed to receive ServiceState entries in an
+ un-sanitized form, even if the location toggle is off. This is intended ONLY for system
+ components, such as the telephony stack, which require access to the full ServiceState for
+ tasks such as network registration. -->
+ <string-array name="config_serviceStateLocationAllowedPackages">
+ <item>"com.android.phone"</item>
+ </string-array>
+
+ <!-- Whether the wake screen on notifications feature is available. -->
+ <bool name="config_pulseOnNotificationsAvailable">true</bool>
</resources>
diff --git a/core/res/res/values/config_telephony.xml b/core/res/res/values/config_telephony.xml
index d9ac5164f705..682ce46d132d 100644
--- a/core/res/res/values/config_telephony.xml
+++ b/core/res/res/values/config_telephony.xml
@@ -35,7 +35,7 @@
rmem_min,rmem_def,rmem_max,wmem_min,wmem_def,wmem_max
If this is configured as an empty string, the system default will be applied.
-->
- <string name="config_tcp_buffers" translatable="false"></string>
+ <string name="config_tcp_buffers" translatable="false">2097152,6291456,16777216,512000,2097152,8388608</string>
<java-symbol type="string" name="config_tcp_buffers" />
<!-- What source to use to estimate link upstream and downstream bandwidth capacities.
diff --git a/core/res/res/values/strings.xml b/core/res/res/values/strings.xml
index a4be0b9e01dc..c6b60f586047 100644
--- a/core/res/res/values/strings.xml
+++ b/core/res/res/values/strings.xml
@@ -876,9 +876,9 @@
<string name="permgroupdesc_sms">send and view SMS messages</string>
<!-- Title of a category of application permissions, listed so the user can choose whether they want to allow the application to do this. -->
- <string name="permgrouplab_storage">Files and documents</string>
+ <string name="permgrouplab_storage">Files</string>
<!-- Description of a category of application permissions, listed so the user can choose whether they want to allow the application to do this. -->
- <string name="permgroupdesc_storage">access files and documents on your device</string>
+ <string name="permgroupdesc_storage">access files on your device</string>
<!-- Title of a category of application permissions, listed so the user can choose whether they want to allow the application to do this. [CHAR LIMIT=40]-->
<string name="permgrouplab_readMediaAural">Music and audio</string>
@@ -6325,5 +6325,5 @@ ul.</string>
<string name="vdm_camera_access_denied" product="tablet">Can’t access the tablet’s camera from your <xliff:g id="device" example="Chromebook">%1$s</xliff:g></string>
<!-- Title for preference of the system default locale. [CHAR LIMIT=50]-->
- <string name="system_locale_title">System language</string>
+ <string name="system_locale_title">System default</string>
</resources>
diff --git a/core/res/res/values/symbols.xml b/core/res/res/values/symbols.xml
index f505ffb21e2f..dfc02a41b025 100644
--- a/core/res/res/values/symbols.xml
+++ b/core/res/res/values/symbols.xml
@@ -3337,6 +3337,7 @@
<java-symbol type="string" name="config_dozeTapSensorType" />
<java-symbol type="array" name="config_dozeTapSensorPostureMapping" />
<java-symbol type="bool" name="config_dozePulsePickup" />
+ <java-symbol type="bool" name="config_pulseOnNotificationsAvailable" />
<!-- Used for MimeIconUtils. -->
<java-symbol type="drawable" name="ic_doc_apk" />
@@ -3425,6 +3426,9 @@
<!-- Search Selector -->
<java-symbol type="string" name="config_defaultSearchSelectorPackageName" />
+ <!-- Captive Portal Login -->
+ <java-symbol type="string" name="config_defaultCaptivePortalLoginPackageName" />
+
<!-- Optional IPsec algorithms -->
<java-symbol type="array" name="config_optionalIpSecAlgorithms" />
@@ -4157,7 +4161,7 @@
<java-symbol type="bool" name="config_disable_all_cb_messages" />
<java-symbol type="drawable" name="ic_close" />
- <java-symbol type="bool" name="config_automotiveHideNavBarForKeyboard" />
+ <java-symbol type="bool" name="config_hideNavBarForKeyboard" />
<java-symbol type="bool" name="config_showBuiltinWirelessChargingAnim" />
@@ -4384,8 +4388,11 @@
<java-symbol type="integer" name="config_letterboxBackgroundType" />
<java-symbol type="color" name="config_letterboxBackgroundColor" />
<java-symbol type="dimen" name="config_letterboxHorizontalPositionMultiplier" />
- <java-symbol type="bool" name="config_letterboxIsReachabilityEnabled" />
- <java-symbol type="integer" name="config_letterboxDefaultPositionForReachability" />
+ <java-symbol type="dimen" name="config_letterboxVerticalPositionMultiplier" />
+ <java-symbol type="bool" name="config_letterboxIsHorizontalReachabilityEnabled" />
+ <java-symbol type="bool" name="config_letterboxIsVerticalReachabilityEnabled" />
+ <java-symbol type="integer" name="config_letterboxDefaultPositionForHorizontalReachability" />
+ <java-symbol type="integer" name="config_letterboxDefaultPositionForVerticalReachability" />
<java-symbol type="bool" name="config_letterboxIsEducationEnabled" />
<java-symbol type="bool" name="config_isCameraCompatControlForStretchedIssuesEnabled" />
@@ -4714,6 +4721,7 @@
<java-symbol type="string" name="config_wearSysUiPackage"/>
<java-symbol type="string" name="config_wearSysUiMainActivity"/>
+ <java-symbol type="string" name="config_defaultQrCodeComponent"/>
<java-symbol type="dimen" name="secondary_rounded_corner_radius" />
<java-symbol type="dimen" name="secondary_rounded_corner_radius_top" />
@@ -4759,7 +4767,10 @@
<!-- For VirtualDeviceManager -->
<java-symbol type="string" name="vdm_camera_access_denied" />
- <java-symbol type="color" name="camera_privacy_light"/>
+ <java-symbol type="color" name="camera_privacy_light_day"/>
+ <java-symbol type="color" name="camera_privacy_light_night"/>
+ <java-symbol type="integer" name="config_cameraPrivacyLightAlsAveragingIntervalMillis"/>
+ <java-symbol type="integer" name="config_cameraPrivacyLightAlsNightThreshold"/>
<java-symbol type="bool" name="config_bg_current_drain_monitor_enabled" />
<java-symbol type="array" name="config_bg_current_drain_threshold_to_restricted_bucket" />
@@ -4773,13 +4784,14 @@
<java-symbol type="array" name="config_bg_current_drain_high_threshold_to_bg_restricted" />
<java-symbol type="integer" name="config_bg_current_drain_media_playback_min_duration" />
<java-symbol type="integer" name="config_bg_current_drain_location_min_duration" />
+ <java-symbol type="bool" name="config_bg_current_drain_auto_restrict_abusive_apps" />
<java-symbol type="bool" name="config_bg_prompt_fgs_with_noti_to_bg_restricted" />
<java-symbol type="bool" name="config_bg_prompt_abusive_apps_to_bg_restricted" />
<java-symbol type="integer" name="config_bg_current_drain_exempted_types" />
<java-symbol type="bool" name="config_bg_current_drain_high_threshold_by_bg_location" />
<java-symbol type="drawable" name="ic_swap_horiz" />
- <java-symbol type="bool" name="config_notificationForceUserSetOnUpgrade" />
<java-symbol type="array" name="config_deviceStatesAvailableForAppRequests" />
+ <java-symbol type="array" name="config_serviceStateLocationAllowedPackages" />
<!-- For app language picker -->
<java-symbol type="string" name="system_locale_title" />
diff --git a/core/tests/coretests/src/android/app/activity/ActivityThreadTest.java b/core/tests/coretests/src/android/app/activity/ActivityThreadTest.java
index bfb2fd57975f..a2d4bafef41c 100644
--- a/core/tests/coretests/src/android/app/activity/ActivityThreadTest.java
+++ b/core/tests/coretests/src/android/app/activity/ActivityThreadTest.java
@@ -31,7 +31,6 @@ import static org.junit.Assert.assertTrue;
import android.annotation.Nullable;
import android.app.Activity;
-import android.app.ActivityManager;
import android.app.ActivityThread;
import android.app.ActivityThread.ActivityClientRecord;
import android.app.IApplicationThread;
@@ -571,53 +570,6 @@ public class ActivityThreadTest {
}
@Test
- public void testHandleProcessConfigurationChanged_DependOnProcessState() {
- final ActivityThread activityThread = ActivityThread.currentActivityThread();
- final Configuration origConfig = activityThread.getConfiguration();
- final int newDpi = origConfig.densityDpi + 10;
- final Configuration newConfig = new Configuration(origConfig);
- newConfig.seq++;
- newConfig.densityDpi = newDpi;
-
- activityThread.updateProcessState(ActivityManager.PROCESS_STATE_CACHED_ACTIVITY,
- false /* fromIPC */);
-
- applyProcessConfiguration(activityThread, newConfig);
- try {
- // In the cached state, the configuration is only set as pending and not applied.
- assertEquals(origConfig.densityDpi, activityThread.getConfiguration().densityDpi);
- assertTrue(activityThread.isCachedProcessState());
- } finally {
- // The foreground state is the default state of instrumentation.
- activityThread.updateProcessState(ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE,
- false /* fromIPC */);
- }
- InstrumentationRegistry.getInstrumentation().waitForIdleSync();
-
- try {
- // The state becomes non-cached, the pending configuration should be applied.
- assertEquals(newConfig.densityDpi, activityThread.getConfiguration().densityDpi);
- assertFalse(activityThread.isCachedProcessState());
- } finally {
- // Restore to the original configuration.
- activityThread.getConfiguration().seq = origConfig.seq - 1;
- applyProcessConfiguration(activityThread, origConfig);
- }
- }
-
- private static void applyProcessConfiguration(ActivityThread thread, Configuration config) {
- final ClientTransaction clientTransaction = newTransaction(thread,
- null /* activityToken */);
- clientTransaction.addCallback(ConfigurationChangeItem.obtain(config));
- final IApplicationThread appThread = thread.getApplicationThread();
- try {
- appThread.scheduleTransaction(clientTransaction);
- } catch (Exception ignored) {
- }
- InstrumentationRegistry.getInstrumentation().waitForIdleSync();
- }
-
- @Test
public void testResumeAfterNewIntent() {
final Activity activity = mActivityTestRule.launchActivity(new Intent());
final ActivityThread activityThread = activity.getActivityThread();
diff --git a/core/tests/coretests/src/android/content/pm/AppSearchShortcutInfoTest.java b/core/tests/coretests/src/android/content/pm/AppSearchShortcutInfoTest.java
index 969357f66dde..22feecbd899f 100644
--- a/core/tests/coretests/src/android/content/pm/AppSearchShortcutInfoTest.java
+++ b/core/tests/coretests/src/android/content/pm/AppSearchShortcutInfoTest.java
@@ -24,7 +24,6 @@ import android.content.Intent;
import android.platform.test.annotations.Presubmit;
import android.util.ArraySet;
-import org.junit.Ignore;
import org.junit.Test;
import java.util.Set;
@@ -32,7 +31,6 @@ import java.util.Set;
@Presubmit
public class AppSearchShortcutInfoTest {
- @Ignore("b/208375334")
@Test
public void testBuildShortcutAndGetValue() {
final String category =
@@ -51,7 +49,7 @@ public class AppSearchShortcutInfoTest {
final Intent shortcutIntent = new Intent(Intent.ACTION_VIEW);
final ShortcutInfo shortcut = new AppSearchShortcutInfo.Builder(/*packageName=*/"", id)
.setActivity(activity)
- .setLongLabel(id)
+ .setShortLabel(id)
.setIconResName(shortcutIconResName)
.setIntent(shortcutIntent)
.setPerson(person)
@@ -64,11 +62,13 @@ public class AppSearchShortcutInfoTest {
assertThat(shortcut.getId()).isEqualTo(id);
assertThat(shortcut.getShortLabel()).isEqualTo(id);
assertThat(shortcut.getIconResName()).isEqualTo(shortcutIconResName);
- assertThat(shortcut.getIntent().toString()).isEqualTo(shortcut.toString());
+ assertThat(shortcut.getIntent().toString()).isEqualTo(shortcutIntent.toString());
assertThat(shortcut.getPersons().length).isEqualTo(1);
- assertThat(shortcut.getPersons()[0]).isEqualTo(person);
+ final Person target = shortcut.getPersons()[0];
+ assertThat(target.getName()).isEqualTo(person.getName());
+ assertThat(target.isBot()).isEqualTo(person.isBot());
+ assertThat(target.isImportant()).isEqualTo(person.isImportant());
assertThat(shortcut.getCategories()).isEqualTo(categorySet);
- assertThat(shortcut.getFlags()).isEqualTo(ShortcutInfo.FLAG_LONG_LIVED);
assertThat(shortcut.getActivity()).isEqualTo(activity);
}
}
diff --git a/core/tests/coretests/src/android/view/RenderNodeAnimatorTest.java b/core/tests/coretests/src/android/view/RenderNodeAnimatorTest.java
index 786c22bf04f6..9b6bcda8aed0 100644
--- a/core/tests/coretests/src/android/view/RenderNodeAnimatorTest.java
+++ b/core/tests/coretests/src/android/view/RenderNodeAnimatorTest.java
@@ -19,17 +19,24 @@ package android.view;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
+import android.animation.Animator;
+import android.animation.AnimatorListenerAdapter;
import android.app.Activity;
import android.content.Context;
+import android.widget.FrameLayout;
import androidx.test.InstrumentationRegistry;
import androidx.test.annotation.UiThreadTest;
import androidx.test.filters.MediumTest;
import androidx.test.rule.ActivityTestRule;
+import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
@MediumTest
public class RenderNodeAnimatorTest {
@Rule
@@ -57,4 +64,46 @@ public class RenderNodeAnimatorTest {
anim.start(); // should initialize mTransformationInfo
assertNotNull(view.mTransformationInfo);
}
+
+ @Test
+ public void testViewDetachCancelsRenderNodeAnimator() {
+ // Start a RenderNodeAnimator with a long duration time, then detach the target view
+ // before the animation completes. Detaching of a View from a window should force cancel all
+ // RenderNodeAnimators
+ CountDownLatch latch = new CountDownLatch(1);
+
+ FrameLayout container = new FrameLayout(getContext());
+ View view = new View(getContext());
+
+ getActivity().runOnUiThread(() -> {
+ container.addView(view, new FrameLayout.LayoutParams(100, 100));
+ getActivity().setContentView(container);
+ });
+ getActivity().runOnUiThread(() -> {
+ RenderNodeAnimator anim = new RenderNodeAnimator(0, 0, 10f, 30f);
+ anim.setDuration(10000);
+ anim.setTarget(view);
+ anim.addListener(new AnimatorListenerAdapter() {
+
+ @Override
+ public void onAnimationEnd(Animator animation) {
+ super.onAnimationEnd(animation);
+ latch.countDown();
+ }
+ });
+
+ anim.start();
+ });
+
+ getActivity().runOnUiThread(()-> {
+ container.removeView(view);
+ });
+
+ try {
+ Assert.assertTrue("onAnimationEnd not invoked",
+ latch.await(3000, TimeUnit.MILLISECONDS));
+ } catch (InterruptedException excep) {
+ Assert.fail("Interrupted waiting for onAnimationEnd callback");
+ }
+ }
}
diff --git a/core/tests/coretests/src/com/android/internal/app/ResolverWrapperActivity.java b/core/tests/coretests/src/com/android/internal/app/ResolverWrapperActivity.java
index 0c009a055e2b..4cf9c3fe75b9 100644
--- a/core/tests/coretests/src/com/android/internal/app/ResolverWrapperActivity.java
+++ b/core/tests/coretests/src/com/android/internal/app/ResolverWrapperActivity.java
@@ -39,6 +39,10 @@ public class ResolverWrapperActivity extends ResolverActivity {
static final OverrideData sOverrides = new OverrideData();
private UsageStatsManager mUsm;
+ public ResolverWrapperActivity() {
+ super(/* isIntentPicker= */ true);
+ }
+
@Override
public ResolverListAdapter createResolverListAdapter(Context context,
List<Intent> payloadIntents, Intent[] initialIntents, List<ResolveInfo> rList,
diff --git a/core/tests/coretests/src/com/android/internal/os/BatteryStatsNoteTest.java b/core/tests/coretests/src/com/android/internal/os/BatteryStatsNoteTest.java
index 87c45dccfa0c..d19f9f5ea58f 100644
--- a/core/tests/coretests/src/com/android/internal/os/BatteryStatsNoteTest.java
+++ b/core/tests/coretests/src/com/android/internal/os/BatteryStatsNoteTest.java
@@ -47,6 +47,7 @@ import android.telephony.DataConnectionRealTimeInfo;
import android.telephony.ModemActivityInfo;
import android.telephony.ServiceState;
import android.telephony.TelephonyManager;
+import android.util.MutableInt;
import android.util.SparseIntArray;
import android.util.SparseLongArray;
import android.view.Display;
@@ -1982,6 +1983,54 @@ public class BatteryStatsNoteTest extends TestCase {
expectedTxDurationsMs, bi, state.currentTimeMs);
}
+ @SmallTest
+ @SuppressWarnings("GuardedBy")
+ public void testProcStateSyncScheduling_mobileRadioActiveState() {
+ final MockClock clock = new MockClock(); // holds realtime and uptime in ms
+ final MockBatteryStatsImpl bi = new MockBatteryStatsImpl(clock);
+ final MutableInt lastProcStateChangeFlags = new MutableInt(0);
+
+ MockBatteryStatsImpl.DummyExternalStatsSync externalStatsSync =
+ new MockBatteryStatsImpl.DummyExternalStatsSync() {
+ @Override
+ public void scheduleSyncDueToProcessStateChange(int flags,
+ long delayMillis) {
+ lastProcStateChangeFlags.value = flags;
+ }
+ };
+
+ bi.setDummyExternalStatsSync(externalStatsSync);
+
+ bi.updateTimeBasesLocked(true, Display.STATE_OFF, 0, 0);
+
+ // Note mobile radio is on.
+ long curr = 1000L * (clock.realtime = clock.uptime = 1001);
+ bi.noteMobileRadioPowerStateLocked(DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH, curr,
+ UID);
+
+ lastProcStateChangeFlags.value = 0;
+ clock.realtime = clock.uptime = 2002;
+ bi.noteUidProcessStateLocked(UID, ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND);
+
+ final int allProcFlags = BatteryStatsImpl.ExternalStatsSync.UPDATE_ON_PROC_STATE_CHANGE;
+ assertEquals(allProcFlags, lastProcStateChangeFlags.value);
+
+ // Note mobile radio is off.
+ curr = 1000L * (clock.realtime = clock.uptime = 3003);
+ bi.noteMobileRadioPowerStateLocked(DataConnectionRealTimeInfo.DC_POWER_STATE_LOW, curr,
+ UID);
+
+ lastProcStateChangeFlags.value = 0;
+ clock.realtime = clock.uptime = 4004;
+ bi.noteUidProcessStateLocked(UID, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
+
+ final int noRadioProcFlags = BatteryStatsImpl.ExternalStatsSync.UPDATE_ON_PROC_STATE_CHANGE
+ & ~BatteryStatsImpl.ExternalStatsSync.UPDATE_RADIO;
+ assertEquals(
+ "An inactive radio should not be queried on proc state change",
+ noRadioProcFlags, lastProcStateChangeFlags.value);
+ }
+
private void setFgState(int uid, boolean fgOn, MockBatteryStatsImpl bi) {
// Note that noteUidProcessStateLocked uses ActivityManager process states.
if (fgOn) {
diff --git a/core/tests/coretests/src/com/android/internal/os/MockBatteryStatsImpl.java b/core/tests/coretests/src/com/android/internal/os/MockBatteryStatsImpl.java
index 00154a3d23b0..edeb5e9f4834 100644
--- a/core/tests/coretests/src/com/android/internal/os/MockBatteryStatsImpl.java
+++ b/core/tests/coretests/src/com/android/internal/os/MockBatteryStatsImpl.java
@@ -212,7 +212,12 @@ public class MockBatteryStatsImpl extends BatteryStatsImpl {
return flags;
}
- private class DummyExternalStatsSync implements ExternalStatsSync {
+ public void setDummyExternalStatsSync(DummyExternalStatsSync externalStatsSync) {
+ mExternalStatsSync = externalStatsSync;
+ setExternalStatsSyncLocked(mExternalStatsSync);
+ }
+
+ public static class DummyExternalStatsSync implements ExternalStatsSync {
public int flags = 0;
@Override
@@ -257,8 +262,7 @@ public class MockBatteryStatsImpl extends BatteryStatsImpl {
}
@Override
- public Future<?> scheduleSyncDueToProcessStateChange(long delayMillis) {
- return null;
+ public void scheduleSyncDueToProcessStateChange(int flags, long delayMillis) {
}
}
}
diff --git a/data/etc/com.android.systemui.xml b/data/etc/com.android.systemui.xml
index ebf5832147f7..f030d80a3533 100644
--- a/data/etc/com.android.systemui.xml
+++ b/data/etc/com.android.systemui.xml
@@ -80,5 +80,6 @@
<permission name="android.permission.READ_COMPAT_CHANGE_CONFIG" />
<permission name="android.permission.READ_DEVICE_CONFIG" />
<permission name="android.permission.READ_SAFETY_CENTER_STATUS" />
+ <permission name="android.permission.SET_UNRESTRICTED_KEEP_CLEAR_AREAS" />
</privapp-permissions>
</permissions>
diff --git a/data/etc/services.core.protolog.json b/data/etc/services.core.protolog.json
index 5ded2ccf8640..3e6fa56f698e 100644
--- a/data/etc/services.core.protolog.json
+++ b/data/etc/services.core.protolog.json
@@ -163,6 +163,12 @@
"group": "WM_ERROR",
"at": "com\/android\/server\/wm\/WindowManagerService.java"
},
+ "-1941440781": {
+ "message": "Creating Pending Move-to-back: %s",
+ "level": "VERBOSE",
+ "group": "WM_DEBUG_WINDOW_TRANSITIONS",
+ "at": "com\/android\/server\/wm\/Task.java"
+ },
"-1939861963": {
"message": "Create root task displayId=%d winMode=%d",
"level": "VERBOSE",
@@ -469,6 +475,12 @@
"group": "WM_DEBUG_ADD_REMOVE",
"at": "com\/android\/server\/wm\/ResetTargetTaskHelper.java"
},
+ "-1635750891": {
+ "message": "Received remote change for Display[%d], applied: [%dx%d, rot = %d]",
+ "level": "VERBOSE",
+ "group": "WM_DEBUG_CONFIGURATION",
+ "at": "com\/android\/server\/wm\/RemoteDisplayChangeController.java"
+ },
"-1633115609": {
"message": "Key dispatch not paused for screen off",
"level": "VERBOSE",
@@ -2923,12 +2935,6 @@
"group": "WM_DEBUG_LOCKTASK",
"at": "com\/android\/server\/wm\/ActivityTaskManagerService.java"
},
- "716528224": {
- "message": "Focused window found using wmService.getFocusedWindowLocked()",
- "level": "DEBUG",
- "group": "WM_DEBUG_BACK_PREVIEW",
- "at": "com\/android\/server\/wm\/BackNavigationController.java"
- },
"726205185": {
"message": "Moving to DESTROYED: %s (destroy skipped)",
"level": "VERBOSE",
@@ -3397,12 +3403,6 @@
"group": "WM_DEBUG_BOOT",
"at": "com\/android\/server\/wm\/WindowManagerService.java"
},
- "1246035185": {
- "message": "stopFreezingDisplayLocked: Returning waitingForConfig=%b, waitingForRemoteRotation=%b, mAppsFreezingScreen=%d, mWindowsFreezingScreen=%d, mClientFreezingScreen=%b, mOpeningApps.size()=%d",
- "level": "DEBUG",
- "group": "WM_DEBUG_ORIENTATION",
- "at": "com\/android\/server\/wm\/WindowManagerService.java"
- },
"1252594551": {
"message": "Window types in WindowContext and LayoutParams.type should match! Type from LayoutParams is %d, but type from WindowContext is %d",
"level": "WARN",
@@ -3499,6 +3499,12 @@
"group": "WM_DEBUG_ORIENTATION",
"at": "com\/android\/server\/wm\/ScreenRotationAnimation.java"
},
+ "1360176455": {
+ "message": "stopFreezingDisplayLocked: Returning waitingForConfig=%b, waitingForRemoteDisplayChange=%b, mAppsFreezingScreen=%d, mWindowsFreezingScreen=%d, mClientFreezingScreen=%b, mOpeningApps.size()=%d",
+ "level": "DEBUG",
+ "group": "WM_DEBUG_ORIENTATION",
+ "at": "com\/android\/server\/wm\/WindowManagerService.java"
+ },
"1364126018": {
"message": "Resumed activity; dropping state of: %s",
"level": "INFO",
@@ -3523,6 +3529,12 @@
"group": "WM_DEBUG_ORIENTATION",
"at": "com\/android\/server\/wm\/TaskDisplayArea.java"
},
+ "1393721079": {
+ "message": "Starting remote display change: from [rot = %d], to [%dx%d, rot = %d]",
+ "level": "VERBOSE",
+ "group": "WM_DEBUG_CONFIGURATION",
+ "at": "com\/android\/server\/wm\/RemoteDisplayChangeController.java"
+ },
"1396893178": {
"message": "createRootTask unknown displayId=%d",
"level": "ERROR",
@@ -3865,6 +3877,12 @@
"group": "WM_DEBUG_ORIENTATION",
"at": "com\/android\/server\/wm\/WindowStateAnimator.java"
},
+ "1764619787": {
+ "message": "Remote change for Display[%d]: timeout reached",
+ "level": "VERBOSE",
+ "group": "WM_DEBUG_CONFIGURATION",
+ "at": "com\/android\/server\/wm\/RemoteDisplayChangeController.java"
+ },
"1774661765": {
"message": "Devices still not ready after waiting %d milliseconds before attempting to detect safe mode.",
"level": "WARN",
diff --git a/graphics/java/android/graphics/RenderNode.java b/graphics/java/android/graphics/RenderNode.java
index 5fd53adc409a..dadbd8d2d1aa 100644
--- a/graphics/java/android/graphics/RenderNode.java
+++ b/graphics/java/android/graphics/RenderNode.java
@@ -1611,6 +1611,11 @@ public final class RenderNode {
nEndAllAnimators(mNativeRenderNode);
}
+ /** @hide */
+ public void forceEndAnimators() {
+ nForceEndAnimators(mNativeRenderNode);
+ }
+
///////////////////////////////////////////////////////////////////////////
// Regular JNI methods
///////////////////////////////////////////////////////////////////////////
@@ -1633,6 +1638,8 @@ public final class RenderNode {
private static native void nEndAllAnimators(long renderNode);
+ private static native void nForceEndAnimators(long renderNode);
+
///////////////////////////////////////////////////////////////////////////
// @CriticalNative methods
///////////////////////////////////////////////////////////////////////////
diff --git a/keystore/java/android/security/keystore2/AndroidKeyStoreBCWorkaroundProvider.java b/keystore/java/android/security/keystore2/AndroidKeyStoreBCWorkaroundProvider.java
index 9ad6f3adbd33..6fff52a20062 100644
--- a/keystore/java/android/security/keystore2/AndroidKeyStoreBCWorkaroundProvider.java
+++ b/keystore/java/android/security/keystore2/AndroidKeyStoreBCWorkaroundProvider.java
@@ -206,6 +206,8 @@ class AndroidKeyStoreBCWorkaroundProvider extends Provider {
putSignatureImpl("NONEwithECDSA",
PACKAGE_NAME + ".AndroidKeyStoreECDSASignatureSpi$NONE");
+ putSignatureImpl("Ed25519",
+ PACKAGE_NAME + ".AndroidKeyStoreECDSASignatureSpi$Ed25519");
putSignatureImpl("SHA1withECDSA", PACKAGE_NAME + ".AndroidKeyStoreECDSASignatureSpi$SHA1");
put("Alg.Alias.Signature.ECDSA", "SHA1withECDSA");
diff --git a/keystore/java/android/security/keystore2/AndroidKeyStoreECDSASignatureSpi.java b/keystore/java/android/security/keystore2/AndroidKeyStoreECDSASignatureSpi.java
index 8289671de212..5216a908826b 100644
--- a/keystore/java/android/security/keystore2/AndroidKeyStoreECDSASignatureSpi.java
+++ b/keystore/java/android/security/keystore2/AndroidKeyStoreECDSASignatureSpi.java
@@ -29,7 +29,10 @@ import libcore.util.EmptyArray;
import java.io.ByteArrayOutputStream;
import java.security.InvalidKeyException;
import java.security.SignatureSpi;
+import java.security.spec.NamedParameterSpec;
+import java.util.Arrays;
import java.util.List;
+import java.util.Set;
/**
* Base class for {@link SignatureSpi} providing Android KeyStore backed ECDSA signatures.
@@ -37,6 +40,10 @@ import java.util.List;
* @hide
*/
abstract class AndroidKeyStoreECDSASignatureSpi extends AndroidKeyStoreSignatureSpiBase {
+ private static final Set<String> ACCEPTED_SIGNING_SCHEMES = Set.of(
+ KeyProperties.KEY_ALGORITHM_EC.toLowerCase(),
+ NamedParameterSpec.ED25519.getName().toLowerCase(),
+ "eddsa");
public final static class NONE extends AndroidKeyStoreECDSASignatureSpi {
public NONE() {
@@ -114,6 +121,18 @@ abstract class AndroidKeyStoreECDSASignatureSpi extends AndroidKeyStoreSignature
}
}
+ public static final class Ed25519 extends AndroidKeyStoreECDSASignatureSpi {
+ public Ed25519() {
+ // Ed25519 uses an internal digest system.
+ super(KeymasterDefs.KM_DIGEST_NONE);
+ }
+
+ @Override
+ protected String getAlgorithm() {
+ return NamedParameterSpec.ED25519.getName();
+ }
+ }
+
public final static class SHA1 extends AndroidKeyStoreECDSASignatureSpi {
public SHA1() {
super(KeymasterDefs.KM_DIGEST_SHA1);
@@ -174,9 +193,10 @@ abstract class AndroidKeyStoreECDSASignatureSpi extends AndroidKeyStoreSignature
@Override
protected final void initKey(AndroidKeyStoreKey key) throws InvalidKeyException {
- if (!KeyProperties.KEY_ALGORITHM_EC.equalsIgnoreCase(key.getAlgorithm())) {
+ if (!ACCEPTED_SIGNING_SCHEMES.contains(key.getAlgorithm().toLowerCase())) {
throw new InvalidKeyException("Unsupported key algorithm: " + key.getAlgorithm()
- + ". Only" + KeyProperties.KEY_ALGORITHM_EC + " supported");
+ + ". Only" + Arrays.toString(ACCEPTED_SIGNING_SCHEMES.stream().toArray())
+ + " supported");
}
long keySizeBits = -1;
diff --git a/keystore/java/android/security/keystore2/AndroidKeyStoreKeyAgreementSpi.java b/keystore/java/android/security/keystore2/AndroidKeyStoreKeyAgreementSpi.java
index fc963a88c4d1..b1338d164055 100644
--- a/keystore/java/android/security/keystore2/AndroidKeyStoreKeyAgreementSpi.java
+++ b/keystore/java/android/security/keystore2/AndroidKeyStoreKeyAgreementSpi.java
@@ -61,6 +61,17 @@ public class AndroidKeyStoreKeyAgreementSpi extends KeyAgreementSpi
}
}
+ /**
+ * X25519 key agreement support.
+ *
+ * @hide
+ */
+ public static class XDH extends AndroidKeyStoreKeyAgreementSpi {
+ public XDH() {
+ super(Algorithm.EC);
+ }
+ }
+
private final int mKeymintAlgorithm;
// Fields below are populated by engineInit and should be preserved after engineDoFinal.
diff --git a/keystore/java/android/security/keystore2/AndroidKeyStoreKeyPairGeneratorSpi.java b/keystore/java/android/security/keystore2/AndroidKeyStoreKeyPairGeneratorSpi.java
index 40659f5dbfb0..cdc1085a5015 100644
--- a/keystore/java/android/security/keystore2/AndroidKeyStoreKeyPairGeneratorSpi.java
+++ b/keystore/java/android/security/keystore2/AndroidKeyStoreKeyPairGeneratorSpi.java
@@ -712,7 +712,7 @@ public abstract class AndroidKeyStoreKeyPairGeneratorSpi extends KeyPairGenerato
case KeymasterDefs.KM_ERROR_HARDWARE_TYPE_UNAVAILABLE:
throw new StrongBoxUnavailableException("Failed to generated key pair.", e);
case ResponseCode.OUT_OF_KEYS:
- throw makeOutOfKeysException(e, securityLevel);
+ return checkIfRetryableOrThrow(e, securityLevel);
default:
ProviderException p = new ProviderException("Failed to generate key pair.", e);
if ((mSpec.getPurposes() & KeyProperties.PURPOSE_WRAP_KEY) != 0) {
@@ -740,7 +740,7 @@ public abstract class AndroidKeyStoreKeyPairGeneratorSpi extends KeyPairGenerato
// In case keystore reports OUT_OF_KEYS, call this handler in an attempt to remotely provision
// some keys.
- private ProviderException makeOutOfKeysException(KeyStoreException e, int securityLevel) {
+ GenerateKeyPairHelperResult checkIfRetryableOrThrow(KeyStoreException e, int securityLevel) {
GenerateRkpKey keyGen = new GenerateRkpKey(ActivityThread
.currentApplication());
KeyStoreException ksException;
@@ -757,8 +757,11 @@ public abstract class AndroidKeyStoreKeyPairGeneratorSpi extends KeyPairGenerato
rkpStatus = KeyStoreException.RKP_SERVER_REFUSED_ISSUANCE;
break;
case IGenerateRkpKeyService.Status.OK:
- // This will actually retry once immediately, so on "OK" go ahead and return
- // "temporarily unavailable". @see generateKeyPair
+ // Explicitly return not-OK here so we retry in generateKeyPair. All other cases
+ // should throw because a retry doesn't make sense if we didn't actually
+ // provision fresh keys.
+ return new GenerateKeyPairHelperResult(
+ KeyStoreException.RKP_TEMPORARILY_UNAVAILABLE, null);
case IGenerateRkpKeyService.Status.NETWORK_COMMUNICATION_ERROR:
case IGenerateRkpKeyService.Status.HTTP_CLIENT_ERROR:
case IGenerateRkpKeyService.Status.HTTP_SERVER_ERROR:
@@ -781,7 +784,7 @@ public abstract class AndroidKeyStoreKeyPairGeneratorSpi extends KeyPairGenerato
KeyStoreException.RKP_TEMPORARILY_UNAVAILABLE);
}
ksException.initCause(e);
- return new ProviderException("Failed to talk to RemoteProvisioner", ksException);
+ throw new ProviderException("Failed to provision new attestation keys.", ksException);
}
private void addAttestationParameters(@NonNull List<KeyParameter> params)
diff --git a/keystore/java/android/security/keystore2/AndroidKeyStoreProvider.java b/keystore/java/android/security/keystore2/AndroidKeyStoreProvider.java
index 0355628b8135..9947d34495ab 100644
--- a/keystore/java/android/security/keystore2/AndroidKeyStoreProvider.java
+++ b/keystore/java/android/security/keystore2/AndroidKeyStoreProvider.java
@@ -104,6 +104,7 @@ public class AndroidKeyStoreProvider extends Provider {
// javax.crypto.KeyAgreement
put("KeyAgreement.ECDH", PACKAGE_NAME + ".AndroidKeyStoreKeyAgreementSpi$ECDH");
+ put("KeyAgreement.XDH", PACKAGE_NAME + ".AndroidKeyStoreKeyAgreementSpi$XDH");
// java.security.SecretKeyFactory
putSecretKeyFactoryImpl("AES");
@@ -235,8 +236,8 @@ public class AndroidKeyStoreProvider extends Provider {
return new AndroidKeyStoreEdECPublicKey(descriptor, metadata, ED25519_OID,
iSecurityLevel, publicKeyEncoded);
} else if (X25519_ALIAS.equalsIgnoreCase(jcaKeyAlgorithm)) {
- //TODO(b/214203951) missing classes in conscrypt
- throw new ProviderException("Curve " + X25519_ALIAS + " not supported yet");
+ return new AndroidKeyStoreXDHPublicKey(descriptor, metadata, X25519_ALIAS,
+ iSecurityLevel, publicKey.getEncoded());
} else {
throw new ProviderException("Unsupported Android Keystore public key algorithm: "
+ jcaKeyAlgorithm);
diff --git a/keystore/java/android/security/keystore2/AndroidKeyStoreXDHPrivateKey.java b/keystore/java/android/security/keystore2/AndroidKeyStoreXDHPrivateKey.java
new file mode 100644
index 000000000000..42589640d2b7
--- /dev/null
+++ b/keystore/java/android/security/keystore2/AndroidKeyStoreXDHPrivateKey.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.security.keystore2;
+
+import android.annotation.NonNull;
+import android.security.KeyStoreSecurityLevel;
+import android.system.keystore2.Authorization;
+import android.system.keystore2.KeyDescriptor;
+
+import java.security.PrivateKey;
+import java.security.interfaces.EdECKey;
+import java.security.spec.NamedParameterSpec;
+
+/**
+ * X25519 Private Key backed by Keystore.
+ * instance of {@link PrivateKey} and {@link EdECKey}
+ *
+ * @hide
+ */
+public class AndroidKeyStoreXDHPrivateKey extends AndroidKeyStorePrivateKey implements EdECKey {
+ public AndroidKeyStoreXDHPrivateKey(
+ @NonNull KeyDescriptor descriptor, long keyId,
+ @NonNull Authorization[] authorizations,
+ @NonNull String algorithm,
+ @NonNull KeyStoreSecurityLevel securityLevel) {
+ super(descriptor, keyId, authorizations, algorithm, securityLevel);
+ }
+
+ @Override
+ public NamedParameterSpec getParams() {
+ return NamedParameterSpec.X25519;
+ }
+}
diff --git a/keystore/java/android/security/keystore2/AndroidKeyStoreXDHPublicKey.java b/keystore/java/android/security/keystore2/AndroidKeyStoreXDHPublicKey.java
new file mode 100644
index 000000000000..9f3df3d72d86
--- /dev/null
+++ b/keystore/java/android/security/keystore2/AndroidKeyStoreXDHPublicKey.java
@@ -0,0 +1,120 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.security.keystore2;
+
+import android.annotation.NonNull;
+import android.security.KeyStoreSecurityLevel;
+import android.system.keystore2.KeyDescriptor;
+import android.system.keystore2.KeyMetadata;
+
+import java.math.BigInteger;
+import java.security.interfaces.XECPublicKey;
+import java.security.spec.AlgorithmParameterSpec;
+import java.security.spec.NamedParameterSpec;
+import java.util.Arrays;
+
+/**
+ * {@link XECPublicKey} backed by keystore.
+ * This class re-implements Conscrypt's OpenSSLX25519PublicKey. The reason is that
+ * OpenSSLX25519PublicKey does not implement XECPublicKey and is not a part of Conscrypt's public
+ * interface so it cannot be referred to.
+ *
+ * So the functionality is duplicated here until (likely Android U) one of the things mentioned
+ * above is fixed.
+ *
+ * @hide
+ */
+public class AndroidKeyStoreXDHPublicKey extends AndroidKeyStorePublicKey implements XECPublicKey {
+ private static final byte[] X509_PREAMBLE = new byte[] {
+ 0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x6e, 0x03, 0x21, 0x00,
+ };
+
+ private static final byte[] X509_PREAMBLE_WITH_NULL = new byte[] {
+ 0x30, 0x2C, 0x30, 0x07, 0x06, 0x03, 0x2B, 0x65, 0x6E, 0x05, 0x00, 0x03, 0x21, 0x00,
+ };
+
+ private static final int X25519_KEY_SIZE_BYTES = 32;
+
+ private final byte[] mEncodedKey;
+ private final int mPreambleLength;
+
+ public AndroidKeyStoreXDHPublicKey(
+ @NonNull KeyDescriptor descriptor,
+ @NonNull KeyMetadata metadata,
+ @NonNull String algorithm,
+ @NonNull KeyStoreSecurityLevel iSecurityLevel,
+ @NonNull byte[] encodedKey) {
+ super(descriptor, metadata, encodedKey, algorithm, iSecurityLevel);
+ mEncodedKey = encodedKey;
+ if (mEncodedKey == null) {
+ throw new IllegalArgumentException("empty encoded key.");
+ }
+
+ mPreambleLength = matchesPreamble(X509_PREAMBLE, mEncodedKey) | matchesPreamble(
+ X509_PREAMBLE_WITH_NULL, mEncodedKey);
+ if (mPreambleLength == 0) {
+ throw new IllegalArgumentException("Key size is not correct size");
+ }
+ }
+
+ private static int matchesPreamble(byte[] preamble, byte[] encoded) {
+ if (encoded.length != (preamble.length + X25519_KEY_SIZE_BYTES)) {
+ return 0;
+ }
+
+ if (Arrays.compare(preamble, 0, preamble.length, encoded, 0, preamble.length) != 0) {
+ return 0;
+ }
+ return preamble.length;
+ }
+
+ @Override
+ AndroidKeyStorePrivateKey getPrivateKey() {
+ return new AndroidKeyStoreXDHPrivateKey(
+ getUserKeyDescriptor(),
+ getKeyIdDescriptor().nspace,
+ getAuthorizations(),
+ "x25519",
+ getSecurityLevel());
+ }
+
+ @Override
+ public BigInteger getU() {
+ return new BigInteger(Arrays.copyOfRange(mEncodedKey, mPreambleLength, mEncodedKey.length));
+ }
+
+ @Override
+ public byte[] getEncoded() {
+ return mEncodedKey.clone();
+ }
+
+ @Override
+ public String getAlgorithm() {
+ return "XDH";
+ }
+
+ @Override
+ public String getFormat() {
+ return "x.509";
+ }
+
+ @Override
+ public AlgorithmParameterSpec getParams() {
+ return NamedParameterSpec.X25519;
+ }
+}
+
diff --git a/libs/WindowManager/Jetpack/src/TEST_MAPPING b/libs/WindowManager/Jetpack/src/TEST_MAPPING
index eacfe2520a6a..f8f64001dd24 100644
--- a/libs/WindowManager/Jetpack/src/TEST_MAPPING
+++ b/libs/WindowManager/Jetpack/src/TEST_MAPPING
@@ -28,5 +28,10 @@
}
]
}
+ ],
+ "imports": [
+ {
+ "path": "vendor/google_testing/integration/tests/scenarios/src/android/platform/test/scenario/sysui"
+ }
]
-} \ No newline at end of file
+}
diff --git a/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/SplitController.java b/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/SplitController.java
index 9713c2735a9c..015205c7a063 100644
--- a/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/SplitController.java
+++ b/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/SplitController.java
@@ -32,6 +32,7 @@ import android.app.ActivityClient;
import android.app.ActivityOptions;
import android.app.ActivityThread;
import android.app.Instrumentation;
+import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
@@ -234,13 +235,45 @@ public class SplitController implements JetpackTaskFragmentOrganizer.TaskFragmen
public void onActivityReparentToTask(int taskId, @NonNull Intent activityIntent,
@NonNull IBinder activityToken) {
// If the activity belongs to the current app process, we treat it as a new activity launch.
- final Activity activity = ActivityThread.currentActivityThread().getActivity(activityToken);
+ final Activity activity = getActivity(activityToken);
if (activity != null) {
- onActivityCreated(activity);
+ // We don't allow split as primary for new launch because we currently only support
+ // launching to top. We allow split as primary for activity reparent because the
+ // activity may be split as primary before it is reparented out. In that case, we want
+ // to show it as primary again when it is reparented back.
+ if (!resolveActivityToContainer(activity, true /* canSplitAsPrimary */)) {
+ // When there is no embedding rule matched, try to place it in the top container
+ // like a normal launch.
+ placeActivityInTopContainer(activity);
+ }
updateCallbackIfNecessary();
return;
}
- // TODO: handle for activity in other process.
+
+ final TaskContainer taskContainer = getTaskContainer(taskId);
+ if (taskContainer == null || taskContainer.isInPictureInPicture()) {
+ // We don't embed activity when it is in PIP.
+ return;
+ }
+
+ // If the activity belongs to a different app process, we treat it as starting new intent,
+ // since both actions might result in a new activity that should appear in an organized
+ // TaskFragment.
+ final WindowContainerTransaction wct = new WindowContainerTransaction();
+ TaskFragmentContainer targetContainer = resolveStartActivityIntent(wct, taskId,
+ activityIntent, null /* launchingActivity */);
+ if (targetContainer == null) {
+ // When there is no embedding rule matched, try to place it in the top container like a
+ // normal launch.
+ targetContainer = taskContainer.getTopTaskFragmentContainer();
+ }
+ if (targetContainer == null) {
+ return;
+ }
+ wct.reparentActivityToTaskFragment(targetContainer.getTaskFragmentToken(), activityToken);
+ mPresenter.applyTransaction(wct);
+ // Because the activity does not belong to the organizer process, we wait until
+ // onTaskFragmentAppeared to trigger updateCallbackIfNecessary().
}
/** Called on receiving {@link #onTaskFragmentVanished(TaskFragmentInfo)} for cleanup. */
@@ -316,92 +349,244 @@ public class SplitController implements JetpackTaskFragmentOrganizer.TaskFragmen
return false;
}
+ @VisibleForTesting
void onActivityCreated(@NonNull Activity launchedActivity) {
- handleActivityCreated(launchedActivity);
+ // TODO(b/229680885): we don't support launching into primary yet because we want to always
+ // launch the new activity on top.
+ resolveActivityToContainer(launchedActivity, false /* canSplitAsPrimary */);
updateCallbackIfNecessary();
}
/**
- * Checks if the activity start should be routed to a particular container. It can create a new
- * container for the activity and a new split container if necessary.
+ * Checks if the new added activity should be routed to a particular container. It can create a
+ * new container for the activity and a new split container if necessary.
+ * @param launchedActivity the new launched activity.
+ * @param canSplitAsPrimary whether we can put the new launched activity into primary split.
+ * @return {@code true} if the activity was placed in TaskFragment container.
*/
- // TODO(b/190433398): Break down into smaller functions.
- void handleActivityCreated(@NonNull Activity launchedActivity) {
- if (isInPictureInPicture(launchedActivity)) {
- // We don't embed activity when it is in PIP.
- return;
+ @VisibleForTesting
+ boolean resolveActivityToContainer(@NonNull Activity launchedActivity,
+ boolean canSplitAsPrimary) {
+ if (isInPictureInPicture(launchedActivity) || launchedActivity.isFinishing()) {
+ // We don't embed activity when it is in PIP, or finishing. Return true since we don't
+ // want any extra handling.
+ return true;
}
- final List<EmbeddingRule> splitRules = getSplitRules();
- final TaskFragmentContainer currentContainer = getContainerWithActivity(
- launchedActivity.getActivityToken());
-
- // Check if the activity is configured to always be expanded.
- if (shouldExpand(launchedActivity, null, splitRules)) {
- if (shouldContainerBeExpanded(currentContainer)) {
- // Make sure that the existing container is expanded
- mPresenter.expandTaskFragment(currentContainer.getTaskFragmentToken());
- } else {
- // Put activity into a new expanded container
- final TaskFragmentContainer newContainer = newContainer(launchedActivity,
- launchedActivity.getTaskId());
- mPresenter.expandActivity(newContainer.getTaskFragmentToken(),
- launchedActivity);
- }
- return;
+
+ /*
+ * We will check the following to see if there is any embedding rule matched:
+ * 1. Whether the new launched activity should always expand.
+ * 2. Whether the new launched activity should launch a placeholder.
+ * 3. Whether the new launched activity has already been in a split with a rule matched
+ * (likely done in #onStartActivity).
+ * 4. Whether the activity below (if any) should be split with the new launched activity.
+ * 5. Whether the activity split with the activity below (if any) should be split with the
+ * new launched activity.
+ */
+
+ // 1. Whether the new launched activity should always expand.
+ if (shouldExpand(launchedActivity, null /* intent */)) {
+ expandActivity(launchedActivity);
+ return true;
}
- // Check if activity requires a placeholder
+ // 2. Whether the new launched activity should launch a placeholder.
if (launchPlaceholderIfNecessary(launchedActivity)) {
+ return true;
+ }
+
+ // 3. Whether the new launched activity has already been in a split with a rule matched.
+ if (isNewActivityInSplitWithRuleMatched(launchedActivity)) {
+ return true;
+ }
+
+ // 4. Whether the activity below (if any) should be split with the new launched activity.
+ final Activity activityBelow = findActivityBelow(launchedActivity);
+ if (activityBelow == null) {
+ // Can't find any activity below.
+ return false;
+ }
+ if (putActivitiesIntoSplitIfNecessary(activityBelow, launchedActivity)) {
+ // Have split rule of [ activityBelow | launchedActivity ].
+ return true;
+ }
+ if (canSplitAsPrimary
+ && putActivitiesIntoSplitIfNecessary(launchedActivity, activityBelow)) {
+ // Have split rule of [ launchedActivity | activityBelow].
+ return true;
+ }
+
+ // 5. Whether the activity split with the activity below (if any) should be split with the
+ // new launched activity.
+ final TaskFragmentContainer activityBelowContainer = getContainerWithActivity(
+ activityBelow);
+ final SplitContainer topSplit = getActiveSplitForContainer(activityBelowContainer);
+ if (topSplit == null || !isTopMostSplit(topSplit)) {
+ // Skip if it is not the topmost split.
+ return false;
+ }
+ final TaskFragmentContainer otherTopContainer =
+ topSplit.getPrimaryContainer() == activityBelowContainer
+ ? topSplit.getSecondaryContainer()
+ : topSplit.getPrimaryContainer();
+ final Activity otherTopActivity = otherTopContainer.getTopNonFinishingActivity();
+ if (otherTopActivity == null || otherTopActivity == launchedActivity) {
+ // Can't find the top activity on the other split TaskFragment.
+ return false;
+ }
+ if (putActivitiesIntoSplitIfNecessary(otherTopActivity, launchedActivity)) {
+ // Have split rule of [ otherTopActivity | launchedActivity ].
+ return true;
+ }
+ // Have split rule of [ launchedActivity | otherTopActivity].
+ return canSplitAsPrimary
+ && putActivitiesIntoSplitIfNecessary(launchedActivity, otherTopActivity);
+ }
+
+ /**
+ * Places the given activity to the top most TaskFragment in the task if there is any.
+ */
+ @VisibleForTesting
+ void placeActivityInTopContainer(@NonNull Activity activity) {
+ if (getContainerWithActivity(activity) != null) {
+ // The activity has already been put in a TaskFragment. This is likely to be done by
+ // the server when the activity is started.
+ return;
+ }
+ final int taskId = getTaskId(activity);
+ final TaskContainer taskContainer = getTaskContainer(taskId);
+ if (taskContainer == null) {
return;
}
+ final TaskFragmentContainer targetContainer = taskContainer.getTopTaskFragmentContainer();
+ if (targetContainer == null) {
+ return;
+ }
+ targetContainer.addPendingAppearedActivity(activity);
+ final WindowContainerTransaction wct = new WindowContainerTransaction();
+ wct.reparentActivityToTaskFragment(targetContainer.getTaskFragmentToken(),
+ activity.getActivityToken());
+ mPresenter.applyTransaction(wct);
+ }
+
+ /**
+ * Expands the given activity by either expanding the TaskFragment it is currently in or putting
+ * it into a new expanded TaskFragment.
+ */
+ private void expandActivity(@NonNull Activity activity) {
+ final TaskFragmentContainer container = getContainerWithActivity(activity);
+ if (shouldContainerBeExpanded(container)) {
+ // Make sure that the existing container is expanded.
+ mPresenter.expandTaskFragment(container.getTaskFragmentToken());
+ } else {
+ // Put activity into a new expanded container.
+ final TaskFragmentContainer newContainer = newContainer(activity, getTaskId(activity));
+ mPresenter.expandActivity(newContainer.getTaskFragmentToken(), activity);
+ }
+ }
+
+ /** Whether the given new launched activity is in a split with a rule matched. */
+ private boolean isNewActivityInSplitWithRuleMatched(@NonNull Activity launchedActivity) {
+ final TaskFragmentContainer container = getContainerWithActivity(launchedActivity);
+ final SplitContainer splitContainer = getActiveSplitForContainer(container);
+ if (splitContainer == null) {
+ return false;
+ }
- // TODO(b/190433398): Check if it is a placeholder and there is already another split
- // created by the primary activity. This is necessary for the case when the primary activity
- // launched another secondary in the split, but the placeholder was still launched by the
- // logic above. We didn't prevent the placeholder launcher because we didn't know that
- // another secondary activity is coming up.
+ if (container == splitContainer.getPrimaryContainer()) {
+ // The new launched can be in the primary container when it is starting a new activity
+ // onCreate, thus the secondary may still be empty.
+ final TaskFragmentContainer secondaryContainer = splitContainer.getSecondaryContainer();
+ final Activity secondaryActivity = secondaryContainer.getTopNonFinishingActivity();
+ return secondaryActivity == null
+ || getSplitRule(launchedActivity, secondaryActivity) != null;
+ }
- // Check if the activity should form a split with the activity below in the same task
- // fragment.
+ // Check if the new launched activity is a placeholder.
+ if (splitContainer.getSplitRule() instanceof SplitPlaceholderRule) {
+ final SplitPlaceholderRule placeholderRule =
+ (SplitPlaceholderRule) splitContainer.getSplitRule();
+ final ComponentName placeholderName = placeholderRule.getPlaceholderIntent()
+ .getComponent();
+ // TODO(b/232330767): Do we have a better way to check this?
+ return placeholderName == null
+ || placeholderName.equals(launchedActivity.getComponentName())
+ || placeholderRule.getPlaceholderIntent().equals(launchedActivity.getIntent());
+ }
+
+ // Check if the new launched activity should be split with the primary top activity.
+ final Activity primaryActivity = splitContainer.getPrimaryContainer()
+ .getTopNonFinishingActivity();
+ if (primaryActivity == null) {
+ return false;
+ }
+ /* TODO(b/231845476) we should always respect clearTop.
+ final SplitPairRule curSplitRule = (SplitPairRule) splitContainer.getSplitRule();
+ final SplitPairRule splitRule = getSplitRule(primaryActivity, launchedActivity);
+ return splitRule != null && haveSamePresentation(splitRule, curSplitRule)
+ // If the new launched split rule should clear top and it is not the bottom most,
+ // it means we should create a new split pair and clear the existing secondary.
+ && (!splitRule.shouldClearTop()
+ || container.getBottomMostActivity() == launchedActivity);
+ */
+ return getSplitRule(primaryActivity, launchedActivity) != null;
+ }
+
+ /** Finds the activity below the given activity. */
+ @Nullable
+ private Activity findActivityBelow(@NonNull Activity activity) {
Activity activityBelow = null;
- if (currentContainer != null) {
- final List<Activity> containerActivities = currentContainer.collectActivities();
- final int index = containerActivities.indexOf(launchedActivity);
+ final TaskFragmentContainer container = getContainerWithActivity(activity);
+ if (container != null) {
+ final List<Activity> containerActivities = container.collectActivities();
+ final int index = containerActivities.indexOf(activity);
if (index > 0) {
activityBelow = containerActivities.get(index - 1);
}
}
if (activityBelow == null) {
- IBinder belowToken = ActivityClient.getInstance().getActivityTokenBelow(
- launchedActivity.getActivityToken());
+ final IBinder belowToken = ActivityClient.getInstance().getActivityTokenBelow(
+ activity.getActivityToken());
if (belowToken != null) {
- activityBelow = ActivityThread.currentActivityThread().getActivity(belowToken);
+ activityBelow = getActivity(belowToken);
}
}
- if (activityBelow == null) {
- return;
- }
+ return activityBelow;
+ }
- // Check if the split is already set.
- final TaskFragmentContainer activityBelowContainer = getContainerWithActivity(
- activityBelow.getActivityToken());
- if (currentContainer != null && activityBelowContainer != null) {
- final SplitContainer existingSplit = getActiveSplitForContainers(currentContainer,
- activityBelowContainer);
- if (existingSplit != null) {
- // There is already an active split with the activity below.
- return;
- }
+ /**
+ * Checks if there is a rule to split the two activities. If there is one, puts them into split
+ * and returns {@code true}. Otherwise, returns {@code false}.
+ */
+ private boolean putActivitiesIntoSplitIfNecessary(@NonNull Activity primaryActivity,
+ @NonNull Activity secondaryActivity) {
+ final SplitPairRule splitRule = getSplitRule(primaryActivity, secondaryActivity);
+ if (splitRule == null) {
+ return false;
}
-
- final SplitPairRule splitPairRule = getSplitRule(activityBelow, launchedActivity,
- splitRules);
- if (splitPairRule == null) {
- return;
+ final TaskFragmentContainer primaryContainer = getContainerWithActivity(
+ primaryActivity);
+ final SplitContainer splitContainer = getActiveSplitForContainer(primaryContainer);
+ if (splitContainer != null && primaryContainer == splitContainer.getPrimaryContainer()
+ && canReuseContainer(splitRule, splitContainer.getSplitRule())) {
+ // Can launch in the existing secondary container if the rules share the same
+ // presentation.
+ final TaskFragmentContainer secondaryContainer = splitContainer.getSecondaryContainer();
+ if (secondaryContainer == getContainerWithActivity(secondaryActivity)) {
+ // The activity is already in the target TaskFragment.
+ return true;
+ }
+ secondaryContainer.addPendingAppearedActivity(secondaryActivity);
+ final WindowContainerTransaction wct = new WindowContainerTransaction();
+ wct.reparentActivityToTaskFragment(
+ secondaryContainer.getTaskFragmentToken(),
+ secondaryActivity.getActivityToken());
+ mPresenter.applyTransaction(wct);
+ return true;
}
-
- mPresenter.createNewSplitContainer(activityBelow, launchedActivity,
- splitPairRule);
+ // Create new split pair.
+ mPresenter.createNewSplitContainer(primaryActivity, secondaryActivity, splitRule);
+ return true;
}
private void onActivityConfigurationChanged(@NonNull Activity activity) {
@@ -409,8 +594,7 @@ public class SplitController implements JetpackTaskFragmentOrganizer.TaskFragmen
// We don't embed activity when it is in PIP.
return;
}
- final TaskFragmentContainer currentContainer = getContainerWithActivity(
- activity.getActivityToken());
+ final TaskFragmentContainer currentContainer = getContainerWithActivity(activity);
if (currentContainer != null) {
// Changes to activities in controllers are handled in
@@ -443,14 +627,149 @@ public class SplitController implements JetpackTaskFragmentOrganizer.TaskFragmen
}
/**
+ * When we are trying to handle a new activity Intent, returns the {@link TaskFragmentContainer}
+ * that we should reparent the new activity to if there is any embedding rule matched.
+ *
+ * @param wct {@link WindowContainerTransaction} including all the window change
+ * requests. The caller is responsible to call
+ * {@link android.window.TaskFragmentOrganizer#applyTransaction}.
+ * @param taskId The Task to start the activity in.
+ * @param intent The {@link Intent} for starting the new launched activity.
+ * @param launchingActivity The {@link Activity} that starts the new activity. We will
+ * prioritize to split the new activity with it if it is not
+ * {@code null}.
+ * @return the {@link TaskFragmentContainer} to start the new activity in. {@code null} if there
+ * is no embedding rule matched.
+ */
+ @VisibleForTesting
+ @Nullable
+ TaskFragmentContainer resolveStartActivityIntent(@NonNull WindowContainerTransaction wct,
+ int taskId, @NonNull Intent intent, @Nullable Activity launchingActivity) {
+ /*
+ * We will check the following to see if there is any embedding rule matched:
+ * 1. Whether the new activity intent should always expand.
+ * 2. Whether the launching activity (if set) should be split with the new activity intent.
+ * 3. Whether the top activity (if any) should be split with the new activity intent.
+ * 4. Whether the top activity (if any) in other split should be split with the new
+ * activity intent.
+ */
+
+ // 1. Whether the new activity intent should always expand.
+ if (shouldExpand(null /* activity */, intent)) {
+ return createEmptyExpandedContainer(wct, taskId, launchingActivity);
+ }
+
+ // 2. Whether the launching activity (if set) should be split with the new activity intent.
+ if (launchingActivity != null) {
+ final TaskFragmentContainer container = getSecondaryContainerForSplitIfAny(wct,
+ launchingActivity, intent, true /* respectClearTop */);
+ if (container != null) {
+ return container;
+ }
+ }
+
+ // 3. Whether the top activity (if any) should be split with the new activity intent.
+ final TaskContainer taskContainer = getTaskContainer(taskId);
+ if (taskContainer == null || taskContainer.getTopTaskFragmentContainer() == null) {
+ // There is no other activity in the Task to check split with.
+ return null;
+ }
+ final TaskFragmentContainer topContainer = taskContainer.getTopTaskFragmentContainer();
+ final Activity topActivity = topContainer.getTopNonFinishingActivity();
+ if (topActivity != null && topActivity != launchingActivity) {
+ final TaskFragmentContainer container = getSecondaryContainerForSplitIfAny(wct,
+ topActivity, intent, false /* respectClearTop */);
+ if (container != null) {
+ return container;
+ }
+ }
+
+ // 4. Whether the top activity (if any) in other split should be split with the new
+ // activity intent.
+ final SplitContainer topSplit = getActiveSplitForContainer(topContainer);
+ if (topSplit == null) {
+ return null;
+ }
+ final TaskFragmentContainer otherTopContainer =
+ topSplit.getPrimaryContainer() == topContainer
+ ? topSplit.getSecondaryContainer()
+ : topSplit.getPrimaryContainer();
+ final Activity otherTopActivity = otherTopContainer.getTopNonFinishingActivity();
+ if (otherTopActivity != null && otherTopActivity != launchingActivity) {
+ return getSecondaryContainerForSplitIfAny(wct, otherTopActivity, intent,
+ false /* respectClearTop */);
+ }
+ return null;
+ }
+
+ /**
+ * Returns an empty expanded {@link TaskFragmentContainer} that we can launch an activity into.
+ */
+ @Nullable
+ private TaskFragmentContainer createEmptyExpandedContainer(
+ @NonNull WindowContainerTransaction wct, int taskId,
+ @Nullable Activity launchingActivity) {
+ // We need an activity in the organizer process in the same Task to use as the owner
+ // activity, as well as to get the Task window info.
+ final Activity activityInTask;
+ if (launchingActivity != null) {
+ activityInTask = launchingActivity;
+ } else {
+ final TaskContainer taskContainer = getTaskContainer(taskId);
+ activityInTask = taskContainer != null
+ ? taskContainer.getTopNonFinishingActivity()
+ : null;
+ }
+ if (activityInTask == null) {
+ // Can't find any activity in the Task that we can use as the owner activity.
+ return null;
+ }
+ final TaskFragmentContainer expandedContainer = newContainer(null /* activity */,
+ activityInTask, taskId);
+ mPresenter.createTaskFragment(wct, expandedContainer.getTaskFragmentToken(),
+ activityInTask.getActivityToken(), new Rect(), WINDOWING_MODE_UNDEFINED);
+ return expandedContainer;
+ }
+
+ /**
+ * Returns a container for the new activity intent to launch into as splitting with the primary
+ * activity.
+ */
+ @Nullable
+ private TaskFragmentContainer getSecondaryContainerForSplitIfAny(
+ @NonNull WindowContainerTransaction wct, @NonNull Activity primaryActivity,
+ @NonNull Intent intent, boolean respectClearTop) {
+ final SplitPairRule splitRule = getSplitRule(primaryActivity, intent);
+ if (splitRule == null) {
+ return null;
+ }
+ final TaskFragmentContainer existingContainer = getContainerWithActivity(primaryActivity);
+ final SplitContainer splitContainer = getActiveSplitForContainer(existingContainer);
+ if (splitContainer != null && existingContainer == splitContainer.getPrimaryContainer()
+ && (canReuseContainer(splitRule, splitContainer.getSplitRule())
+ // TODO(b/231845476) we should always respect clearTop.
+ || !respectClearTop)) {
+ // Can launch in the existing secondary container if the rules share the same
+ // presentation.
+ return splitContainer.getSecondaryContainer();
+ }
+ // Create a new TaskFragment to split with the primary activity for the new activity.
+ return mPresenter.createNewSplitWithEmptySideContainer(wct, primaryActivity, splitRule);
+ }
+
+ /**
* Returns a container that this activity is registered with. An activity can only belong to one
* container, or no container at all.
*/
@Nullable
- TaskFragmentContainer getContainerWithActivity(@NonNull IBinder activityToken) {
+ TaskFragmentContainer getContainerWithActivity(@NonNull Activity activity) {
+ final IBinder activityToken = activity.getActivityToken();
for (int i = mTaskContainers.size() - 1; i >= 0; i--) {
final List<TaskFragmentContainer> containers = mTaskContainers.valueAt(i).mContainers;
- for (TaskFragmentContainer container : containers) {
+ // Traverse from top to bottom in case an activity is added to top pending, and hasn't
+ // received update from server yet.
+ for (int j = containers.size() - 1; j >= 0; j--) {
+ final TaskFragmentContainer container = containers.get(j);
if (container.hasActivity(activityToken)) {
return container;
}
@@ -647,8 +966,7 @@ public class SplitController implements JetpackTaskFragmentOrganizer.TaskFragmen
if (splitContainer == null) {
return;
}
- final List<SplitContainer> splitContainers = container.getTaskContainer().mSplitContainers;
- if (splitContainer != splitContainers.get(splitContainers.size() - 1)) {
+ if (!isTopMostSplit(splitContainer)) {
// Skip position update - it isn't the topmost split.
return;
}
@@ -664,11 +982,21 @@ public class SplitController implements JetpackTaskFragmentOrganizer.TaskFragmen
mPresenter.updateSplitContainer(splitContainer, container, wct);
}
+ /** Whether the given split is the topmost split in the Task. */
+ private boolean isTopMostSplit(@NonNull SplitContainer splitContainer) {
+ final List<SplitContainer> splitContainers = splitContainer.getPrimaryContainer()
+ .getTaskContainer().mSplitContainers;
+ return splitContainer == splitContainers.get(splitContainers.size() - 1);
+ }
+
/**
* Returns the top active split container that has the provided container, if available.
*/
@Nullable
- private SplitContainer getActiveSplitForContainer(@NonNull TaskFragmentContainer container) {
+ private SplitContainer getActiveSplitForContainer(@Nullable TaskFragmentContainer container) {
+ if (container == null) {
+ return null;
+ }
final List<SplitContainer> splitContainers = container.getTaskContainer().mSplitContainers;
if (splitContainers.isEmpty()) {
return null;
@@ -687,8 +1015,9 @@ public class SplitController implements JetpackTaskFragmentOrganizer.TaskFragmen
* Returns the active split that has the provided containers as primary and secondary or as
* secondary and primary, if available.
*/
+ @VisibleForTesting
@Nullable
- private SplitContainer getActiveSplitForContainers(
+ SplitContainer getActiveSplitForContainers(
@NonNull TaskFragmentContainer firstContainer,
@NonNull TaskFragmentContainer secondContainer) {
final List<SplitContainer> splitContainers = firstContainer.getTaskContainer()
@@ -718,15 +1047,13 @@ public class SplitController implements JetpackTaskFragmentOrganizer.TaskFragmen
}
boolean launchPlaceholderIfNecessary(@NonNull Activity activity) {
- final TaskFragmentContainer container = getContainerWithActivity(
- activity.getActivityToken());
+ final TaskFragmentContainer container = getContainerWithActivity(activity);
// Don't launch placeholder if the container is occluded.
if (container != null && container != getTopActiveContainer(container.getTaskId())) {
return false;
}
- SplitContainer splitContainer = container != null ? getActiveSplitForContainer(container)
- : null;
+ final SplitContainer splitContainer = getActiveSplitForContainer(container);
if (splitContainer != null && container.equals(splitContainer.getPrimaryContainer())) {
// Don't launch placeholder in primary split container
return false;
@@ -861,14 +1188,7 @@ public class SplitController implements JetpackTaskFragmentOrganizer.TaskFragmen
if (container == null) {
return false;
}
- final List<SplitContainer> splitContainers = container.getTaskContainer().mSplitContainers;
- for (SplitContainer splitContainer : splitContainers) {
- if (container.equals(splitContainer.getPrimaryContainer())
- || container.equals(splitContainer.getSecondaryContainer())) {
- return false;
- }
- }
- return true;
+ return getActiveSplitForContainer(container) == null;
}
/**
@@ -876,9 +1196,9 @@ public class SplitController implements JetpackTaskFragmentOrganizer.TaskFragmen
* if available.
*/
@Nullable
- private static SplitPairRule getSplitRule(@NonNull Activity primaryActivity,
- @NonNull Intent secondaryActivityIntent, @NonNull List<EmbeddingRule> splitRules) {
- for (EmbeddingRule rule : splitRules) {
+ private SplitPairRule getSplitRule(@NonNull Activity primaryActivity,
+ @NonNull Intent secondaryActivityIntent) {
+ for (EmbeddingRule rule : mSplitRules) {
if (!(rule instanceof SplitPairRule)) {
continue;
}
@@ -894,9 +1214,9 @@ public class SplitController implements JetpackTaskFragmentOrganizer.TaskFragmen
* Returns a split rule for the provided pair of primary and secondary activities if available.
*/
@Nullable
- private static SplitPairRule getSplitRule(@NonNull Activity primaryActivity,
- @NonNull Activity secondaryActivity, @NonNull List<EmbeddingRule> splitRules) {
- for (EmbeddingRule rule : splitRules) {
+ private SplitPairRule getSplitRule(@NonNull Activity primaryActivity,
+ @NonNull Activity secondaryActivity) {
+ for (EmbeddingRule rule : mSplitRules) {
if (!(rule instanceof SplitPairRule)) {
continue;
}
@@ -933,16 +1253,24 @@ public class SplitController implements JetpackTaskFragmentOrganizer.TaskFragmen
return mHandler;
}
+ int getTaskId(@NonNull Activity activity) {
+ // Prefer to get the taskId from TaskFragmentContainer because Activity.getTaskId() is an
+ // IPC call.
+ final TaskFragmentContainer container = getContainerWithActivity(activity);
+ return container != null ? container.getTaskId() : activity.getTaskId();
+ }
+
+ @Nullable
+ Activity getActivity(@NonNull IBinder activityToken) {
+ return ActivityThread.currentActivityThread().getActivity(activityToken);
+ }
+
/**
* Returns {@code true} if an Activity with the provided component name should always be
* expanded to occupy full task bounds. Such activity must not be put in a split.
*/
- private static boolean shouldExpand(@Nullable Activity activity, @Nullable Intent intent,
- List<EmbeddingRule> splitRules) {
- if (splitRules == null) {
- return false;
- }
- for (EmbeddingRule rule : splitRules) {
+ private boolean shouldExpand(@Nullable Activity activity, @Nullable Intent intent) {
+ for (EmbeddingRule rule : mSplitRules) {
if (!(rule instanceof ActivityRule)) {
continue;
}
@@ -996,8 +1324,8 @@ public class SplitController implements JetpackTaskFragmentOrganizer.TaskFragmen
*/
boolean shouldRetainAssociatedActivity(@NonNull TaskFragmentContainer finishingContainer,
@NonNull Activity associatedActivity) {
- TaskFragmentContainer associatedContainer = getContainerWithActivity(
- associatedActivity.getActivityToken());
+ final TaskFragmentContainer associatedContainer = getContainerWithActivity(
+ associatedActivity);
if (associatedContainer == null) {
return false;
}
@@ -1085,130 +1413,20 @@ public class SplitController implements JetpackTaskFragmentOrganizer.TaskFragmen
return super.onStartActivity(who, intent, options);
}
- if (shouldExpand(null, intent, getSplitRules())) {
- setLaunchingInExpandedContainer(launchingActivity, options);
- } else if (!splitWithLaunchingActivity(launchingActivity, intent, options)) {
- setLaunchingInSameSideContainer(launchingActivity, intent, options);
+ final int taskId = getTaskId(launchingActivity);
+ final WindowContainerTransaction wct = new WindowContainerTransaction();
+ final TaskFragmentContainer launchedInTaskFragment = resolveStartActivityIntent(wct,
+ taskId, intent, launchingActivity);
+ if (launchedInTaskFragment != null) {
+ mPresenter.applyTransaction(wct);
+ // Amend the request to let the WM know that the activity should be placed in the
+ // dedicated container.
+ options.putBinder(ActivityOptions.KEY_LAUNCH_TASK_FRAGMENT_TOKEN,
+ launchedInTaskFragment.getTaskFragmentToken());
}
return super.onStartActivity(who, intent, options);
}
-
- private void setLaunchingInExpandedContainer(Activity launchingActivity, Bundle options) {
- TaskFragmentContainer newContainer = mPresenter.createNewExpandedContainer(
- launchingActivity);
-
- // Amend the request to let the WM know that the activity should be placed in the
- // dedicated container.
- options.putBinder(ActivityOptions.KEY_LAUNCH_TASK_FRAGMENT_TOKEN,
- newContainer.getTaskFragmentToken());
- }
-
- /**
- * Returns {@code true} if the activity that is going to be started via the
- * {@code intent} should be paired with the {@code launchingActivity} and is set to be
- * launched in the side container.
- */
- private boolean splitWithLaunchingActivity(Activity launchingActivity, Intent intent,
- Bundle options) {
- final SplitPairRule splitPairRule = getSplitRule(launchingActivity, intent,
- getSplitRules());
- if (splitPairRule == null) {
- return false;
- }
-
- // Check if there is any existing side container to launch into.
- TaskFragmentContainer secondaryContainer = findSideContainerForNewLaunch(
- launchingActivity, splitPairRule);
- if (secondaryContainer == null) {
- // Create a new split with an empty side container.
- secondaryContainer = mPresenter
- .createNewSplitWithEmptySideContainer(launchingActivity, splitPairRule);
- }
-
- // Amend the request to let the WM know that the activity should be placed in the
- // dedicated container.
- options.putBinder(ActivityOptions.KEY_LAUNCH_TASK_FRAGMENT_TOKEN,
- secondaryContainer.getTaskFragmentToken());
- return true;
- }
-
- /**
- * Finds if there is an existing split side {@link TaskFragmentContainer} that can be used
- * for the new rule.
- */
- @Nullable
- private TaskFragmentContainer findSideContainerForNewLaunch(Activity launchingActivity,
- SplitPairRule splitPairRule) {
- final TaskFragmentContainer launchingContainer = getContainerWithActivity(
- launchingActivity.getActivityToken());
- if (launchingContainer == null) {
- return null;
- }
-
- // We only check if the launching activity is the primary of the split. We will check
- // if the launching activity is the secondary in #setLaunchingInSameSideContainer.
- final SplitContainer splitContainer = getActiveSplitForContainer(launchingContainer);
- if (splitContainer == null
- || splitContainer.getPrimaryContainer() != launchingContainer) {
- return null;
- }
-
- if (canReuseContainer(splitPairRule, splitContainer.getSplitRule())) {
- return splitContainer.getSecondaryContainer();
- }
- return null;
- }
-
- /**
- * Checks if the activity that is going to be started via the {@code intent} should be
- * paired with the existing top activity which is currently paired with the
- * {@code launchingActivity}. If so, set the activity to be launched in the same side
- * container of the {@code launchingActivity}.
- */
- private void setLaunchingInSameSideContainer(Activity launchingActivity, Intent intent,
- Bundle options) {
- final TaskFragmentContainer launchingContainer = getContainerWithActivity(
- launchingActivity.getActivityToken());
- if (launchingContainer == null) {
- return;
- }
-
- final SplitContainer splitContainer = getActiveSplitForContainer(launchingContainer);
- if (splitContainer == null) {
- return;
- }
-
- if (splitContainer.getSecondaryContainer() != launchingContainer) {
- return;
- }
-
- // The launching activity is on the secondary container. Retrieve the primary
- // activity from the other container.
- Activity primaryActivity =
- splitContainer.getPrimaryContainer().getTopNonFinishingActivity();
- if (primaryActivity == null) {
- return;
- }
-
- final SplitPairRule splitPairRule = getSplitRule(primaryActivity, intent,
- getSplitRules());
- if (splitPairRule == null) {
- return;
- }
-
- // Can only launch in the same container if the rules share the same presentation.
- if (!canReuseContainer(splitPairRule, splitContainer.getSplitRule())) {
- return;
- }
-
- // Amend the request to let the WM know that the activity should be placed in the
- // dedicated container. This is necessary for the case that the activity is started
- // into a new Task, or new Task will be escaped from the current host Task and be
- // displayed in fullscreen.
- options.putBinder(ActivityOptions.KEY_LAUNCH_TASK_FRAGMENT_TOKEN,
- launchingContainer.getTaskFragmentToken());
- }
}
/**
@@ -1228,8 +1446,18 @@ public class SplitController implements JetpackTaskFragmentOrganizer.TaskFragmen
if (!isContainerReusableRule(rule1) || !isContainerReusableRule(rule2)) {
return false;
}
+ return haveSamePresentation((SplitPairRule) rule1, (SplitPairRule) rule2);
+ }
+
+ /** Whether the two rules have the same presentation. */
+ private static boolean haveSamePresentation(SplitPairRule rule1, SplitPairRule rule2) {
+ // TODO(b/231655482): add util method to do the comparison in SplitPairRule.
return rule1.getSplitRatio() == rule2.getSplitRatio()
- && rule1.getLayoutDirection() == rule2.getLayoutDirection();
+ && rule1.getLayoutDirection() == rule2.getLayoutDirection()
+ && rule1.getFinishPrimaryWithSecondary()
+ == rule2.getFinishPrimaryWithSecondary()
+ && rule1.getFinishSecondaryWithPrimary()
+ == rule2.getFinishSecondaryWithPrimary();
}
/**
diff --git a/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/SplitPresenter.java b/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/SplitPresenter.java
index b32f4fa67906..43d0402c1525 100644
--- a/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/SplitPresenter.java
+++ b/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/SplitPresenter.java
@@ -16,8 +16,6 @@
package androidx.window.extensions.embedding;
-import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
-
import android.app.Activity;
import android.app.WindowConfiguration;
import android.app.WindowConfiguration.WindowingMode;
@@ -100,10 +98,10 @@ class SplitPresenter extends JetpackTaskFragmentOrganizer {
* Creates a new split with the primary activity and an empty secondary container.
* @return The newly created secondary container.
*/
- TaskFragmentContainer createNewSplitWithEmptySideContainer(@NonNull Activity primaryActivity,
+ @NonNull
+ TaskFragmentContainer createNewSplitWithEmptySideContainer(
+ @NonNull WindowContainerTransaction wct, @NonNull Activity primaryActivity,
@NonNull SplitPairRule rule) {
- final WindowContainerTransaction wct = new WindowContainerTransaction();
-
final Rect parentBounds = getParentContainerBounds(primaryActivity);
final Rect primaryRectBounds = getBoundsForPosition(POSITION_START, parentBounds, rule,
isLtr(primaryActivity, rule));
@@ -127,8 +125,6 @@ class SplitPresenter extends JetpackTaskFragmentOrganizer {
mController.registerSplit(wct, primaryContainer, primaryActivity, secondaryContainer, rule);
- applyTransaction(wct);
-
return secondaryContainer;
}
@@ -155,8 +151,15 @@ class SplitPresenter extends JetpackTaskFragmentOrganizer {
final Rect secondaryRectBounds = getBoundsForPosition(POSITION_END, parentBounds, rule,
isLtr(primaryActivity, rule));
+ final TaskFragmentContainer curSecondaryContainer = mController.getContainerWithActivity(
+ secondaryActivity);
+ TaskFragmentContainer containerToAvoid = primaryContainer;
+ if (rule.shouldClearTop() && curSecondaryContainer != null) {
+ // Do not reuse the current TaskFragment if the rule is to clear top.
+ containerToAvoid = curSecondaryContainer;
+ }
final TaskFragmentContainer secondaryContainer = prepareContainerForActivity(wct,
- secondaryActivity, secondaryRectBounds, primaryContainer);
+ secondaryActivity, secondaryRectBounds, containerToAvoid);
// Set adjacent to each other so that the containers below will be invisible.
setAdjacentTaskFragments(wct, primaryContainer, secondaryContainer, rule);
@@ -167,21 +170,6 @@ class SplitPresenter extends JetpackTaskFragmentOrganizer {
}
/**
- * Creates a new expanded container.
- */
- TaskFragmentContainer createNewExpandedContainer(@NonNull Activity launchingActivity) {
- final TaskFragmentContainer newContainer = mController.newContainer(null /* activity */,
- launchingActivity, launchingActivity.getTaskId());
-
- final WindowContainerTransaction wct = new WindowContainerTransaction();
- createTaskFragment(wct, newContainer.getTaskFragmentToken(),
- launchingActivity.getActivityToken(), new Rect(), WINDOWING_MODE_UNDEFINED);
-
- applyTransaction(wct);
- return newContainer;
- }
-
- /**
* Creates a new container or resizes an existing container for activity to the provided bounds.
* @param activity The activity to be re-parented to the container if necessary.
* @param containerToAvoid Re-parent from this container if an activity is already in it.
@@ -189,8 +177,7 @@ class SplitPresenter extends JetpackTaskFragmentOrganizer {
private TaskFragmentContainer prepareContainerForActivity(
@NonNull WindowContainerTransaction wct, @NonNull Activity activity,
@NonNull Rect bounds, @Nullable TaskFragmentContainer containerToAvoid) {
- TaskFragmentContainer container = mController.getContainerWithActivity(
- activity.getActivityToken());
+ TaskFragmentContainer container = mController.getContainerWithActivity(activity);
final int taskId = container != null ? container.getTaskId() : activity.getTaskId();
if (container == null || container == containerToAvoid) {
container = mController.newContainer(activity, taskId);
@@ -230,7 +217,7 @@ class SplitPresenter extends JetpackTaskFragmentOrganizer {
isLtr(launchingActivity, rule));
TaskFragmentContainer primaryContainer = mController.getContainerWithActivity(
- launchingActivity.getActivityToken());
+ launchingActivity);
if (primaryContainer == null) {
primaryContainer = mController.newContainer(launchingActivity,
launchingActivity.getTaskId());
@@ -460,8 +447,7 @@ class SplitPresenter extends JetpackTaskFragmentOrganizer {
@NonNull
Rect getParentContainerBounds(@NonNull Activity activity) {
- final TaskFragmentContainer container = mController.getContainerWithActivity(
- activity.getActivityToken());
+ final TaskFragmentContainer container = mController.getContainerWithActivity(activity);
if (container != null) {
return getParentContainerBounds(container);
}
diff --git a/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/TaskContainer.java b/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/TaskContainer.java
index dba71ef21946..0ea5603b1f3d 100644
--- a/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/TaskContainer.java
+++ b/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/TaskContainer.java
@@ -142,4 +142,23 @@ class TaskContainer {
container.removePendingAppearedActivity(pendingAppearedActivity);
}
}
+
+ @Nullable
+ TaskFragmentContainer getTopTaskFragmentContainer() {
+ if (mContainers.isEmpty()) {
+ return null;
+ }
+ return mContainers.get(mContainers.size() - 1);
+ }
+
+ @Nullable
+ Activity getTopNonFinishingActivity() {
+ for (int i = mContainers.size() - 1; i >= 0; i--) {
+ final Activity activity = mContainers.get(i).getTopNonFinishingActivity();
+ if (activity != null) {
+ return activity;
+ }
+ }
+ return null;
+ }
}
diff --git a/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/TaskFragmentAnimationAdapter.java b/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/TaskFragmentAnimationAdapter.java
index b3becad3dc5a..cdee9e386b33 100644
--- a/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/TaskFragmentAnimationAdapter.java
+++ b/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/TaskFragmentAnimationAdapter.java
@@ -17,6 +17,8 @@
package androidx.window.extensions.embedding;
import static android.graphics.Matrix.MSCALE_X;
+import static android.graphics.Matrix.MTRANS_X;
+import static android.graphics.Matrix.MTRANS_Y;
import android.graphics.Rect;
import android.view.Choreographer;
@@ -96,22 +98,20 @@ class TaskFragmentAnimationAdapter {
mTarget.localBounds.left, mTarget.localBounds.top);
t.setMatrix(mLeash, mTransformation.getMatrix(), mMatrix);
t.setAlpha(mLeash, mTransformation.getAlpha());
-
- // Open/close animation may scale up the surface. Apply an inverse scale to the window crop
- // so that it will not be covering other windows.
- mVecs[1] = mVecs[2] = 0;
- mVecs[0] = mVecs[3] = 1;
- mTransformation.getMatrix().mapVectors(mVecs);
- mVecs[0] = 1.f / mVecs[0];
- mVecs[3] = 1.f / mVecs[3];
- final Rect clipRect = mTarget.localBounds;
- mRect.left = (int) (clipRect.left * mVecs[0] + 0.5f);
- mRect.right = (int) (clipRect.right * mVecs[0] + 0.5f);
- mRect.top = (int) (clipRect.top * mVecs[3] + 0.5f);
- mRect.bottom = (int) (clipRect.bottom * mVecs[3] + 0.5f);
- mRect.offsetTo(Math.round(mTarget.localBounds.width() * (1 - mVecs[0]) / 2.f),
- Math.round(mTarget.localBounds.height() * (1 - mVecs[3]) / 2.f));
- t.setWindowCrop(mLeash, mRect);
+ // Get current animation position.
+ final int positionX = Math.round(mMatrix[MTRANS_X]);
+ final int positionY = Math.round(mMatrix[MTRANS_Y]);
+ // The exiting surface starts at position: mTarget.localBounds and moves with
+ // positionX varying. Offset our crop region by the amount we have slided so crop
+ // regions stays exactly on the original container in split.
+ final int cropOffsetX = mTarget.localBounds.left - positionX;
+ final int cropOffsetY = mTarget.localBounds.top - positionY;
+ final Rect cropRect = new Rect();
+ cropRect.set(mTarget.localBounds);
+ // Because window crop uses absolute position.
+ cropRect.offsetTo(0, 0);
+ cropRect.offset(cropOffsetX, cropOffsetY);
+ t.setCrop(mLeash, cropRect);
}
/** Called after animation finished. */
diff --git a/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/TaskFragmentContainer.java b/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/TaskFragmentContainer.java
index 6693755ee102..26ddae4a0818 100644
--- a/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/TaskFragmentContainer.java
+++ b/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/TaskFragmentContainer.java
@@ -21,7 +21,6 @@ import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.app.Activity;
-import android.app.ActivityThread;
import android.app.WindowConfiguration.WindowingMode;
import android.graphics.Rect;
import android.os.Binder;
@@ -122,21 +121,24 @@ class TaskFragmentContainer {
/** List of activities that belong to this container and live in this process. */
@NonNull
List<Activity> collectActivities() {
+ final List<Activity> allActivities = new ArrayList<>();
+ if (mInfo != null) {
+ // Add activities reported from the server.
+ for (IBinder token : mInfo.getActivities()) {
+ final Activity activity = mController.getActivity(token);
+ if (activity != null && !activity.isFinishing()) {
+ allActivities.add(activity);
+ }
+ }
+ }
+
// Add the re-parenting activity, in case the server has not yet reported the task
// fragment info update with it placed in this container. We still want to apply rules
// in this intermediate state.
- List<Activity> allActivities = new ArrayList<>();
- if (!mPendingAppearedActivities.isEmpty()) {
- allActivities.addAll(mPendingAppearedActivities);
- }
- // Add activities reported from the server.
- if (mInfo == null) {
- return allActivities;
- }
- ActivityThread activityThread = ActivityThread.currentActivityThread();
- for (IBinder token : mInfo.getActivities()) {
- Activity activity = activityThread.getActivity(token);
- if (activity != null && !activity.isFinishing() && !allActivities.contains(activity)) {
+ // Place those on top of the list since they will be on the top after reported from the
+ // server.
+ for (Activity activity : mPendingAppearedActivities) {
+ if (!activity.isFinishing()) {
allActivities.add(activity);
}
}
@@ -243,6 +245,12 @@ class TaskFragmentContainer {
return i >= 0 ? activities.get(i) : null;
}
+ @Nullable
+ Activity getBottomMostActivity() {
+ final List<Activity> activities = collectActivities();
+ return activities.isEmpty() ? null : activities.get(0);
+ }
+
boolean isEmpty() {
return mPendingAppearedActivities.isEmpty() && (mInfo == null || mInfo.isEmpty());
}
diff --git a/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/SplitControllerTest.java b/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/SplitControllerTest.java
index 34cde9bca763..353c7df2cbc5 100644
--- a/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/SplitControllerTest.java
+++ b/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/SplitControllerTest.java
@@ -16,6 +16,9 @@
package androidx.window.extensions.embedding;
+import static android.app.WindowConfiguration.WINDOWING_MODE_MULTI_WINDOW;
+import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
+
import static com.android.dx.mockito.inline.extended.ExtendedMockito.spyOn;
import static com.android.dx.mockito.inline.extended.ExtendedMockito.verify;
@@ -24,23 +27,35 @@ import static com.google.common.truth.Truth.assertWithMessage;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.ArgumentMatchers.isNull;
+import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
+import android.annotation.NonNull;
import android.app.Activity;
+import android.content.ComponentName;
+import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
+import android.graphics.Point;
import android.graphics.Rect;
import android.os.Binder;
import android.os.Handler;
+import android.os.IBinder;
import android.platform.test.annotations.Presubmit;
+import android.util.Pair;
import android.window.TaskFragmentInfo;
+import android.window.WindowContainerToken;
import android.window.WindowContainerTransaction;
import androidx.test.ext.junit.runners.AndroidJUnit4;
@@ -53,6 +68,7 @@ import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.ArrayList;
+import java.util.Collections;
import java.util.List;
/**
@@ -67,8 +83,10 @@ import java.util.List;
public class SplitControllerTest {
private static final int TASK_ID = 10;
private static final Rect TASK_BOUNDS = new Rect(0, 0, 600, 1200);
+ private static final float SPLIT_RATIO = 0.5f;
+ private static final Intent PLACEHOLDER_INTENT = new Intent().setComponent(
+ new ComponentName("test", "placeholder"));
- @Mock
private Activity mActivity;
@Mock
private Resources mActivityResources;
@@ -89,12 +107,13 @@ public class SplitControllerTest {
mSplitPresenter = mSplitController.mPresenter;
spyOn(mSplitController);
spyOn(mSplitPresenter);
+ doNothing().when(mSplitPresenter).applyTransaction(any());
final Configuration activityConfig = new Configuration();
activityConfig.windowConfiguration.setBounds(TASK_BOUNDS);
activityConfig.windowConfiguration.setMaxBounds(TASK_BOUNDS);
- doReturn(mActivityResources).when(mActivity).getResources();
doReturn(activityConfig).when(mActivityResources).getConfiguration();
doReturn(mHandler).when(mSplitController).getHandler();
+ mActivity = createMockActivity();
}
@Test
@@ -260,6 +279,622 @@ public class SplitControllerTest {
mSplitController.updateContainer(mTransaction, tf);
- verify(mSplitPresenter).updateSplitContainer(eq(splitContainer), eq(tf), eq(mTransaction));
+ verify(mSplitPresenter).updateSplitContainer(splitContainer, tf, mTransaction);
+ }
+
+ @Test
+ public void testOnActivityCreated() {
+ mSplitController.onActivityCreated(mActivity);
+
+ // Disallow to split as primary because we want the new launch to be always on top.
+ verify(mSplitController).resolveActivityToContainer(mActivity,
+ false /* canSplitAsPrimary */);
+ }
+
+ @Test
+ public void testOnActivityReparentToTask_sameProcess() {
+ mSplitController.onActivityReparentToTask(TASK_ID, new Intent(),
+ mActivity.getActivityToken());
+
+ // Treated as on activity created, but allow to split as primary.
+ verify(mSplitController).resolveActivityToContainer(mActivity,
+ true /* canSplitAsPrimary */);
+ // Try to place the activity to the top TaskFragment when there is no matched rule.
+ verify(mSplitController).placeActivityInTopContainer(mActivity);
+ }
+
+ @Test
+ public void testOnActivityReparentToTask_diffProcess() {
+ // Create an empty TaskFragment to initialize for the Task.
+ mSplitController.newContainer(null, mActivity, TASK_ID);
+ final IBinder activityToken = new Binder();
+ final Intent intent = new Intent();
+
+ mSplitController.onActivityReparentToTask(TASK_ID, intent, activityToken);
+
+ // Treated as starting new intent
+ verify(mSplitController, never()).resolveActivityToContainer(any(), anyBoolean());
+ verify(mSplitController).resolveStartActivityIntent(any(), eq(TASK_ID), eq(intent),
+ isNull());
+ }
+
+ @Test
+ public void testResolveStartActivityIntent_withoutLaunchingActivity() {
+ final Intent intent = new Intent();
+ final ActivityRule expandRule = new ActivityRule.Builder(r -> false, i -> i == intent)
+ .setShouldAlwaysExpand(true)
+ .build();
+ mSplitController.setEmbeddingRules(Collections.singleton(expandRule));
+
+ // No other activity available in the Task.
+ TaskFragmentContainer container = mSplitController.resolveStartActivityIntent(mTransaction,
+ TASK_ID, intent, null /* launchingActivity */);
+ assertNull(container);
+
+ // Task contains another activity that can be used as owner activity.
+ createMockTaskFragmentContainer(mActivity);
+ container = mSplitController.resolveStartActivityIntent(mTransaction,
+ TASK_ID, intent, null /* launchingActivity */);
+ assertNotNull(container);
+ }
+
+ @Test
+ public void testResolveStartActivityIntent_shouldExpand() {
+ final Intent intent = new Intent();
+ setupExpandRule(intent);
+ final TaskFragmentContainer container = mSplitController.resolveStartActivityIntent(
+ mTransaction, TASK_ID, intent, mActivity);
+
+ assertNotNull(container);
+ assertTrue(container.areLastRequestedBoundsEqual(null));
+ assertTrue(container.isLastRequestedWindowingModeEqual(WINDOWING_MODE_UNDEFINED));
+ assertFalse(container.hasActivity(mActivity.getActivityToken()));
+ verify(mSplitPresenter).createTaskFragment(mTransaction, container.getTaskFragmentToken(),
+ mActivity.getActivityToken(), new Rect(), WINDOWING_MODE_UNDEFINED);
+ }
+
+ @Test
+ public void testResolveStartActivityIntent_shouldSplitWithLaunchingActivity() {
+ final Intent intent = new Intent();
+ setupSplitRule(mActivity, intent);
+
+ final TaskFragmentContainer container = mSplitController.resolveStartActivityIntent(
+ mTransaction, TASK_ID, intent, mActivity);
+ final TaskFragmentContainer primaryContainer = mSplitController.getContainerWithActivity(
+ mActivity);
+
+ assertSplitPair(primaryContainer, container);
+ }
+
+ @Test
+ public void testResolveStartActivityIntent_shouldSplitWithTopExpandActivity() {
+ final Intent intent = new Intent();
+ setupSplitRule(mActivity, intent);
+ createMockTaskFragmentContainer(mActivity);
+
+ final TaskFragmentContainer container = mSplitController.resolveStartActivityIntent(
+ mTransaction, TASK_ID, intent, null /* launchingActivity */);
+ final TaskFragmentContainer primaryContainer = mSplitController.getContainerWithActivity(
+ mActivity);
+
+ assertSplitPair(primaryContainer, container);
+ }
+
+ @Test
+ public void testResolveStartActivityIntent_shouldSplitWithTopSecondaryActivity() {
+ final Intent intent = new Intent();
+ setupSplitRule(mActivity, intent);
+ final Activity primaryActivity = createMockActivity();
+ addSplitTaskFragments(primaryActivity, mActivity);
+
+ final TaskFragmentContainer container = mSplitController.resolveStartActivityIntent(
+ mTransaction, TASK_ID, intent, null /* launchingActivity */);
+ final TaskFragmentContainer primaryContainer = mSplitController.getContainerWithActivity(
+ mActivity);
+
+ assertSplitPair(primaryContainer, container);
+ }
+
+ @Test
+ public void testResolveStartActivityIntent_shouldSplitWithTopPrimaryActivity() {
+ final Intent intent = new Intent();
+ setupSplitRule(mActivity, intent);
+ final Activity secondaryActivity = createMockActivity();
+ addSplitTaskFragments(mActivity, secondaryActivity);
+
+ final TaskFragmentContainer container = mSplitController.resolveStartActivityIntent(
+ mTransaction, TASK_ID, intent, null /* launchingActivity */);
+ final TaskFragmentContainer primaryContainer = mSplitController.getContainerWithActivity(
+ mActivity);
+
+ assertSplitPair(primaryContainer, container);
+ }
+
+ @Test
+ public void testPlaceActivityInTopContainer() {
+ mSplitController.placeActivityInTopContainer(mActivity);
+
+ verify(mSplitPresenter, never()).applyTransaction(any());
+
+ mSplitController.newContainer(null /* activity */, mActivity, TASK_ID);
+ mSplitController.placeActivityInTopContainer(mActivity);
+
+ verify(mSplitPresenter).applyTransaction(any());
+
+ // Not reparent if activity is in a TaskFragment.
+ clearInvocations(mSplitPresenter);
+ mSplitController.newContainer(mActivity, TASK_ID);
+ mSplitController.placeActivityInTopContainer(mActivity);
+
+ verify(mSplitPresenter, never()).applyTransaction(any());
+ }
+
+ @Test
+ public void testResolveActivityToContainer_noRuleMatched() {
+ final boolean result = mSplitController.resolveActivityToContainer(mActivity,
+ false /* canSplitAsPrimary */);
+
+ assertFalse(result);
+ verify(mSplitController, never()).newContainer(any(), any(), anyInt());
+ }
+
+ @Test
+ public void testResolveActivityToContainer_expandRule_notInTaskFragment() {
+ setupExpandRule(mActivity);
+
+ // When the activity is not in any TaskFragment, create a new expanded TaskFragment for it.
+ final boolean result = mSplitController.resolveActivityToContainer(mActivity,
+ false /* canSplitAsPrimary */);
+ final TaskFragmentContainer container = mSplitController.getContainerWithActivity(
+ mActivity);
+
+ assertTrue(result);
+ assertNotNull(container);
+ verify(mSplitController).newContainer(mActivity, TASK_ID);
+ verify(mSplitPresenter).expandActivity(container.getTaskFragmentToken(), mActivity);
+ }
+
+ @Test
+ public void testResolveActivityToContainer_expandRule_inSingleTaskFragment() {
+ setupExpandRule(mActivity);
+
+ // When the activity is not in any TaskFragment, create a new expanded TaskFragment for it.
+ final TaskFragmentContainer container = mSplitController.newContainer(mActivity, TASK_ID);
+ final boolean result = mSplitController.resolveActivityToContainer(mActivity,
+ false /* canSplitAsPrimary */);
+
+ assertTrue(result);
+ verify(mSplitPresenter).expandTaskFragment(container.getTaskFragmentToken());
+ }
+
+ @Test
+ public void testResolveActivityToContainer_expandRule_inSplitTaskFragment() {
+ setupExpandRule(mActivity);
+
+ // When the activity is not in any TaskFragment, create a new expanded TaskFragment for it.
+ final Activity activity = createMockActivity();
+ addSplitTaskFragments(activity, mActivity);
+ final boolean result = mSplitController.resolveActivityToContainer(mActivity,
+ false /* canSplitAsPrimary */);
+ final TaskFragmentContainer container = mSplitController.getContainerWithActivity(
+ mActivity);
+
+ assertTrue(result);
+ assertNotNull(container);
+ verify(mSplitPresenter).expandActivity(container.getTaskFragmentToken(), mActivity);
+ }
+
+ @Test
+ public void testResolveActivityToContainer_placeholderRule_notInTaskFragment() {
+ setupPlaceholderRule(mActivity);
+ final SplitPlaceholderRule placeholderRule =
+ (SplitPlaceholderRule) mSplitController.getSplitRules().get(0);
+
+ // Launch placeholder if the activity is not in any TaskFragment.
+ final boolean result = mSplitController.resolveActivityToContainer(mActivity,
+ false /* canSplitAsPrimary */);
+
+ assertTrue(result);
+ verify(mSplitPresenter).startActivityToSide(mActivity, PLACEHOLDER_INTENT,
+ null /* activityOptions */, placeholderRule, true /* isPlaceholder */);
+ }
+
+ @Test
+ public void testResolveActivityToContainer_placeholderRule_inOccludedTaskFragment() {
+ setupPlaceholderRule(mActivity);
+
+ // Don't launch placeholder if the activity is not in the topmost active TaskFragment.
+ final Activity activity = createMockActivity();
+ mSplitController.newContainer(mActivity, TASK_ID);
+ mSplitController.newContainer(activity, TASK_ID);
+ final boolean result = mSplitController.resolveActivityToContainer(mActivity,
+ false /* canSplitAsPrimary */);
+
+ assertFalse(result);
+ verify(mSplitPresenter, never()).startActivityToSide(any(), any(), any(), any(),
+ anyBoolean());
+ }
+
+ @Test
+ public void testResolveActivityToContainer_placeholderRule_inTopMostTaskFragment() {
+ setupPlaceholderRule(mActivity);
+ final SplitPlaceholderRule placeholderRule =
+ (SplitPlaceholderRule) mSplitController.getSplitRules().get(0);
+
+ // Launch placeholder if the activity is in the topmost expanded TaskFragment.
+ mSplitController.newContainer(mActivity, TASK_ID);
+ final boolean result = mSplitController.resolveActivityToContainer(mActivity,
+ false /* canSplitAsPrimary */);
+
+ assertTrue(result);
+ verify(mSplitPresenter).startActivityToSide(mActivity, PLACEHOLDER_INTENT,
+ null /* activityOptions */, placeholderRule, true /* isPlaceholder */);
+ }
+
+ @Test
+ public void testResolveActivityToContainer_placeholderRule_inPrimarySplit() {
+ setupPlaceholderRule(mActivity);
+
+ // Don't launch placeholder if the activity is in primary split.
+ final Activity secondaryActivity = createMockActivity();
+ addSplitTaskFragments(mActivity, secondaryActivity);
+ final boolean result = mSplitController.resolveActivityToContainer(mActivity,
+ false /* canSplitAsPrimary */);
+
+ assertFalse(result);
+ verify(mSplitPresenter, never()).startActivityToSide(any(), any(), any(), any(),
+ anyBoolean());
+ }
+
+ @Test
+ public void testResolveActivityToContainer_placeholderRule_inSecondarySplit() {
+ setupPlaceholderRule(mActivity);
+ final SplitPlaceholderRule placeholderRule =
+ (SplitPlaceholderRule) mSplitController.getSplitRules().get(0);
+
+ // Launch placeholder if the activity is in secondary split.
+ final Activity primaryActivity = createMockActivity();
+ addSplitTaskFragments(primaryActivity, mActivity);
+ final boolean result = mSplitController.resolveActivityToContainer(mActivity,
+ false /* canSplitAsPrimary */);
+
+ assertTrue(result);
+ verify(mSplitPresenter).startActivityToSide(mActivity, PLACEHOLDER_INTENT,
+ null /* activityOptions */, placeholderRule, true /* isPlaceholder */);
+ }
+
+ @Test
+ public void testResolveActivityToContainer_splitRule_inPrimarySplitWithRuleMatched() {
+ final Intent secondaryIntent = new Intent();
+ setupSplitRule(mActivity, secondaryIntent);
+ final SplitPairRule splitRule = (SplitPairRule) mSplitController.getSplitRules().get(0);
+
+ // Activity is already in primary split, no need to create new split.
+ final TaskFragmentContainer primaryContainer = mSplitController.newContainer(mActivity,
+ TASK_ID);
+ final TaskFragmentContainer secondaryContainer = mSplitController.newContainer(
+ null /* activity */, mActivity, TASK_ID);
+ mSplitController.registerSplit(
+ mTransaction,
+ primaryContainer,
+ mActivity,
+ secondaryContainer,
+ splitRule);
+ clearInvocations(mSplitController);
+ final boolean result = mSplitController.resolveActivityToContainer(mActivity,
+ false /* canSplitAsPrimary */);
+
+ assertTrue(result);
+ verify(mSplitController, never()).newContainer(any(), any(), anyInt());
+ verify(mSplitController, never()).registerSplit(any(), any(), any(), any(), any());
+ }
+
+ @Test
+ public void testResolveActivityToContainer_splitRule_inSecondarySplitWithRuleMatched() {
+ final Activity primaryActivity = createMockActivity();
+ setupSplitRule(primaryActivity, mActivity);
+
+ // Activity is already in secondary split, no need to create new split.
+ addSplitTaskFragments(primaryActivity, mActivity);
+ clearInvocations(mSplitController);
+ final boolean result = mSplitController.resolveActivityToContainer(mActivity,
+ false /* canSplitAsPrimary */);
+
+ assertTrue(result);
+ verify(mSplitController, never()).newContainer(any(), any(), anyInt());
+ verify(mSplitController, never()).registerSplit(any(), any(), any(), any(), any());
+ }
+
+ @Test
+ public void testResolveActivityToContainer_splitRule_inSecondarySplitWithNoRuleMatched() {
+ final Activity primaryActivity = createMockActivity();
+ final Activity secondaryActivity = createMockActivity();
+ setupSplitRule(primaryActivity, secondaryActivity);
+
+ // Activity is in secondary split, but there is no rule to split it with primary.
+ addSplitTaskFragments(primaryActivity, secondaryActivity);
+ mSplitController.getContainerWithActivity(secondaryActivity)
+ .addPendingAppearedActivity(mActivity);
+ final boolean result = mSplitController.resolveActivityToContainer(mActivity,
+ false /* canSplitAsPrimary */);
+
+ assertFalse(result);
+ }
+
+ @Test
+ public void testResolveActivityToContainer_placeholderRule_isPlaceholderWithRuleMatched() {
+ final Activity primaryActivity = createMockActivity();
+ setupPlaceholderRule(primaryActivity);
+ final SplitPlaceholderRule placeholderRule =
+ (SplitPlaceholderRule) mSplitController.getSplitRules().get(0);
+ doReturn(PLACEHOLDER_INTENT).when(mActivity).getIntent();
+
+ // Activity is a placeholder.
+ final TaskFragmentContainer primaryContainer = mSplitController.newContainer(
+ primaryActivity, TASK_ID);
+ final TaskFragmentContainer secondaryContainer = mSplitController.newContainer(mActivity,
+ TASK_ID);
+ mSplitController.registerSplit(
+ mTransaction,
+ primaryContainer,
+ mActivity,
+ secondaryContainer,
+ placeholderRule);
+ final boolean result = mSplitController.resolveActivityToContainer(mActivity,
+ false /* canSplitAsPrimary */);
+
+ assertTrue(result);
+ }
+
+ @Test
+ public void testResolveActivityToContainer_splitRule_splitWithActivityBelowAsSecondary() {
+ final Activity activityBelow = createMockActivity();
+ setupSplitRule(activityBelow, mActivity);
+
+ final TaskFragmentContainer container = mSplitController.newContainer(activityBelow,
+ TASK_ID);
+ container.addPendingAppearedActivity(mActivity);
+ final boolean result = mSplitController.resolveActivityToContainer(mActivity,
+ false /* canSplitAsPrimary */);
+
+ assertTrue(result);
+ assertSplitPair(activityBelow, mActivity);
+ }
+
+ @Test
+ public void testResolveActivityToContainer_splitRule_splitWithActivityBelowAsPrimary() {
+ final Activity activityBelow = createMockActivity();
+ setupSplitRule(mActivity, activityBelow);
+
+ // Disallow to split as primary.
+ final TaskFragmentContainer container = mSplitController.newContainer(activityBelow,
+ TASK_ID);
+ container.addPendingAppearedActivity(mActivity);
+ boolean result = mSplitController.resolveActivityToContainer(mActivity,
+ false /* canSplitAsPrimary */);
+
+ assertFalse(result);
+ assertEquals(container, mSplitController.getContainerWithActivity(mActivity));
+
+ // Allow to split as primary.
+ result = mSplitController.resolveActivityToContainer(mActivity,
+ true /* canSplitAsPrimary */);
+
+ assertTrue(result);
+ assertSplitPair(mActivity, activityBelow);
+ }
+
+ @Test
+ public void testResolveActivityToContainer_splitRule_splitWithCurrentPrimaryAsSecondary() {
+ final Activity primaryActivity = createMockActivity();
+ setupSplitRule(primaryActivity, mActivity);
+
+ final Activity activityBelow = createMockActivity();
+ addSplitTaskFragments(primaryActivity, activityBelow);
+ final TaskFragmentContainer primaryContainer = mSplitController.getContainerWithActivity(
+ primaryActivity);
+ final TaskFragmentContainer secondaryContainer = mSplitController.getContainerWithActivity(
+ activityBelow);
+ secondaryContainer.addPendingAppearedActivity(mActivity);
+ final boolean result = mSplitController.resolveActivityToContainer(mActivity,
+ false /* canSplitAsPrimary */);
+ final TaskFragmentContainer container = mSplitController.getContainerWithActivity(
+ mActivity);
+
+ assertTrue(result);
+ // TODO(b/231845476) we should always respect clearTop.
+ // assertNotEquals(secondaryContainer, container);
+ assertSplitPair(primaryContainer, container);
+ }
+
+ @Test
+ public void testResolveActivityToContainer_splitRule_splitWithCurrentPrimaryAsPrimary() {
+ final Activity primaryActivity = createMockActivity();
+ setupSplitRule(mActivity, primaryActivity);
+
+ final Activity activityBelow = createMockActivity();
+ addSplitTaskFragments(primaryActivity, activityBelow);
+ final TaskFragmentContainer primaryContainer = mSplitController.getContainerWithActivity(
+ primaryActivity);
+ primaryContainer.addPendingAppearedActivity(mActivity);
+ boolean result = mSplitController.resolveActivityToContainer(mActivity,
+ false /* canSplitAsPrimary */);
+
+ assertFalse(result);
+ assertEquals(primaryContainer, mSplitController.getContainerWithActivity(mActivity));
+
+
+ result = mSplitController.resolveActivityToContainer(mActivity,
+ true /* canSplitAsPrimary */);
+
+ assertTrue(result);
+ assertSplitPair(mActivity, primaryActivity);
+ }
+
+ /** Creates a mock activity in the organizer process. */
+ private Activity createMockActivity() {
+ final Activity activity = mock(Activity.class);
+ doReturn(mActivityResources).when(activity).getResources();
+ final IBinder activityToken = new Binder();
+ doReturn(activityToken).when(activity).getActivityToken();
+ doReturn(activity).when(mSplitController).getActivity(activityToken);
+ doReturn(TASK_ID).when(activity).getTaskId();
+ return activity;
+ }
+
+ /** Creates a mock TaskFragmentInfo for the given TaskFragment. */
+ private TaskFragmentInfo createMockTaskFragmentInfo(@NonNull TaskFragmentContainer container,
+ @NonNull Activity activity) {
+ return new TaskFragmentInfo(container.getTaskFragmentToken(),
+ mock(WindowContainerToken.class),
+ new Configuration(),
+ 1,
+ true /* isVisible */,
+ Collections.singletonList(activity.getActivityToken()),
+ new Point(),
+ false /* isTaskClearedForReuse */,
+ false /* isTaskFragmentClearedForPip */);
+ }
+
+ /** Creates a mock TaskFragment that has been registered and appeared in the organizer. */
+ private TaskFragmentContainer createMockTaskFragmentContainer(@NonNull Activity activity) {
+ final TaskFragmentContainer container = mSplitController.newContainer(activity, TASK_ID);
+ setupTaskFragmentInfo(container, activity);
+ return container;
+ }
+
+ /** Setups the given TaskFragment as it has appeared in the server. */
+ private void setupTaskFragmentInfo(@NonNull TaskFragmentContainer container,
+ @NonNull Activity activity) {
+ final TaskFragmentInfo info = createMockTaskFragmentInfo(container, activity);
+ container.setInfo(info);
+ mSplitPresenter.mFragmentInfos.put(container.getTaskFragmentToken(), info);
+ }
+
+ /** Setups a rule to always expand the given intent. */
+ private void setupExpandRule(@NonNull Intent expandIntent) {
+ final ActivityRule expandRule = new ActivityRule.Builder(r -> false, expandIntent::equals)
+ .setShouldAlwaysExpand(true)
+ .build();
+ mSplitController.setEmbeddingRules(Collections.singleton(expandRule));
+ }
+
+ /** Setups a rule to always expand the given activity. */
+ private void setupExpandRule(@NonNull Activity expandActivity) {
+ final ActivityRule expandRule = new ActivityRule.Builder(expandActivity::equals, i -> false)
+ .setShouldAlwaysExpand(true)
+ .build();
+ mSplitController.setEmbeddingRules(Collections.singleton(expandRule));
+ }
+
+ /** Setups a rule to launch placeholder for the given activity. */
+ private void setupPlaceholderRule(@NonNull Activity primaryActivity) {
+ final SplitRule placeholderRule = new SplitPlaceholderRule.Builder(PLACEHOLDER_INTENT,
+ primaryActivity::equals, i -> false, w -> true)
+ .setSplitRatio(SPLIT_RATIO)
+ .build();
+ mSplitController.setEmbeddingRules(Collections.singleton(placeholderRule));
+ }
+
+ /** Setups a rule to always split the given activities. */
+ private void setupSplitRule(@NonNull Activity primaryActivity,
+ @NonNull Intent secondaryIntent) {
+ final SplitRule splitRule = createSplitRule(primaryActivity, secondaryIntent);
+ mSplitController.setEmbeddingRules(Collections.singleton(splitRule));
+ }
+
+ /** Setups a rule to always split the given activities. */
+ private void setupSplitRule(@NonNull Activity primaryActivity,
+ @NonNull Activity secondaryActivity) {
+ final SplitRule splitRule = createSplitRule(primaryActivity, secondaryActivity);
+ mSplitController.setEmbeddingRules(Collections.singleton(splitRule));
+ }
+
+ /** Creates a rule to always split the given activity and the given intent. */
+ private SplitRule createSplitRule(@NonNull Activity primaryActivity,
+ @NonNull Intent secondaryIntent) {
+ final Pair<Activity, Intent> targetPair = new Pair<>(primaryActivity, secondaryIntent);
+ return new SplitPairRule.Builder(
+ activityPair -> false,
+ targetPair::equals,
+ w -> true)
+ .setSplitRatio(SPLIT_RATIO)
+ .setShouldClearTop(true)
+ .build();
+ }
+
+ /** Creates a rule to always split the given activities. */
+ private SplitRule createSplitRule(@NonNull Activity primaryActivity,
+ @NonNull Activity secondaryActivity) {
+ final Pair<Activity, Activity> targetPair = new Pair<>(primaryActivity, secondaryActivity);
+ return new SplitPairRule.Builder(
+ targetPair::equals,
+ activityIntentPair -> false,
+ w -> true)
+ .setSplitRatio(SPLIT_RATIO)
+ .setShouldClearTop(true)
+ .build();
+ }
+
+ /** Adds a pair of TaskFragments as split for the given activities. */
+ private void addSplitTaskFragments(@NonNull Activity primaryActivity,
+ @NonNull Activity secondaryActivity) {
+ final TaskFragmentContainer primaryContainer = createMockTaskFragmentContainer(
+ primaryActivity);
+ final TaskFragmentContainer secondaryContainer = createMockTaskFragmentContainer(
+ secondaryActivity);
+ mSplitController.registerSplit(
+ mock(WindowContainerTransaction.class),
+ primaryContainer,
+ primaryActivity,
+ secondaryContainer,
+ createSplitRule(primaryActivity, secondaryActivity));
+
+ // We need to set those in case we are not respecting clear top.
+ // TODO(b/231845476) we should always respect clearTop.
+ final int windowingMode = mSplitController.getTaskContainer(TASK_ID)
+ .getWindowingModeForSplitTaskFragment(TASK_BOUNDS);
+ primaryContainer.setLastRequestedWindowingMode(windowingMode);
+ secondaryContainer.setLastRequestedWindowingMode(windowingMode);
+ primaryContainer.setLastRequestedBounds(getSplitBounds(true /* isPrimary */));
+ secondaryContainer.setLastRequestedBounds(getSplitBounds(false /* isPrimary */));
+ }
+
+ /** Gets the bounds of a TaskFragment that is in split. */
+ private Rect getSplitBounds(boolean isPrimary) {
+ final int width = (int) (TASK_BOUNDS.width() * SPLIT_RATIO);
+ return isPrimary
+ ? new Rect(TASK_BOUNDS.left, TASK_BOUNDS.top, TASK_BOUNDS.left + width,
+ TASK_BOUNDS.bottom)
+ : new Rect(TASK_BOUNDS.left + width, TASK_BOUNDS.top, TASK_BOUNDS.right,
+ TASK_BOUNDS.bottom);
+ }
+
+ /** Asserts that the two given activities are in split. */
+ private void assertSplitPair(@NonNull Activity primaryActivity,
+ @NonNull Activity secondaryActivity) {
+ assertSplitPair(mSplitController.getContainerWithActivity(primaryActivity),
+ mSplitController.getContainerWithActivity(secondaryActivity));
+ }
+
+ /** Asserts that the two given TaskFragments are in split. */
+ private void assertSplitPair(@NonNull TaskFragmentContainer primaryContainer,
+ @NonNull TaskFragmentContainer secondaryContainer) {
+ assertNotNull(primaryContainer);
+ assertNotNull(secondaryContainer);
+ assertNotNull(mSplitController.getActiveSplitForContainers(primaryContainer,
+ secondaryContainer));
+ if (primaryContainer.mInfo != null) {
+ assertTrue(primaryContainer.areLastRequestedBoundsEqual(
+ getSplitBounds(true /* isPrimary */)));
+ assertTrue(primaryContainer.isLastRequestedWindowingModeEqual(
+ WINDOWING_MODE_MULTI_WINDOW));
+ }
+ if (secondaryContainer.mInfo != null) {
+ assertTrue(secondaryContainer.areLastRequestedBoundsEqual(
+ getSplitBounds(false /* isPrimary */)));
+ assertTrue(secondaryContainer.isLastRequestedWindowingModeEqual(
+ WINDOWING_MODE_MULTI_WINDOW));
+ }
}
}
diff --git a/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/TaskContainerTest.java b/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/TaskContainerTest.java
index 0de94b0dc26f..f1042ab6ce7d 100644
--- a/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/TaskContainerTest.java
+++ b/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/TaskContainerTest.java
@@ -24,8 +24,12 @@ import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import android.app.Activity;
import android.graphics.Rect;
import android.platform.test.annotations.Presubmit;
@@ -147,4 +151,38 @@ public class TaskContainerTest {
assertFalse(taskContainer.isEmpty());
}
+
+ @Test
+ public void testGetTopTaskFragmentContainer() {
+ final TaskContainer taskContainer = new TaskContainer(TASK_ID);
+ assertNull(taskContainer.getTopTaskFragmentContainer());
+
+ final TaskFragmentContainer tf0 = new TaskFragmentContainer(null /* activity */,
+ taskContainer, mController);
+ assertEquals(tf0, taskContainer.getTopTaskFragmentContainer());
+
+ final TaskFragmentContainer tf1 = new TaskFragmentContainer(null /* activity */,
+ taskContainer, mController);
+ assertEquals(tf1, taskContainer.getTopTaskFragmentContainer());
+ }
+
+ @Test
+ public void testGetTopNonFinishingActivity() {
+ final TaskContainer taskContainer = new TaskContainer(TASK_ID);
+ assertNull(taskContainer.getTopNonFinishingActivity());
+
+ final TaskFragmentContainer tf0 = mock(TaskFragmentContainer.class);
+ taskContainer.mContainers.add(tf0);
+ final Activity activity0 = mock(Activity.class);
+ doReturn(activity0).when(tf0).getTopNonFinishingActivity();
+ assertEquals(activity0, taskContainer.getTopNonFinishingActivity());
+
+ final TaskFragmentContainer tf1 = mock(TaskFragmentContainer.class);
+ taskContainer.mContainers.add(tf1);
+ assertEquals(activity0, taskContainer.getTopNonFinishingActivity());
+
+ final Activity activity1 = mock(Activity.class);
+ doReturn(activity1).when(tf1).getTopNonFinishingActivity();
+ assertEquals(activity1, taskContainer.getTopNonFinishingActivity());
+ }
}
diff --git a/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/TaskFragmentContainerTest.java b/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/TaskFragmentContainerTest.java
index ce80cbf323b2..587878f3bf01 100644
--- a/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/TaskFragmentContainerTest.java
+++ b/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/TaskFragmentContainerTest.java
@@ -18,6 +18,7 @@ package androidx.window.extensions.embedding;
import static com.android.dx.mockito.inline.extended.ExtendedMockito.verify;
+import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
@@ -29,7 +30,9 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import android.app.Activity;
+import android.os.Binder;
import android.os.Handler;
+import android.os.IBinder;
import android.platform.test.annotations.Presubmit;
import android.window.TaskFragmentInfo;
import android.window.WindowContainerTransaction;
@@ -37,6 +40,8 @@ import android.window.WindowContainerTransaction;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.SmallTest;
+import com.google.android.collect.Lists;
+
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -44,6 +49,7 @@ import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.ArrayList;
+import java.util.List;
/**
* Test class for {@link TaskFragmentContainer}.
@@ -62,16 +68,16 @@ public class TaskFragmentContainerTest {
@Mock
private SplitController mController;
@Mock
- private Activity mActivity;
- @Mock
private TaskFragmentInfo mInfo;
@Mock
private Handler mHandler;
+ private Activity mActivity;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
doReturn(mHandler).when(mController).getHandler();
+ mActivity = createMockActivity();
}
@Test
@@ -165,4 +171,72 @@ public class TaskFragmentContainerTest {
assertNull(container.mAppearEmptyTimeout);
verify(mController).onTaskFragmentAppearEmptyTimeout(container);
}
+
+ @Test
+ public void testCollectActivities() {
+ final TaskContainer taskContainer = new TaskContainer(TASK_ID);
+ final TaskFragmentContainer container = new TaskFragmentContainer(null /* activity */,
+ taskContainer, mController);
+ List<Activity> activities = container.collectActivities();
+
+ assertTrue(activities.isEmpty());
+
+ container.addPendingAppearedActivity(mActivity);
+ activities = container.collectActivities();
+
+ assertEquals(1, activities.size());
+
+ final Activity activity0 = createMockActivity();
+ final Activity activity1 = createMockActivity();
+ final List<IBinder> runningActivities = Lists.newArrayList(activity0.getActivityToken(),
+ activity1.getActivityToken());
+ doReturn(runningActivities).when(mInfo).getActivities();
+ container.setInfo(mInfo);
+ activities = container.collectActivities();
+
+ assertEquals(3, activities.size());
+ assertEquals(activity0, activities.get(0));
+ assertEquals(activity1, activities.get(1));
+ assertEquals(mActivity, activities.get(2));
+ }
+
+ @Test
+ public void testAddPendingActivity() {
+ final TaskContainer taskContainer = new TaskContainer(TASK_ID);
+ final TaskFragmentContainer container = new TaskFragmentContainer(null /* activity */,
+ taskContainer, mController);
+ container.addPendingAppearedActivity(mActivity);
+
+ assertEquals(1, container.collectActivities().size());
+
+ container.addPendingAppearedActivity(mActivity);
+
+ assertEquals(1, container.collectActivities().size());
+ }
+
+ @Test
+ public void testGetBottomMostActivity() {
+ final TaskContainer taskContainer = new TaskContainer(TASK_ID);
+ final TaskFragmentContainer container = new TaskFragmentContainer(null /* activity */,
+ taskContainer, mController);
+ container.addPendingAppearedActivity(mActivity);
+
+ assertEquals(mActivity, container.getBottomMostActivity());
+
+ final Activity activity = createMockActivity();
+ final List<IBinder> runningActivities = Lists.newArrayList(activity.getActivityToken());
+ doReturn(runningActivities).when(mInfo).getActivities();
+ container.setInfo(mInfo);
+
+ assertEquals(activity, container.getBottomMostActivity());
+ }
+
+ /** Creates a mock activity in the organizer process. */
+ private Activity createMockActivity() {
+ final Activity activity = mock(Activity.class);
+ final IBinder activityToken = new Binder();
+ doReturn(activityToken).when(activity).getActivityToken();
+ doReturn(activity).when(mController).getActivity(activityToken);
+ return activity;
+ }
}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/ShellCommandHandlerImpl.java b/libs/WindowManager/Shell/src/com/android/wm/shell/ShellCommandHandlerImpl.java
index d7ff9d28441a..c5f7c19518a7 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/ShellCommandHandlerImpl.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/ShellCommandHandlerImpl.java
@@ -18,7 +18,6 @@ package com.android.wm.shell;
import static com.android.wm.shell.common.split.SplitScreenConstants.SPLIT_POSITION_BOTTOM_OR_RIGHT;
-import com.android.wm.shell.apppairs.AppPairsController;
import com.android.wm.shell.common.ShellExecutor;
import com.android.wm.shell.hidedisplaycutout.HideDisplayCutoutController;
import com.android.wm.shell.kidsmode.KidsModeTaskOrganizer;
@@ -42,7 +41,6 @@ public final class ShellCommandHandlerImpl {
private final Optional<Pip> mPipOptional;
private final Optional<OneHandedController> mOneHandedOptional;
private final Optional<HideDisplayCutoutController> mHideDisplayCutout;
- private final Optional<AppPairsController> mAppPairsOptional;
private final Optional<RecentTasksController> mRecentTasks;
private final ShellTaskOrganizer mShellTaskOrganizer;
private final KidsModeTaskOrganizer mKidsModeTaskOrganizer;
@@ -56,7 +54,6 @@ public final class ShellCommandHandlerImpl {
Optional<Pip> pipOptional,
Optional<OneHandedController> oneHandedOptional,
Optional<HideDisplayCutoutController> hideDisplayCutout,
- Optional<AppPairsController> appPairsOptional,
Optional<RecentTasksController> recentTasks,
ShellExecutor mainExecutor) {
mShellTaskOrganizer = shellTaskOrganizer;
@@ -66,7 +63,6 @@ public final class ShellCommandHandlerImpl {
mPipOptional = pipOptional;
mOneHandedOptional = oneHandedOptional;
mHideDisplayCutout = hideDisplayCutout;
- mAppPairsOptional = appPairsOptional;
mMainExecutor = mainExecutor;
}
@@ -84,9 +80,6 @@ public final class ShellCommandHandlerImpl {
mHideDisplayCutout.ifPresent(hideDisplayCutout -> hideDisplayCutout.dump(pw));
pw.println();
pw.println();
- mAppPairsOptional.ifPresent(appPairs -> appPairs.dump(pw, ""));
- pw.println();
- pw.println();
mSplitScreenOptional.ifPresent(splitScreen -> splitScreen.dump(pw, ""));
pw.println();
pw.println();
@@ -104,10 +97,6 @@ public final class ShellCommandHandlerImpl {
return false;
}
switch (args[1]) {
- case "pair":
- return runPair(args, pw);
- case "unpair":
- return runUnpair(args, pw);
case "moveToSideStage":
return runMoveToSideStage(args, pw);
case "removeFromSideStage":
@@ -121,29 +110,6 @@ public final class ShellCommandHandlerImpl {
}
}
- private boolean runPair(String[] args, PrintWriter pw) {
- if (args.length < 4) {
- // First two arguments are "WMShell" and command name.
- pw.println("Error: two task ids should be provided as arguments");
- return false;
- }
- final int taskId1 = new Integer(args[2]);
- final int taskId2 = new Integer(args[3]);
- mAppPairsOptional.ifPresent(appPairs -> appPairs.pair(taskId1, taskId2));
- return true;
- }
-
- private boolean runUnpair(String[] args, PrintWriter pw) {
- if (args.length < 3) {
- // First two arguments are "WMShell" and command name.
- pw.println("Error: task id should be provided as an argument");
- return false;
- }
- final int taskId = new Integer(args[2]);
- mAppPairsOptional.ifPresent(appPairs -> appPairs.unpair(taskId));
- return true;
- }
-
private boolean runMoveToSideStage(String[] args, PrintWriter pw) {
if (args.length < 3) {
// First arguments are "WMShell" and command name.
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/ShellInitImpl.java b/libs/WindowManager/Shell/src/com/android/wm/shell/ShellInitImpl.java
index ecdccd7b1419..f6a3e7fb54d9 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/ShellInitImpl.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/ShellInitImpl.java
@@ -18,7 +18,6 @@ package com.android.wm.shell;
import static com.android.wm.shell.ShellTaskOrganizer.TASK_LISTENER_TYPE_FULLSCREEN;
-import com.android.wm.shell.apppairs.AppPairsController;
import com.android.wm.shell.bubbles.BubbleController;
import com.android.wm.shell.common.DisplayController;
import com.android.wm.shell.common.DisplayImeController;
@@ -54,7 +53,6 @@ public class ShellInitImpl {
private final KidsModeTaskOrganizer mKidsModeTaskOrganizer;
private final Optional<BubbleController> mBubblesOptional;
private final Optional<SplitScreenController> mSplitScreenOptional;
- private final Optional<AppPairsController> mAppPairsOptional;
private final Optional<PipTouchHandler> mPipTouchHandlerOptional;
private final FullscreenTaskListener mFullscreenTaskListener;
private final Optional<FullscreenUnfoldController> mFullscreenUnfoldController;
@@ -76,7 +74,6 @@ public class ShellInitImpl {
KidsModeTaskOrganizer kidsModeTaskOrganizer,
Optional<BubbleController> bubblesOptional,
Optional<SplitScreenController> splitScreenOptional,
- Optional<AppPairsController> appPairsOptional,
Optional<PipTouchHandler> pipTouchHandlerOptional,
FullscreenTaskListener fullscreenTaskListener,
Optional<FullscreenUnfoldController> fullscreenUnfoldTransitionController,
@@ -94,7 +91,6 @@ public class ShellInitImpl {
mKidsModeTaskOrganizer = kidsModeTaskOrganizer;
mBubblesOptional = bubblesOptional;
mSplitScreenOptional = splitScreenOptional;
- mAppPairsOptional = appPairsOptional;
mFullscreenTaskListener = fullscreenTaskListener;
mPipTouchHandlerOptional = pipTouchHandlerOptional;
mFullscreenUnfoldController = fullscreenUnfoldTransitionController;
@@ -122,7 +118,6 @@ public class ShellInitImpl {
mShellTaskOrganizer.initStartingWindow(mStartingWindow);
mShellTaskOrganizer.registerOrganizer();
- mAppPairsOptional.ifPresent(AppPairsController::onOrganizerRegistered);
mSplitScreenOptional.ifPresent(SplitScreenController::onOrganizerRegistered);
mBubblesOptional.ifPresent(BubbleController::initialize);
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/animation/Interpolators.java b/libs/WindowManager/Shell/src/com/android/wm/shell/animation/Interpolators.java
index 2aead9392e59..a0dde6ad168d 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/animation/Interpolators.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/animation/Interpolators.java
@@ -53,6 +53,19 @@ public class Interpolators {
public static final Interpolator LINEAR_OUT_SLOW_IN = new PathInterpolator(0f, 0f, 0.2f, 1f);
/**
+ * The accelerated emphasized interpolator. Used for hero / emphasized movement of content that
+ * is disappearing e.g. when moving off screen.
+ */
+ public static final Interpolator EMPHASIZED_ACCELERATE = new PathInterpolator(
+ 0.3f, 0f, 0.8f, 0.15f);
+
+ /**
+ * The decelerating emphasized interpolator. Used for hero / emphasized movement of content that
+ * is appearing e.g. when coming from off screen
+ */
+ public static final Interpolator EMPHASIZED_DECELERATE = new PathInterpolator(
+ 0.05f, 0.7f, 0.1f, 1f);
+ /**
* Interpolator to be used when animating a move based on a click. Pair with enough duration.
*/
public static final Interpolator TOUCH_RESPONSE = new PathInterpolator(0.3f, 0f, 0.1f, 1f);
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/apppairs/AppPair.java b/libs/WindowManager/Shell/src/com/android/wm/shell/apppairs/AppPair.java
deleted file mode 100644
index 3f0b01bef0ce..000000000000
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/apppairs/AppPair.java
+++ /dev/null
@@ -1,357 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.wm.shell.apppairs;
-
-import static android.app.ActivityTaskManager.INVALID_TASK_ID;
-import static android.app.WindowConfiguration.WINDOWING_MODE_MULTI_WINDOW;
-import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
-
-import static com.android.wm.shell.common.split.SplitScreenConstants.SPLIT_POSITION_BOTTOM_OR_RIGHT;
-import static com.android.wm.shell.common.split.SplitScreenConstants.SPLIT_POSITION_TOP_OR_LEFT;
-import static com.android.wm.shell.common.split.SplitScreenConstants.SPLIT_POSITION_UNDEFINED;
-import static com.android.wm.shell.protolog.ShellProtoLogGroup.WM_SHELL_TASK_ORG;
-
-import android.app.ActivityManager;
-import android.view.SurfaceControl;
-import android.view.SurfaceSession;
-import android.window.WindowContainerToken;
-import android.window.WindowContainerTransaction;
-
-import androidx.annotation.NonNull;
-import androidx.annotation.Nullable;
-
-import com.android.internal.protolog.common.ProtoLog;
-import com.android.wm.shell.ShellTaskOrganizer;
-import com.android.wm.shell.common.DisplayController;
-import com.android.wm.shell.common.DisplayImeController;
-import com.android.wm.shell.common.DisplayInsetsController;
-import com.android.wm.shell.common.SurfaceUtils;
-import com.android.wm.shell.common.SyncTransactionQueue;
-import com.android.wm.shell.common.split.SplitLayout;
-import com.android.wm.shell.common.split.SplitWindowManager;
-
-import java.io.PrintWriter;
-
-/**
- * An app-pairs consisting of {@link #mRootTaskInfo} that acts as the hierarchy parent of
- * {@link #mTaskInfo1} and {@link #mTaskInfo2} in the pair.
- * Also includes all UI for managing the pair like the divider.
- */
-class AppPair implements ShellTaskOrganizer.TaskListener, SplitLayout.SplitLayoutHandler {
- private static final String TAG = AppPair.class.getSimpleName();
-
- private ActivityManager.RunningTaskInfo mRootTaskInfo;
- private SurfaceControl mRootTaskLeash;
- private ActivityManager.RunningTaskInfo mTaskInfo1;
- private SurfaceControl mTaskLeash1;
- private ActivityManager.RunningTaskInfo mTaskInfo2;
- private SurfaceControl mTaskLeash2;
- private SurfaceControl mDimLayer1;
- private SurfaceControl mDimLayer2;
- private final SurfaceSession mSurfaceSession = new SurfaceSession();
-
- private final AppPairsController mController;
- private final SyncTransactionQueue mSyncQueue;
- private final DisplayController mDisplayController;
- private final DisplayImeController mDisplayImeController;
- private final DisplayInsetsController mDisplayInsetsController;
- private SplitLayout mSplitLayout;
-
- private final SplitWindowManager.ParentContainerCallbacks mParentContainerCallbacks =
- new SplitWindowManager.ParentContainerCallbacks() {
- @Override
- public void attachToParentSurface(SurfaceControl.Builder b) {
- b.setParent(mRootTaskLeash);
- }
-
- @Override
- public void onLeashReady(SurfaceControl leash) {
- mSyncQueue.runInSync(t -> t
- .show(leash)
- .setLayer(leash, Integer.MAX_VALUE)
- .setPosition(leash,
- mSplitLayout.getDividerBounds().left,
- mSplitLayout.getDividerBounds().top));
- }
- };
-
- AppPair(AppPairsController controller) {
- mController = controller;
- mSyncQueue = controller.getSyncTransactionQueue();
- mDisplayController = controller.getDisplayController();
- mDisplayImeController = controller.getDisplayImeController();
- mDisplayInsetsController = controller.getDisplayInsetsController();
- }
-
- int getRootTaskId() {
- return mRootTaskInfo != null ? mRootTaskInfo.taskId : INVALID_TASK_ID;
- }
-
- private int getTaskId1() {
- return mTaskInfo1 != null ? mTaskInfo1.taskId : INVALID_TASK_ID;
- }
-
- private int getTaskId2() {
- return mTaskInfo2 != null ? mTaskInfo2.taskId : INVALID_TASK_ID;
- }
-
- boolean contains(int taskId) {
- return taskId == getRootTaskId() || taskId == getTaskId1() || taskId == getTaskId2();
- }
-
- boolean pair(ActivityManager.RunningTaskInfo task1, ActivityManager.RunningTaskInfo task2) {
- ProtoLog.v(WM_SHELL_TASK_ORG, "pair task1=%d task2=%d in AppPair=%s",
- task1.taskId, task2.taskId, this);
-
- if (!task1.supportsMultiWindow || !task2.supportsMultiWindow) {
- ProtoLog.e(WM_SHELL_TASK_ORG,
- "Can't pair tasks that doesn't support multi window, "
- + "task1.supportsMultiWindow=%b, task2.supportsMultiWindow=%b",
- task1.supportsMultiWindow, task2.supportsMultiWindow);
- return false;
- }
-
- mTaskInfo1 = task1;
- mTaskInfo2 = task2;
- mSplitLayout = new SplitLayout(TAG + "SplitDivider",
- mDisplayController.getDisplayContext(mRootTaskInfo.displayId),
- mRootTaskInfo.configuration, this /* layoutChangeListener */,
- mParentContainerCallbacks, mDisplayImeController, mController.getTaskOrganizer(),
- SplitLayout.PARALLAX_DISMISSING);
- mDisplayInsetsController.addInsetsChangedListener(mRootTaskInfo.displayId, mSplitLayout);
-
- final WindowContainerToken token1 = task1.token;
- final WindowContainerToken token2 = task2.token;
- final WindowContainerTransaction wct = new WindowContainerTransaction();
-
- wct.setHidden(mRootTaskInfo.token, false)
- .reparent(token1, mRootTaskInfo.token, true /* onTop */)
- .reparent(token2, mRootTaskInfo.token, true /* onTop */)
- .setWindowingMode(token1, WINDOWING_MODE_MULTI_WINDOW)
- .setWindowingMode(token2, WINDOWING_MODE_MULTI_WINDOW)
- .setBounds(token1, mSplitLayout.getBounds1())
- .setBounds(token2, mSplitLayout.getBounds2())
- // Moving the root task to top after the child tasks were repareted , or the root
- // task cannot be visible and focused.
- .reorder(mRootTaskInfo.token, true);
- mController.getTaskOrganizer().applyTransaction(wct);
- return true;
- }
-
- void unpair() {
- unpair(null /* toTopToken */);
- }
-
- private void unpair(@Nullable WindowContainerToken toTopToken) {
- final WindowContainerToken token1 = mTaskInfo1.token;
- final WindowContainerToken token2 = mTaskInfo2.token;
- final WindowContainerTransaction wct = new WindowContainerTransaction();
-
- // Reparent out of this container and reset windowing mode.
- wct.setHidden(mRootTaskInfo.token, true)
- .reorder(mRootTaskInfo.token, false)
- .reparent(token1, null, token1 == toTopToken /* onTop */)
- .reparent(token2, null, token2 == toTopToken /* onTop */)
- .setWindowingMode(token1, WINDOWING_MODE_UNDEFINED)
- .setWindowingMode(token2, WINDOWING_MODE_UNDEFINED);
- mController.getTaskOrganizer().applyTransaction(wct);
-
- mTaskInfo1 = null;
- mTaskInfo2 = null;
- mSplitLayout.release();
- mSplitLayout = null;
- }
-
- @Override
- public void onTaskAppeared(ActivityManager.RunningTaskInfo taskInfo, SurfaceControl leash) {
- if (mRootTaskInfo == null || taskInfo.taskId == mRootTaskInfo.taskId) {
- mRootTaskInfo = taskInfo;
- mRootTaskLeash = leash;
- } else if (taskInfo.taskId == getTaskId1()) {
- mTaskInfo1 = taskInfo;
- mTaskLeash1 = leash;
- mSyncQueue.runInSync(t -> mDimLayer1 =
- SurfaceUtils.makeDimLayer(t, mTaskLeash1, "Dim layer", mSurfaceSession));
- } else if (taskInfo.taskId == getTaskId2()) {
- mTaskInfo2 = taskInfo;
- mTaskLeash2 = leash;
- mSyncQueue.runInSync(t -> mDimLayer2 =
- SurfaceUtils.makeDimLayer(t, mTaskLeash2, "Dim layer", mSurfaceSession));
- } else {
- throw new IllegalStateException("Unknown task=" + taskInfo.taskId);
- }
-
- if (mTaskLeash1 == null || mTaskLeash2 == null) return;
-
- mSplitLayout.init();
-
- mSyncQueue.runInSync(t -> t
- .show(mRootTaskLeash)
- .show(mTaskLeash1)
- .show(mTaskLeash2)
- .setPosition(mTaskLeash1,
- mTaskInfo1.positionInParent.x,
- mTaskInfo1.positionInParent.y)
- .setPosition(mTaskLeash2,
- mTaskInfo2.positionInParent.x,
- mTaskInfo2.positionInParent.y));
- }
-
- @Override
- public void onTaskInfoChanged(ActivityManager.RunningTaskInfo taskInfo) {
- if (!taskInfo.supportsMultiWindow) {
- // Dismiss AppPair if the task no longer supports multi window.
- mController.unpair(mRootTaskInfo.taskId);
- return;
- }
- if (taskInfo.taskId == getRootTaskId()) {
- if (mRootTaskInfo.isVisible != taskInfo.isVisible) {
- mSyncQueue.runInSync(t -> {
- if (taskInfo.isVisible) {
- t.show(mRootTaskLeash);
- } else {
- t.hide(mRootTaskLeash);
- }
- });
- }
- mRootTaskInfo = taskInfo;
-
- if (mSplitLayout != null
- && mSplitLayout.updateConfiguration(mRootTaskInfo.configuration)) {
- onLayoutSizeChanged(mSplitLayout);
- }
- } else if (taskInfo.taskId == getTaskId1()) {
- mTaskInfo1 = taskInfo;
- } else if (taskInfo.taskId == getTaskId2()) {
- mTaskInfo2 = taskInfo;
- } else {
- throw new IllegalStateException("Unknown task=" + taskInfo.taskId);
- }
- }
-
- @Override
- public int getSplitItemPosition(WindowContainerToken token) {
- if (token == null) {
- return SPLIT_POSITION_UNDEFINED;
- }
-
- if (token.equals(mTaskInfo1.getToken())) {
- return SPLIT_POSITION_TOP_OR_LEFT;
- } else if (token.equals(mTaskInfo2.getToken())) {
- return SPLIT_POSITION_BOTTOM_OR_RIGHT;
- }
-
- return SPLIT_POSITION_UNDEFINED;
- }
-
- @Override
- public void onTaskVanished(ActivityManager.RunningTaskInfo taskInfo) {
- if (taskInfo.taskId == getRootTaskId()) {
- // We don't want to release this object back to the pool since the root task went away.
- mController.unpair(mRootTaskInfo.taskId, false /* releaseToPool */);
- } else if (taskInfo.taskId == getTaskId1()) {
- mController.unpair(mRootTaskInfo.taskId);
- mSyncQueue.runInSync(t -> t.remove(mDimLayer1));
- } else if (taskInfo.taskId == getTaskId2()) {
- mController.unpair(mRootTaskInfo.taskId);
- mSyncQueue.runInSync(t -> t.remove(mDimLayer2));
- }
- }
-
- @Override
- public void attachChildSurfaceToTask(int taskId, SurfaceControl.Builder b) {
- b.setParent(findTaskSurface(taskId));
- }
-
- @Override
- public void reparentChildSurfaceToTask(int taskId, SurfaceControl sc,
- SurfaceControl.Transaction t) {
- t.reparent(sc, findTaskSurface(taskId));
- }
-
- private SurfaceControl findTaskSurface(int taskId) {
- if (getRootTaskId() == taskId) {
- return mRootTaskLeash;
- } else if (getTaskId1() == taskId) {
- return mTaskLeash1;
- } else if (getTaskId2() == taskId) {
- return mTaskLeash2;
- } else {
- throw new IllegalArgumentException("There is no surface for taskId=" + taskId);
- }
- }
-
- @Override
- public void dump(@NonNull PrintWriter pw, String prefix) {
- final String innerPrefix = prefix + " ";
- final String childPrefix = innerPrefix + " ";
- pw.println(prefix + this);
- if (mRootTaskInfo != null) {
- pw.println(innerPrefix + "Root taskId=" + mRootTaskInfo.taskId
- + " winMode=" + mRootTaskInfo.getWindowingMode());
- }
- if (mTaskInfo1 != null) {
- pw.println(innerPrefix + "1 taskId=" + mTaskInfo1.taskId
- + " winMode=" + mTaskInfo1.getWindowingMode());
- }
- if (mTaskInfo2 != null) {
- pw.println(innerPrefix + "2 taskId=" + mTaskInfo2.taskId
- + " winMode=" + mTaskInfo2.getWindowingMode());
- }
- }
-
- @Override
- public String toString() {
- return TAG + "#" + getRootTaskId();
- }
-
- @Override
- public void onSnappedToDismiss(boolean snappedToEnd) {
- unpair(snappedToEnd ? mTaskInfo1.token : mTaskInfo2.token /* toTopToken */);
- }
-
- @Override
- public void onLayoutPositionChanging(SplitLayout layout) {
- mSyncQueue.runInSync(t ->
- layout.applySurfaceChanges(t, mTaskLeash1, mTaskLeash2, mDimLayer1, mDimLayer2,
- true /* applyResizingOffset */));
- }
-
- @Override
- public void onLayoutSizeChanging(SplitLayout layout) {
- mSyncQueue.runInSync(t ->
- layout.applySurfaceChanges(t, mTaskLeash1, mTaskLeash2, mDimLayer1, mDimLayer2,
- true /* applyResizingOffset */));
- }
-
- @Override
- public void onLayoutSizeChanged(SplitLayout layout) {
- final WindowContainerTransaction wct = new WindowContainerTransaction();
- layout.applyTaskChanges(wct, mTaskInfo1, mTaskInfo2);
- mSyncQueue.queue(wct);
- mSyncQueue.runInSync(t ->
- layout.applySurfaceChanges(t, mTaskLeash1, mTaskLeash2, mDimLayer1, mDimLayer2,
- false /* applyResizingOffset */));
- }
-
- @Override
- public void setLayoutOffsetTarget(int offsetX, int offsetY, SplitLayout layout) {
- final WindowContainerTransaction wct = new WindowContainerTransaction();
- layout.applyLayoutOffsetTarget(wct, offsetX, offsetY, mTaskInfo1, mTaskInfo2);
- mController.getTaskOrganizer().applyTransaction(wct);
- }
-}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/apppairs/AppPairs.java b/libs/WindowManager/Shell/src/com/android/wm/shell/apppairs/AppPairs.java
deleted file mode 100644
index a9b1dbc3c23b..000000000000
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/apppairs/AppPairs.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.wm.shell.apppairs;
-
-import android.app.ActivityManager;
-
-import androidx.annotation.NonNull;
-
-import com.android.wm.shell.common.annotations.ExternalThread;
-
-import java.io.PrintWriter;
-
-/**
- * Interface to engage app pairs feature.
- */
-@ExternalThread
-public interface AppPairs {
- /** Pairs indicated tasks. */
- boolean pair(int task1, int task2);
- /** Pairs indicated tasks. */
- boolean pair(ActivityManager.RunningTaskInfo task1, ActivityManager.RunningTaskInfo task2);
- /** Unpairs any app-pair containing this task id. */
- void unpair(int taskId);
-}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/apppairs/AppPairsController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/apppairs/AppPairsController.java
deleted file mode 100644
index 53234ab971d6..000000000000
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/apppairs/AppPairsController.java
+++ /dev/null
@@ -1,213 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.wm.shell.apppairs;
-
-import static com.android.wm.shell.protolog.ShellProtoLogGroup.WM_SHELL_TASK_ORG;
-
-import android.app.ActivityManager;
-import android.util.Slog;
-import android.util.SparseArray;
-
-import androidx.annotation.NonNull;
-
-import com.android.internal.annotations.VisibleForTesting;
-import com.android.internal.protolog.common.ProtoLog;
-import com.android.wm.shell.ShellTaskOrganizer;
-import com.android.wm.shell.common.DisplayController;
-import com.android.wm.shell.common.DisplayImeController;
-import com.android.wm.shell.common.DisplayInsetsController;
-import com.android.wm.shell.common.ShellExecutor;
-import com.android.wm.shell.common.SyncTransactionQueue;
-
-import java.io.PrintWriter;
-
-/**
- * Class manages app-pairs multitasking mode and implements the main interface {@link AppPairs}.
- */
-public class AppPairsController {
- private static final String TAG = AppPairsController.class.getSimpleName();
-
- private final ShellTaskOrganizer mTaskOrganizer;
- private final SyncTransactionQueue mSyncQueue;
- private final ShellExecutor mMainExecutor;
- private final AppPairsImpl mImpl = new AppPairsImpl();
-
- private AppPairsPool mPairsPool;
- // Active app-pairs mapped by root task id key.
- private final SparseArray<AppPair> mActiveAppPairs = new SparseArray<>();
- private final DisplayController mDisplayController;
- private final DisplayImeController mDisplayImeController;
- private final DisplayInsetsController mDisplayInsetsController;
-
- public AppPairsController(ShellTaskOrganizer organizer, SyncTransactionQueue syncQueue,
- DisplayController displayController, ShellExecutor mainExecutor,
- DisplayImeController displayImeController,
- DisplayInsetsController displayInsetsController) {
- mTaskOrganizer = organizer;
- mSyncQueue = syncQueue;
- mDisplayController = displayController;
- mDisplayImeController = displayImeController;
- mDisplayInsetsController = displayInsetsController;
- mMainExecutor = mainExecutor;
- }
-
- public AppPairs asAppPairs() {
- return mImpl;
- }
-
- public void onOrganizerRegistered() {
- if (mPairsPool == null) {
- setPairsPool(new AppPairsPool(this));
- }
- }
-
- @VisibleForTesting
- public void setPairsPool(AppPairsPool pool) {
- mPairsPool = pool;
- }
-
- public boolean pair(int taskId1, int taskId2) {
- final ActivityManager.RunningTaskInfo task1 = mTaskOrganizer.getRunningTaskInfo(taskId1);
- final ActivityManager.RunningTaskInfo task2 = mTaskOrganizer.getRunningTaskInfo(taskId2);
- if (task1 == null || task2 == null) {
- return false;
- }
- return pair(task1, task2);
- }
-
- public boolean pair(ActivityManager.RunningTaskInfo task1,
- ActivityManager.RunningTaskInfo task2) {
- return pairInner(task1, task2) != null;
- }
-
- @VisibleForTesting
- public AppPair pairInner(
- @NonNull ActivityManager.RunningTaskInfo task1,
- @NonNull ActivityManager.RunningTaskInfo task2) {
- final AppPair pair = mPairsPool.acquire();
- if (!pair.pair(task1, task2)) {
- mPairsPool.release(pair);
- return null;
- }
-
- mActiveAppPairs.put(pair.getRootTaskId(), pair);
- return pair;
- }
-
- public void unpair(int taskId) {
- unpair(taskId, true /* releaseToPool */);
- }
-
- public void unpair(int taskId, boolean releaseToPool) {
- AppPair pair = mActiveAppPairs.get(taskId);
- if (pair == null) {
- for (int i = mActiveAppPairs.size() - 1; i >= 0; --i) {
- final AppPair candidate = mActiveAppPairs.valueAt(i);
- if (candidate.contains(taskId)) {
- pair = candidate;
- break;
- }
- }
- }
- if (pair == null) {
- ProtoLog.v(WM_SHELL_TASK_ORG, "taskId %d isn't isn't in an app-pair.", taskId);
- return;
- }
-
- ProtoLog.v(WM_SHELL_TASK_ORG, "unpair taskId=%d pair=%s", taskId, pair);
- mActiveAppPairs.remove(pair.getRootTaskId());
- pair.unpair();
- if (releaseToPool) {
- mPairsPool.release(pair);
- }
- }
-
- ShellTaskOrganizer getTaskOrganizer() {
- return mTaskOrganizer;
- }
-
- SyncTransactionQueue getSyncTransactionQueue() {
- return mSyncQueue;
- }
-
- DisplayController getDisplayController() {
- return mDisplayController;
- }
-
- DisplayImeController getDisplayImeController() {
- return mDisplayImeController;
- }
-
- DisplayInsetsController getDisplayInsetsController() {
- return mDisplayInsetsController;
- }
-
- public void dump(@NonNull PrintWriter pw, String prefix) {
- final String innerPrefix = prefix + " ";
- final String childPrefix = innerPrefix + " ";
- pw.println(prefix + this);
-
- for (int i = mActiveAppPairs.size() - 1; i >= 0; --i) {
- mActiveAppPairs.valueAt(i).dump(pw, childPrefix);
- }
-
- if (mPairsPool != null) {
- mPairsPool.dump(pw, prefix);
- }
- }
-
- @Override
- public String toString() {
- return TAG + "#" + mActiveAppPairs.size();
- }
-
- private class AppPairsImpl implements AppPairs {
- @Override
- public boolean pair(int task1, int task2) {
- boolean[] result = new boolean[1];
- try {
- mMainExecutor.executeBlocking(() -> {
- result[0] = AppPairsController.this.pair(task1, task2);
- });
- } catch (InterruptedException e) {
- Slog.e(TAG, "Failed to pair tasks: " + task1 + ", " + task2);
- }
- return result[0];
- }
-
- @Override
- public boolean pair(ActivityManager.RunningTaskInfo task1,
- ActivityManager.RunningTaskInfo task2) {
- boolean[] result = new boolean[1];
- try {
- mMainExecutor.executeBlocking(() -> {
- result[0] = AppPairsController.this.pair(task1, task2);
- });
- } catch (InterruptedException e) {
- Slog.e(TAG, "Failed to pair tasks: " + task1 + ", " + task2);
- }
- return result[0];
- }
-
- @Override
- public void unpair(int taskId) {
- mMainExecutor.execute(() -> {
- AppPairsController.this.unpair(taskId);
- });
- }
- }
-}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/apppairs/AppPairsPool.java b/libs/WindowManager/Shell/src/com/android/wm/shell/apppairs/AppPairsPool.java
deleted file mode 100644
index 5c6037ea0702..000000000000
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/apppairs/AppPairsPool.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.wm.shell.apppairs;
-
-import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
-import static android.view.Display.DEFAULT_DISPLAY;
-
-import static com.android.wm.shell.protolog.ShellProtoLogGroup.WM_SHELL_TASK_ORG;
-
-import androidx.annotation.NonNull;
-
-import com.android.internal.annotations.VisibleForTesting;
-import com.android.internal.protolog.common.ProtoLog;
-
-import java.io.PrintWriter;
-import java.util.ArrayList;
-
-/**
- * Class that manager pool of {@link AppPair} objects. Helps reduce the need to call system_server
- * to create a root task for the app-pair when needed since we always have one ready to go.
- */
-class AppPairsPool {
- private static final String TAG = AppPairsPool.class.getSimpleName();
-
- @VisibleForTesting
- final AppPairsController mController;
- // The pool
- private final ArrayList<AppPair> mPool = new ArrayList();
-
- AppPairsPool(AppPairsController controller) {
- mController = controller;
- incrementPool();
- }
-
- AppPair acquire() {
- final AppPair entry = mPool.remove(mPool.size() - 1);
- ProtoLog.v(WM_SHELL_TASK_ORG, "acquire entry.taskId=%s listener=%s size=%d",
- entry.getRootTaskId(), entry, mPool.size());
- if (mPool.size() == 0) {
- incrementPool();
- }
- return entry;
- }
-
- void release(AppPair entry) {
- mPool.add(entry);
- ProtoLog.v(WM_SHELL_TASK_ORG, "release entry.taskId=%s listener=%s size=%d",
- entry.getRootTaskId(), entry, mPool.size());
- }
-
- @VisibleForTesting
- void incrementPool() {
- ProtoLog.v(WM_SHELL_TASK_ORG, "incrementPool size=%d", mPool.size());
- final AppPair entry = new AppPair(mController);
- // TODO: multi-display...
- mController.getTaskOrganizer().createRootTask(
- DEFAULT_DISPLAY, WINDOWING_MODE_FULLSCREEN, entry);
- mPool.add(entry);
- }
-
- @VisibleForTesting
- int poolSize() {
- return mPool.size();
- }
-
- public void dump(@NonNull PrintWriter pw, String prefix) {
- final String innerPrefix = prefix + " ";
- final String childPrefix = innerPrefix + " ";
- pw.println(prefix + this);
- for (int i = mPool.size() - 1; i >= 0; --i) {
- mPool.get(i).dump(pw, childPrefix);
- }
- }
-
- @Override
- public String toString() {
- return TAG + "#" + mPool.size();
- }
-}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/apppairs/OWNERS b/libs/WindowManager/Shell/src/com/android/wm/shell/apppairs/OWNERS
deleted file mode 100644
index 4d9b520e3f0e..000000000000
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/apppairs/OWNERS
+++ /dev/null
@@ -1,2 +0,0 @@
-# WM shell sub-modules apppair owner
-chenghsiuchang@google.com
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BadgedImageView.java b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BadgedImageView.java
index b04a1fa93bbd..f1ee8fa38485 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BadgedImageView.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BadgedImageView.java
@@ -183,7 +183,7 @@ public class BadgedImageView extends ConstraintLayout {
getDrawingRect(mTempBounds);
- mDrawParams.color = mDotColor;
+ mDrawParams.dotColor = mDotColor;
mDrawParams.iconBounds = mTempBounds;
mDrawParams.leftAlign = mOnLeft;
mDrawParams.scale = mDotScale;
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleController.java
index f407bdcb8852..6c0a6b4c81b6 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleController.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleController.java
@@ -78,7 +78,6 @@ import android.view.View;
import android.view.ViewGroup;
import android.view.WindowInsets;
import android.view.WindowManager;
-import android.window.WindowContainerTransaction;
import androidx.annotation.MainThread;
import androidx.annotation.Nullable;
@@ -89,13 +88,14 @@ import com.android.internal.statusbar.IStatusBarService;
import com.android.wm.shell.ShellTaskOrganizer;
import com.android.wm.shell.TaskViewTransitions;
import com.android.wm.shell.WindowManagerShellWrapper;
-import com.android.wm.shell.common.DisplayChangeController;
import com.android.wm.shell.common.DisplayController;
import com.android.wm.shell.common.FloatingContentCoordinator;
import com.android.wm.shell.common.ShellExecutor;
import com.android.wm.shell.common.SyncTransactionQueue;
import com.android.wm.shell.common.TaskStackListenerCallback;
import com.android.wm.shell.common.TaskStackListenerImpl;
+import com.android.wm.shell.common.annotations.ShellBackgroundThread;
+import com.android.wm.shell.common.annotations.ShellMainThread;
import com.android.wm.shell.draganddrop.DragAndDropController;
import com.android.wm.shell.onehanded.OneHandedController;
import com.android.wm.shell.onehanded.OneHandedTransitionCallback;
@@ -158,6 +158,8 @@ public class BubbleController {
private final ShellExecutor mMainExecutor;
private final Handler mMainHandler;
+ private final ShellExecutor mBackgroundExecutor;
+
private BubbleLogger mLogger;
private BubbleData mBubbleData;
@Nullable private BubbleStackView mStackView;
@@ -234,8 +236,9 @@ public class BubbleController {
DisplayController displayController,
Optional<OneHandedController> oneHandedOptional,
DragAndDropController dragAndDropController,
- ShellExecutor mainExecutor,
- Handler mainHandler,
+ @ShellMainThread ShellExecutor mainExecutor,
+ @ShellMainThread Handler mainHandler,
+ @ShellBackgroundThread ShellExecutor bgExecutor,
TaskViewTransitions taskViewTransitions,
SyncTransactionQueue syncQueue) {
BubbleLogger logger = new BubbleLogger(uiEventLogger);
@@ -245,7 +248,7 @@ public class BubbleController {
new BubbleDataRepository(context, launcherApps, mainExecutor),
statusBarService, windowManager, windowManagerShellWrapper, launcherApps,
logger, taskStackListener, organizer, positioner, displayController,
- oneHandedOptional, dragAndDropController, mainExecutor, mainHandler,
+ oneHandedOptional, dragAndDropController, mainExecutor, mainHandler, bgExecutor,
taskViewTransitions, syncQueue);
}
@@ -269,8 +272,9 @@ public class BubbleController {
DisplayController displayController,
Optional<OneHandedController> oneHandedOptional,
DragAndDropController dragAndDropController,
- ShellExecutor mainExecutor,
- Handler mainHandler,
+ @ShellMainThread ShellExecutor mainExecutor,
+ @ShellMainThread Handler mainHandler,
+ @ShellBackgroundThread ShellExecutor bgExecutor,
TaskViewTransitions taskViewTransitions,
SyncTransactionQueue syncQueue) {
mContext = context;
@@ -286,6 +290,7 @@ public class BubbleController {
mLogger = bubbleLogger;
mMainExecutor = mainExecutor;
mMainHandler = mainHandler;
+ mBackgroundExecutor = bgExecutor;
mTaskStackListener = taskStackListener;
mTaskOrganizer = organizer;
mSurfaceSynchronizer = synchronizer;
@@ -423,17 +428,13 @@ public class BubbleController {
});
mDisplayController.addDisplayChangingController(
- new DisplayChangeController.OnDisplayChangingListener() {
- @Override
- public void onRotateDisplay(int displayId, int fromRotation, int toRotation,
- WindowContainerTransaction t) {
- // This is triggered right before the rotation is applied
- if (fromRotation != toRotation) {
- if (mStackView != null) {
- // Layout listener set on stackView will update the positioner
- // once the rotation is applied
- mStackView.onOrientationChanged();
- }
+ (displayId, fromRotation, toRotation, newDisplayAreaInfo, t) -> {
+ // This is triggered right before the rotation is applied
+ if (fromRotation != toRotation) {
+ if (mStackView != null) {
+ // Layout listener set on stackView will update the positioner
+ // once the rotation is applied
+ mStackView.onOrientationChanged();
}
}
});
@@ -725,7 +726,8 @@ public class BubbleController {
try {
mAddedToWindowManager = false;
- mContext.unregisterReceiver(mBroadcastReceiver);
+ // Put on background for this binder call, was causing jank
+ mBackgroundExecutor.execute(() -> mContext.unregisterReceiver(mBroadcastReceiver));
if (mStackView != null) {
mWindowManager.removeView(mStackView);
mBubbleData.getOverflow().cleanUpExpandedState();
@@ -1518,7 +1520,7 @@ public class BubbleController {
public void onImeVisibilityChanged(boolean imeVisible, int imeHeight) {
mBubblePositioner.setImeVisible(imeVisible, imeHeight);
if (mStackView != null) {
- mStackView.animateForIme(imeVisible);
+ mStackView.setImeVisible(imeVisible);
}
}
}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleDebugConfig.java b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleDebugConfig.java
index dc2ace949f0c..dce6b56261ff 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleDebugConfig.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleDebugConfig.java
@@ -46,6 +46,9 @@ public class BubbleDebugConfig {
static final boolean DEBUG_OVERFLOW = false;
static final boolean DEBUG_USER_EDUCATION = false;
static final boolean DEBUG_POSITIONER = false;
+ public static final boolean DEBUG_COLLAPSE_ANIMATOR = false;
+ static final boolean DEBUG_BUBBLE_GESTURE = false;
+ public static boolean DEBUG_EXPANDED_VIEW_DRAGGING = false;
private static final boolean FORCE_SHOW_USER_EDUCATION = false;
private static final String FORCE_SHOW_USER_EDUCATION_SETTING =
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleExpandedView.java b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleExpandedView.java
index a089585a5a00..1eb6f731d173 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleExpandedView.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleExpandedView.java
@@ -43,10 +43,13 @@ import android.graphics.CornerPathEffect;
import android.graphics.Outline;
import android.graphics.Paint;
import android.graphics.Picture;
+import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.drawable.ShapeDrawable;
import android.os.RemoteException;
import android.util.AttributeSet;
+import android.util.FloatProperty;
+import android.util.IntProperty;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
@@ -75,6 +78,48 @@ import java.io.PrintWriter;
public class BubbleExpandedView extends LinearLayout {
private static final String TAG = TAG_WITH_CLASS_NAME ? "BubbleExpandedView" : TAG_BUBBLES;
+ /** {@link IntProperty} for updating bottom clip */
+ public static final IntProperty<BubbleExpandedView> BOTTOM_CLIP_PROPERTY =
+ new IntProperty<BubbleExpandedView>("bottomClip") {
+ @Override
+ public void setValue(BubbleExpandedView expandedView, int value) {
+ expandedView.setBottomClip(value);
+ }
+
+ @Override
+ public Integer get(BubbleExpandedView expandedView) {
+ return expandedView.mBottomClip;
+ }
+ };
+
+ /** {@link FloatProperty} for updating taskView or overflow alpha */
+ public static final FloatProperty<BubbleExpandedView> CONTENT_ALPHA =
+ new FloatProperty<BubbleExpandedView>("contentAlpha") {
+ @Override
+ public void setValue(BubbleExpandedView expandedView, float value) {
+ expandedView.setContentAlpha(value);
+ }
+
+ @Override
+ public Float get(BubbleExpandedView expandedView) {
+ return expandedView.getContentAlpha();
+ }
+ };
+
+ /** {@link FloatProperty} for updating manage button alpha */
+ public static final FloatProperty<BubbleExpandedView> MANAGE_BUTTON_ALPHA =
+ new FloatProperty<BubbleExpandedView>("manageButtonAlpha") {
+ @Override
+ public void setValue(BubbleExpandedView expandedView, float value) {
+ expandedView.mManageButton.setAlpha(value);
+ }
+
+ @Override
+ public Float get(BubbleExpandedView expandedView) {
+ return expandedView.mManageButton.getAlpha();
+ }
+ };
+
// The triangle pointing to the expanded view
private View mPointerView;
@Nullable private int[] mExpandedViewContainerLocation;
@@ -90,7 +135,7 @@ public class BubbleExpandedView extends LinearLayout {
/**
* Whether we want the {@code TaskView}'s content to be visible (alpha = 1f). If
- * {@link #mIsAlphaAnimating} is true, this may not reflect the {@code TaskView}'s actual alpha
+ * {@link #mIsAnimating} is true, this may not reflect the {@code TaskView}'s actual alpha
* value until the animation ends.
*/
private boolean mIsContentVisible = false;
@@ -99,12 +144,13 @@ public class BubbleExpandedView extends LinearLayout {
* Whether we're animating the {@code TaskView}'s alpha value. If so, we will hold off on
* applying alpha changes from {@link #setContentVisibility} until the animation ends.
*/
- private boolean mIsAlphaAnimating = false;
+ private boolean mIsAnimating = false;
private int mPointerWidth;
private int mPointerHeight;
private float mPointerRadius;
private float mPointerOverlap;
+ private final PointF mPointerPos = new PointF();
private CornerPathEffect mPointerEffect;
private ShapeDrawable mCurrentPointer;
private ShapeDrawable mTopPointer;
@@ -113,11 +159,13 @@ public class BubbleExpandedView extends LinearLayout {
private float mCornerRadius = 0f;
private int mBackgroundColorFloating;
private boolean mUsingMaxHeight;
-
+ private int mTopClip = 0;
+ private int mBottomClip = 0;
@Nullable private Bubble mBubble;
private PendingIntent mPendingIntent;
// TODO(b/170891664): Don't use a flag, set the BubbleOverflow object instead
private boolean mIsOverflow;
+ private boolean mIsClipping;
private BubbleController mController;
private BubbleStackView mStackView;
@@ -268,7 +316,8 @@ public class BubbleExpandedView extends LinearLayout {
mExpandedViewContainer.setOutlineProvider(new ViewOutlineProvider() {
@Override
public void getOutline(View view, Outline outline) {
- outline.setRoundRect(0, 0, view.getWidth(), view.getHeight(), mCornerRadius);
+ Rect clip = new Rect(0, mTopClip, view.getWidth(), view.getHeight() - mBottomClip);
+ outline.setRoundRect(clip, mCornerRadius);
}
});
mExpandedViewContainer.setClipToOutline(true);
@@ -300,9 +349,9 @@ public class BubbleExpandedView extends LinearLayout {
// they should not collapse the stack (which all other touches on areas around the AV
// would do).
if (motionEvent.getRawY() >= avBounds.top
- && motionEvent.getRawY() <= avBounds.bottom
- && (motionEvent.getRawX() < avBounds.left
- || motionEvent.getRawX() > avBounds.right)) {
+ && motionEvent.getRawY() <= avBounds.bottom
+ && (motionEvent.getRawX() < avBounds.left
+ || motionEvent.getRawX() > avBounds.right)) {
return true;
}
@@ -384,7 +433,7 @@ public class BubbleExpandedView extends LinearLayout {
}
void applyThemeAttrs() {
- final TypedArray ta = mContext.obtainStyledAttributes(new int[] {
+ final TypedArray ta = mContext.obtainStyledAttributes(new int[]{
android.R.attr.dialogCornerRadius,
android.R.attr.colorBackgroundFloating});
boolean supportsRoundedCorners = ScreenDecorationsUtils.supportsRoundedCornersOnWindows(
@@ -429,7 +478,7 @@ public class BubbleExpandedView extends LinearLayout {
* ordering surfaces during animations. When content is drawn on top of the app (e.g. bubble
* being dragged out, the manage menu) this is set to false, otherwise it should be true.
*/
- void setSurfaceZOrderedOnTop(boolean onTop) {
+ public void setSurfaceZOrderedOnTop(boolean onTop) {
if (mTaskView == null) {
return;
}
@@ -510,12 +559,12 @@ public class BubbleExpandedView extends LinearLayout {
}
/**
- * Whether we are currently animating the {@code TaskView}'s alpha value. If this is set to
+ * Whether we are currently animating the {@code TaskView}. If this is set to
* true, calls to {@link #setContentVisibility} will not be applied until this is set to false
* again.
*/
- void setAlphaAnimating(boolean animating) {
- mIsAlphaAnimating = animating;
+ public void setAnimating(boolean animating) {
+ mIsAnimating = animating;
// If we're done animating, apply the correct
if (!animating) {
@@ -524,15 +573,128 @@ public class BubbleExpandedView extends LinearLayout {
}
/**
- * Sets the alpha of the underlying {@code TaskView}, since changing the expanded view's alpha
- * does not affect the {@code TaskView} since it uses a Surface.
+ * Get alpha from underlying {@code TaskView} if this view is for a bubble.
+ * Or get alpha for the overflow view if this view is for overflow.
+ *
+ * @return alpha for the content being shown
*/
- void setTaskViewAlpha(float alpha) {
+ public float getContentAlpha() {
+ if (mIsOverflow) {
+ return mOverflowView.getAlpha();
+ }
if (mTaskView != null) {
+ return mTaskView.getAlpha();
+ }
+ return 1f;
+ }
+
+ /**
+ * Set alpha of the underlying {@code TaskView} if this view is for a bubble.
+ * Or set alpha for the overflow view if this view is for overflow.
+ *
+ * Changing expanded view's alpha does not affect the {@code TaskView} since it uses a Surface.
+ */
+ public void setContentAlpha(float alpha) {
+ if (mIsOverflow) {
+ mOverflowView.setAlpha(alpha);
+ } else if (mTaskView != null) {
mTaskView.setAlpha(alpha);
}
- mPointerView.setAlpha(alpha);
- setAlpha(alpha);
+ }
+
+ /**
+ * Set translation Y for the expanded view content.
+ * Excludes manage button and pointer.
+ */
+ public void setContentTranslationY(float translationY) {
+ mExpandedViewContainer.setTranslationY(translationY);
+
+ // Left or right pointer can become detached when moving the view up
+ if (translationY <= 0 && (isShowingLeftPointer() || isShowingRightPointer())) {
+ // Y coordinate where the pointer would start to get detached from the expanded view.
+ // Takes into account bottom clipping and rounded corners
+ float detachPoint =
+ mExpandedViewContainer.getBottom() - mBottomClip - mCornerRadius + translationY;
+ float pointerBottom = mPointerPos.y + mPointerHeight;
+ // If pointer bottom is past detach point, move it in by that many pixels
+ float horizontalShift = 0;
+ if (pointerBottom > detachPoint) {
+ horizontalShift = pointerBottom - detachPoint;
+ }
+ if (isShowingLeftPointer()) {
+ // Move left pointer right
+ movePointerBy(horizontalShift, 0);
+ } else {
+ // Move right pointer left
+ movePointerBy(-horizontalShift, 0);
+ }
+ // Hide pointer if it is moved by entire width
+ mPointerView.setVisibility(
+ horizontalShift > mPointerWidth ? View.INVISIBLE : View.VISIBLE);
+ }
+ }
+
+ /**
+ * Update alpha value for the manage button
+ */
+ public void setManageButtonAlpha(float alpha) {
+ mManageButton.setAlpha(alpha);
+ }
+
+ /**
+ * Set {@link #setTranslationY(float) translationY} for the manage button
+ */
+ public void setManageButtonTranslationY(float translationY) {
+ mManageButton.setTranslationY(translationY);
+ }
+
+ /**
+ * Set top clipping for the view
+ */
+ public void setTopClip(int clip) {
+ mTopClip = clip;
+ onContainerClipUpdate();
+ }
+
+ /**
+ * Set bottom clipping for the view
+ */
+ public void setBottomClip(int clip) {
+ mBottomClip = clip;
+ onContainerClipUpdate();
+ }
+
+ private void onContainerClipUpdate() {
+ if (mTopClip == 0 && mBottomClip == 0) {
+ if (mIsClipping) {
+ mIsClipping = false;
+ if (mTaskView != null) {
+ mTaskView.setClipBounds(null);
+ mTaskView.setEnableSurfaceClipping(false);
+ }
+ mExpandedViewContainer.invalidateOutline();
+ }
+ } else {
+ if (!mIsClipping) {
+ mIsClipping = true;
+ if (mTaskView != null) {
+ mTaskView.setEnableSurfaceClipping(true);
+ }
+ }
+ mExpandedViewContainer.invalidateOutline();
+ if (mTaskView != null) {
+ mTaskView.setClipBounds(new Rect(0, mTopClip, mTaskView.getWidth(),
+ mTaskView.getHeight() - mBottomClip));
+ }
+ }
+ }
+
+ /**
+ * Move pointer from base position
+ */
+ public void movePointerBy(float x, float y) {
+ mPointerView.setTranslationX(mPointerPos.x + x);
+ mPointerView.setTranslationY(mPointerPos.y + y);
}
/**
@@ -543,13 +705,13 @@ public class BubbleExpandedView extends LinearLayout {
* Note that this contents visibility doesn't affect visibility at {@link android.view.View},
* and setting {@code false} actually means rendering the contents in transparent.
*/
- void setContentVisibility(boolean visibility) {
+ public void setContentVisibility(boolean visibility) {
if (DEBUG_BUBBLE_EXPANDED_VIEW) {
Log.d(TAG, "setContentVisibility: visibility=" + visibility
+ " bubble=" + getBubbleKey());
}
mIsContentVisible = visibility;
- if (mTaskView != null && !mIsAlphaAnimating) {
+ if (mTaskView != null && !mIsAnimating) {
mTaskView.setAlpha(visibility ? 1f : 0f);
mPointerView.setAlpha(visibility ? 1f : 0f);
}
@@ -560,6 +722,44 @@ public class BubbleExpandedView extends LinearLayout {
return mTaskView;
}
+ @VisibleForTesting
+ public BubbleOverflowContainerView getOverflow() {
+ return mOverflowView;
+ }
+
+
+ /**
+ * Return content height: taskView or overflow.
+ * Takes into account clippings set by {@link #setTopClip(int)} and {@link #setBottomClip(int)}
+ *
+ * @return if bubble is for overflow, return overflow height, otherwise return taskView height
+ */
+ public int getContentHeight() {
+ if (mIsOverflow) {
+ return mOverflowView.getHeight() - mTopClip - mBottomClip;
+ }
+ if (mTaskView != null) {
+ return mTaskView.getHeight() - mTopClip - mBottomClip;
+ }
+ return 0;
+ }
+
+ /**
+ * Return bottom position of the content on screen
+ *
+ * @return if bubble is for overflow, return value for overflow, otherwise taskView
+ */
+ public int getContentBottomOnScreen() {
+ Rect out = new Rect();
+ if (mIsOverflow) {
+ mOverflowView.getBoundsOnScreen(out);
+ }
+ if (mTaskView != null) {
+ mTaskView.getBoundsOnScreen(out);
+ }
+ return out.bottom;
+ }
+
int getTaskId() {
return mTaskId;
}
@@ -728,28 +928,48 @@ public class BubbleExpandedView extends LinearLayout {
post(() -> {
mCurrentPointer = showVertically ? onLeft ? mLeftPointer : mRightPointer : mTopPointer;
updatePointerView();
- float pointerY;
- float pointerX;
if (showVertically) {
- pointerY = bubbleCenter - (mPointerWidth / 2f);
- pointerX = onLeft
+ mPointerPos.y = bubbleCenter - (mPointerWidth / 2f);
+ mPointerPos.x = onLeft
? -mPointerHeight + mPointerOverlap
: getWidth() - mPaddingRight - mPointerOverlap;
} else {
- pointerY = mPointerOverlap;
- pointerX = bubbleCenter - (mPointerWidth / 2f);
+ mPointerPos.y = mPointerOverlap;
+ mPointerPos.x = bubbleCenter - (mPointerWidth / 2f);
}
if (animate) {
- mPointerView.animate().translationX(pointerX).translationY(pointerY).start();
+ mPointerView.animate().translationX(mPointerPos.x).translationY(
+ mPointerPos.y).start();
} else {
- mPointerView.setTranslationY(pointerY);
- mPointerView.setTranslationX(pointerX);
+ mPointerView.setTranslationY(mPointerPos.y);
+ mPointerView.setTranslationX(mPointerPos.x);
mPointerView.setVisibility(VISIBLE);
}
});
}
/**
+ * Return true if pointer is shown on the left
+ */
+ public boolean isShowingLeftPointer() {
+ return mCurrentPointer == mLeftPointer;
+ }
+
+ /**
+ * Return true if pointer is shown on the right
+ */
+ public boolean isShowingRightPointer() {
+ return mCurrentPointer == mRightPointer;
+ }
+
+ /**
+ * Return width of the current pointer
+ */
+ public int getPointerWidth() {
+ return mPointerWidth;
+ }
+
+ /**
* Position of the manage button displayed in the expanded view. Used for placing user
* education about the manage button.
*/
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubblePositioner.java b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubblePositioner.java
index 7cfacbcc92f8..7d60114fe927 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubblePositioner.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubblePositioner.java
@@ -344,6 +344,14 @@ public class BubblePositioner {
return mImeVisible ? mImeHeight : 0;
}
+ /** Return top position of the IME if it's visible */
+ public int getImeTop() {
+ if (mImeVisible) {
+ return getScreenRect().bottom - getImeHeight() - getInsets().bottom;
+ }
+ return 0;
+ }
+
/** Sets whether the IME is visible. **/
public void setImeVisible(boolean visible, int height) {
mImeVisible = visible;
@@ -706,4 +714,21 @@ public class BubblePositioner {
public void setPinnedLocation(PointF point) {
mPinLocation = point;
}
+
+ /**
+ * Navigation bar has an area where system gestures can be started from.
+ *
+ * @return {@link Rect} for system navigation bar gesture zone
+ */
+ public Rect getNavBarGestureZone() {
+ // Gesture zone height from the bottom
+ int gestureZoneHeight = mContext.getResources().getDimensionPixelSize(
+ com.android.internal.R.dimen.navigation_bar_gesture_height);
+ Rect screen = getScreenRect();
+ return new Rect(
+ screen.left,
+ screen.bottom - gestureZoneHeight,
+ screen.right,
+ screen.bottom);
+ }
}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleStackView.java b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleStackView.java
index b7c5eb06fbfa..941bcab9b81d 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleStackView.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleStackView.java
@@ -44,6 +44,7 @@ import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
+import android.os.SystemProperties;
import android.provider.Settings;
import android.util.Log;
import android.view.Choreographer;
@@ -56,6 +57,7 @@ import android.view.View;
import android.view.ViewGroup;
import android.view.ViewOutlineProvider;
import android.view.ViewTreeObserver;
+import android.view.WindowManagerPolicyConstants;
import android.view.accessibility.AccessibilityNodeInfo;
import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction;
import android.widget.FrameLayout;
@@ -75,8 +77,12 @@ import com.android.internal.util.FrameworkStatsLog;
import com.android.wm.shell.R;
import com.android.wm.shell.animation.Interpolators;
import com.android.wm.shell.animation.PhysicsAnimator;
+import com.android.wm.shell.bubbles.BubblesNavBarMotionEventHandler.MotionEventListener;
import com.android.wm.shell.bubbles.animation.AnimatableScaleMatrix;
import com.android.wm.shell.bubbles.animation.ExpandedAnimationController;
+import com.android.wm.shell.bubbles.animation.ExpandedViewAnimationController;
+import com.android.wm.shell.bubbles.animation.ExpandedViewAnimationControllerImpl;
+import com.android.wm.shell.bubbles.animation.ExpandedViewAnimationControllerStub;
import com.android.wm.shell.bubbles.animation.PhysicsAnimationLayout;
import com.android.wm.shell.bubbles.animation.StackAnimationController;
import com.android.wm.shell.common.FloatingContentCoordinator;
@@ -97,6 +103,12 @@ import java.util.stream.Collectors;
*/
public class BubbleStackView extends FrameLayout
implements ViewTreeObserver.OnComputeInternalInsetsListener {
+ /**
+ * Set to {@code true} to enable home gesture handling in bubbles
+ */
+ public static final boolean HOME_GESTURE_ENABLED =
+ SystemProperties.getBoolean("persist.wm.debug.bubbles_home_gesture", false);
+
private static final String TAG = TAG_WITH_CLASS_NAME ? "BubbleStackView" : TAG_BUBBLES;
/** How far the flyout needs to be dragged before it's dismissed regardless of velocity. */
@@ -148,7 +160,7 @@ public class BubbleStackView extends FrameLayout
* Handler to use for all delayed animations - this way, we can easily cancel them before
* starting a new animation.
*/
- private final ShellExecutor mDelayedAnimationExecutor;
+ private final ShellExecutor mMainExecutor;
private Runnable mDelayedAnimation;
/**
@@ -197,6 +209,7 @@ public class BubbleStackView extends FrameLayout
private PhysicsAnimationLayout mBubbleContainer;
private StackAnimationController mStackAnimationController;
private ExpandedAnimationController mExpandedAnimationController;
+ private ExpandedViewAnimationController mExpandedViewAnimationController;
private View mScrim;
private View mManageMenuScrim;
@@ -276,6 +289,9 @@ public class BubbleStackView extends FrameLayout
*/
private int mPointerIndexDown = -1;
+ @Nullable
+ private BubblesNavBarGestureTracker mBubblesNavBarGestureTracker;
+
/** Description of current animation controller state. */
public void dump(PrintWriter pw, String[] args) {
pw.println("Stack view state:");
@@ -693,6 +709,67 @@ public class BubbleStackView extends FrameLayout
}
};
+ /** Touch listener set on the whole view that forwards event to the swipe up listener. */
+ private final RelativeTouchListener mContainerSwipeListener = new RelativeTouchListener() {
+ @Override
+ public boolean onDown(@NonNull View v, @NonNull MotionEvent ev) {
+ // Pass move event on to swipe listener
+ mSwipeUpListener.onDown(ev.getX(), ev.getY());
+ return true;
+ }
+
+ @Override
+ public void onMove(@NonNull View v, @NonNull MotionEvent ev, float viewInitialX,
+ float viewInitialY, float dx, float dy) {
+ // Pass move event on to swipe listener
+ mSwipeUpListener.onMove(dx, dy);
+ }
+
+ @Override
+ public void onUp(@NonNull View v, @NonNull MotionEvent ev, float viewInitialX,
+ float viewInitialY, float dx, float dy, float velX, float velY) {
+ // Pass up even on to swipe listener
+ mSwipeUpListener.onUp(velX, velY);
+ }
+ };
+
+ /** MotionEventListener that listens from home gesture swipe event. */
+ private final MotionEventListener mSwipeUpListener = new MotionEventListener() {
+ @Override
+ public void onDown(float x, float y) {}
+
+ @Override
+ public void onMove(float dx, float dy) {
+ if ((mManageEduView != null && mManageEduView.getVisibility() == VISIBLE)
+ || isStackEduShowing()) {
+ return;
+ }
+
+ if (mShowingManage) {
+ showManageMenu(false /* show */);
+ }
+ // Only allow up
+ float collapsed = Math.min(dy, 0);
+ mExpandedViewAnimationController.updateDrag((int) -collapsed);
+ }
+
+ @Override
+ public void onCancel() {
+ mExpandedViewAnimationController.animateBackToExpanded();
+ }
+
+ @Override
+ public void onUp(float velX, float velY) {
+ mExpandedViewAnimationController.setSwipeVelocity(velY);
+ if (mExpandedViewAnimationController.shouldCollapse()) {
+ // Update data first and start the animation when we are processing change
+ mBubbleData.setExpanded(false);
+ } else {
+ mExpandedViewAnimationController.animateBackToExpanded();
+ }
+ }
+ };
+
/** Click listener set on the flyout, which expands the stack when the flyout is tapped. */
private OnClickListener mFlyoutClickListener = new OnClickListener() {
@Override
@@ -766,7 +843,7 @@ public class BubbleStackView extends FrameLayout
ShellExecutor mainExecutor) {
super(context);
- mDelayedAnimationExecutor = mainExecutor;
+ mMainExecutor = mainExecutor;
mBubbleController = bubbleController;
mBubbleData = data;
@@ -796,6 +873,14 @@ public class BubbleStackView extends FrameLayout
mExpandedAnimationController = new ExpandedAnimationController(mPositioner,
onBubbleAnimatedOut, this);
+
+ if (HOME_GESTURE_ENABLED) {
+ mExpandedViewAnimationController =
+ new ExpandedViewAnimationControllerImpl(context, mPositioner);
+ } else {
+ mExpandedViewAnimationController = new ExpandedViewAnimationControllerStub();
+ }
+
mSurfaceSynchronizer = synchronizer != null ? synchronizer : DEFAULT_SURFACE_SYNCHRONIZER;
// Force LTR by default since most of the Bubbles UI is positioned manually by the user, or
@@ -971,7 +1056,7 @@ public class BubbleStackView extends FrameLayout
if (mExpandedBubble != null && mExpandedBubble.getExpandedView() != null) {
// We need to be Z ordered on top in order for alpha animations to work.
mExpandedBubble.getExpandedView().setSurfaceZOrderedOnTop(true);
- mExpandedBubble.getExpandedView().setAlphaAnimating(true);
+ mExpandedBubble.getExpandedView().setAnimating(true);
}
}
@@ -985,14 +1070,15 @@ public class BubbleStackView extends FrameLayout
// = 0f remains in effect.
&& !mExpandedViewTemporarilyHidden) {
mExpandedBubble.getExpandedView().setSurfaceZOrderedOnTop(false);
- mExpandedBubble.getExpandedView().setAlphaAnimating(false);
+ mExpandedBubble.getExpandedView().setAnimating(false);
}
}
});
mExpandedViewAlphaAnimator.addUpdateListener(valueAnimator -> {
if (mExpandedBubble != null && mExpandedBubble.getExpandedView() != null) {
- mExpandedBubble.getExpandedView().setTaskViewAlpha(
- (float) valueAnimator.getAnimatedValue());
+ float alpha = (float) valueAnimator.getAnimatedValue();
+ mExpandedBubble.getExpandedView().setContentAlpha(alpha);
+ mExpandedBubble.getExpandedView().setAlpha(alpha);
}
});
@@ -1795,6 +1881,7 @@ public class BubbleStackView extends FrameLayout
private void showNewlySelectedBubble(BubbleViewProvider bubbleToSelect) {
final BubbleViewProvider previouslySelected = mExpandedBubble;
mExpandedBubble = bubbleToSelect;
+ mExpandedViewAnimationController.setExpandedView(mExpandedBubble.getExpandedView());
if (mIsExpanded) {
hideCurrentInputMethod();
@@ -1848,7 +1935,12 @@ public class BubbleStackView extends FrameLayout
mBubbleController.getSysuiProxy().onStackExpandChanged(shouldExpand);
if (mIsExpanded) {
- animateCollapse();
+ stopMonitoringSwipeUpGesture();
+ if (HOME_GESTURE_ENABLED) {
+ animateCollapse();
+ } else {
+ animateCollapseWithScale();
+ }
logBubbleEvent(mExpandedBubble, FrameworkStatsLog.BUBBLE_UICHANGED__ACTION__COLLAPSED);
} else {
animateExpansion();
@@ -1856,10 +1948,37 @@ public class BubbleStackView extends FrameLayout
logBubbleEvent(mExpandedBubble, FrameworkStatsLog.BUBBLE_UICHANGED__ACTION__EXPANDED);
logBubbleEvent(mExpandedBubble,
FrameworkStatsLog.BUBBLE_UICHANGED__ACTION__STACK_EXPANDED);
+ if (HOME_GESTURE_ENABLED) {
+ startMonitoringSwipeUpGesture();
+ }
}
notifyExpansionChanged(mExpandedBubble, mIsExpanded);
}
+ private void startMonitoringSwipeUpGesture() {
+ stopMonitoringSwipeUpGesture();
+
+ if (isGestureNavEnabled()) {
+ mBubblesNavBarGestureTracker = new BubblesNavBarGestureTracker(mContext, mPositioner);
+ mBubblesNavBarGestureTracker.start(mSwipeUpListener);
+ setOnTouchListener(mContainerSwipeListener);
+ }
+ }
+
+ private boolean isGestureNavEnabled() {
+ return mContext.getResources().getInteger(
+ com.android.internal.R.integer.config_navBarInteractionMode)
+ == WindowManagerPolicyConstants.NAV_BAR_MODE_GESTURAL;
+ }
+
+ private void stopMonitoringSwipeUpGesture() {
+ if (mBubblesNavBarGestureTracker != null) {
+ mBubblesNavBarGestureTracker.stop();
+ mBubblesNavBarGestureTracker = null;
+ setOnTouchListener(null);
+ }
+ }
+
/**
* Called when back press occurs while bubbles are expanded.
*/
@@ -2072,11 +2191,12 @@ public class BubbleStackView extends FrameLayout
mExpandedViewContainer.setAnimationMatrix(mExpandedViewContainerMatrix);
if (mExpandedBubble.getExpandedView() != null) {
- mExpandedBubble.getExpandedView().setTaskViewAlpha(0f);
+ mExpandedBubble.getExpandedView().setContentAlpha(0f);
+ mExpandedBubble.getExpandedView().setAlpha(0f);
// We'll be starting the alpha animation after a slight delay, so set this flag early
// here.
- mExpandedBubble.getExpandedView().setAlphaAnimating(true);
+ mExpandedBubble.getExpandedView().setAnimating(true);
}
mDelayedAnimation = () -> {
@@ -2114,10 +2234,10 @@ public class BubbleStackView extends FrameLayout
})
.start();
};
- mDelayedAnimationExecutor.executeDelayed(mDelayedAnimation, startDelay);
+ mMainExecutor.executeDelayed(mDelayedAnimation, startDelay);
}
- private void animateCollapse() {
+ private void animateCollapseWithScale() {
cancelDelayedExpandCollapseSwitchAnimations();
if (mManageEduView != null && mManageEduView.getVisibility() == VISIBLE) {
@@ -2217,6 +2337,68 @@ public class BubbleStackView extends FrameLayout
.start();
}
+ private void animateCollapse() {
+ cancelDelayedExpandCollapseSwitchAnimations();
+
+ if (mManageEduView != null && mManageEduView.getVisibility() == VISIBLE) {
+ mManageEduView.hide();
+ }
+
+ mIsExpanded = false;
+ mIsExpansionAnimating = true;
+
+ showScrim(false);
+
+ mBubbleContainer.cancelAllAnimations();
+
+ // If we were in the middle of swapping, the animating-out surface would have been scaling
+ // to zero - finish it off.
+ PhysicsAnimator.getInstance(mAnimatingOutSurfaceContainer).cancel();
+ mAnimatingOutSurfaceContainer.setScaleX(0f);
+ mAnimatingOutSurfaceContainer.setScaleY(0f);
+
+ // Let the expanded animation controller know that it shouldn't animate child adds/reorders
+ // since we're about to animate collapsed.
+ mExpandedAnimationController.notifyPreparingToCollapse();
+
+ final Runnable collapseBackToStack = () -> mExpandedAnimationController.collapseBackToStack(
+ mStackAnimationController
+ .getStackPositionAlongNearestHorizontalEdge()
+ /* collapseTo */,
+ () -> mBubbleContainer.setActiveController(mStackAnimationController));
+
+ final Runnable after = () -> {
+ final BubbleViewProvider previouslySelected = mExpandedBubble;
+ // TODO(b/231350255): investigate why this call is needed here
+ beforeExpandedViewAnimation();
+ if (mManageEduView != null) {
+ mManageEduView.hide();
+ }
+
+ if (DEBUG_BUBBLE_STACK_VIEW) {
+ Log.d(TAG, "animateCollapse");
+ Log.d(TAG, BubbleDebugConfig.formatBubblesString(getBubblesOnScreen(),
+ mExpandedBubble));
+ }
+ updateOverflowVisibility();
+ updateZOrder();
+ updateBadges(true /* setBadgeForCollapsedStack */);
+ afterExpandedViewAnimation();
+ if (previouslySelected != null) {
+ previouslySelected.setTaskViewVisibility(false);
+ }
+ mExpandedViewAnimationController.reset();
+ };
+ mExpandedViewAnimationController.animateCollapse(collapseBackToStack, after);
+ if (mExpandedBubble != null && mExpandedBubble.getExpandedView() != null) {
+ // When the animation completes, we should no longer be showing the content.
+ // This won't actually update content visibility immediately, if we are currently
+ // animating. But updates the internal state for the content to be hidden after
+ // animation completes.
+ mExpandedBubble.getExpandedView().setContentVisibility(false);
+ }
+ }
+
private void animateSwitchBubbles() {
// If we're no longer expanded, this is meaningless.
if (!mIsExpanded) {
@@ -2278,7 +2460,7 @@ public class BubbleStackView extends FrameLayout
mExpandedViewContainer.setAnimationMatrix(mExpandedViewContainerMatrix);
- mDelayedAnimationExecutor.executeDelayed(() -> {
+ mMainExecutor.executeDelayed(() -> {
if (!mIsExpanded) {
mIsBubbleSwitchAnimating = false;
return;
@@ -2309,7 +2491,7 @@ public class BubbleStackView extends FrameLayout
* animating flags for those animations.
*/
private void cancelDelayedExpandCollapseSwitchAnimations() {
- mDelayedAnimationExecutor.removeCallbacks(mDelayedAnimation);
+ mMainExecutor.removeCallbacks(mDelayedAnimation);
mIsExpansionAnimating = false;
mIsBubbleSwitchAnimating = false;
@@ -2333,9 +2515,18 @@ public class BubbleStackView extends FrameLayout
/**
* Updates the stack based for IME changes. When collapsed it'll move the stack if it
* overlaps where they IME would be. When expanded it'll shift the expanded bubbles
- * if they might overlap with the IME (this only happens for large screens).
+ * if they might overlap with the IME (this only happens for large screens)
+ * and clip the expanded view.
*/
- public void animateForIme(boolean visible) {
+ public void setImeVisible(boolean visible) {
+ if (HOME_GESTURE_ENABLED) {
+ setImeVisibleInternal(visible);
+ } else {
+ setImeVisibleWithoutClipping(visible);
+ }
+ }
+
+ private void setImeVisibleWithoutClipping(boolean visible) {
if ((mIsExpansionAnimating || mIsBubbleSwitchAnimating) && mIsExpanded) {
// This will update the animation so the bubbles move to position for the IME
mExpandedAnimationController.expandFromStack(() -> {
@@ -2386,6 +2577,62 @@ public class BubbleStackView extends FrameLayout
}
}
+ private void setImeVisibleInternal(boolean visible) {
+ if ((mIsExpansionAnimating || mIsBubbleSwitchAnimating) && mIsExpanded) {
+ // This will update the animation so the bubbles move to position for the IME
+ mExpandedAnimationController.expandFromStack(() -> {
+ updatePointerPosition(false /* forIme */);
+ afterExpandedViewAnimation();
+ mExpandedViewAnimationController.animateForImeVisibilityChange(visible);
+ } /* after */);
+ return;
+ }
+
+ if (!mIsExpanded && getBubbleCount() > 0) {
+ final float stackDestinationY =
+ mStackAnimationController.animateForImeVisibility(visible);
+
+ // How far the stack is animating due to IME, we'll just animate the flyout by that
+ // much too.
+ final float stackDy =
+ stackDestinationY - mStackAnimationController.getStackPosition().y;
+
+ // If the flyout is visible, translate it along with the bubble stack.
+ if (mFlyout.getVisibility() == VISIBLE) {
+ PhysicsAnimator.getInstance(mFlyout)
+ .spring(DynamicAnimation.TRANSLATION_Y,
+ mFlyout.getTranslationY() + stackDy,
+ FLYOUT_IME_ANIMATION_SPRING_CONFIG)
+ .start();
+ }
+ }
+
+ if (mIsExpanded) {
+ mExpandedViewAnimationController.animateForImeVisibilityChange(visible);
+ if (mPositioner.showBubblesVertically()
+ && mExpandedBubble != null && mExpandedBubble.getExpandedView() != null) {
+ float selectedY = mPositioner.getExpandedBubbleXY(getState().selectedIndex,
+ getState()).y;
+ float newExpandedViewTop = mPositioner.getExpandedViewY(mExpandedBubble, selectedY);
+ mExpandedBubble.getExpandedView().setImeVisible(visible);
+ if (!mExpandedBubble.getExpandedView().isUsingMaxHeight()) {
+ mExpandedViewContainer.animate().translationY(newExpandedViewTop);
+ }
+ List<Animator> animList = new ArrayList();
+ for (int i = 0; i < mBubbleContainer.getChildCount(); i++) {
+ View child = mBubbleContainer.getChildAt(i);
+ float transY = mPositioner.getExpandedBubbleXY(i, getState()).y;
+ ObjectAnimator anim = ObjectAnimator.ofFloat(child, TRANSLATION_Y, transY);
+ animList.add(anim);
+ }
+ updatePointerPosition(true /* forIme */);
+ AnimatorSet set = new AnimatorSet();
+ set.playTogether(animList);
+ set.start();
+ }
+ }
+ }
+
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() != MotionEvent.ACTION_DOWN && ev.getActionIndex() != mPointerIndexDown) {
@@ -2821,7 +3068,7 @@ public class BubbleStackView extends FrameLayout
&& mExpandedBubble.getExpandedView() != null) {
BubbleExpandedView bev = mExpandedBubble.getExpandedView();
bev.setContentVisibility(false);
- bev.setAlphaAnimating(!mIsExpansionAnimating);
+ bev.setAnimating(!mIsExpansionAnimating);
mExpandedViewContainerMatrix.setScaleX(0f);
mExpandedViewContainerMatrix.setScaleY(0f);
mExpandedViewContainerMatrix.setTranslate(0f, 0f);
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubblesNavBarGestureTracker.java b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubblesNavBarGestureTracker.java
new file mode 100644
index 000000000000..e7beeeb06534
--- /dev/null
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubblesNavBarGestureTracker.java
@@ -0,0 +1,104 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.wm.shell.bubbles;
+
+import static com.android.wm.shell.bubbles.BubbleDebugConfig.TAG_BUBBLES;
+import static com.android.wm.shell.bubbles.BubbleDebugConfig.TAG_WITH_CLASS_NAME;
+
+import android.content.Context;
+import android.hardware.input.InputManager;
+import android.util.Log;
+import android.view.Choreographer;
+import android.view.InputChannel;
+import android.view.InputEventReceiver;
+import android.view.InputMonitor;
+
+import androidx.annotation.Nullable;
+
+import com.android.wm.shell.bubbles.BubblesNavBarMotionEventHandler.MotionEventListener;
+
+/**
+ * Set up tracking bubbles gestures that begin in navigation bar
+ */
+class BubblesNavBarGestureTracker {
+
+ private static final String TAG = TAG_WITH_CLASS_NAME ? "BubblesGestureTracker" : TAG_BUBBLES;
+
+ private static final String GESTURE_MONITOR = "bubbles-gesture";
+ private final Context mContext;
+ private final BubblePositioner mPositioner;
+
+ @Nullable
+ private InputMonitor mInputMonitor;
+ @Nullable
+ private InputEventReceiver mInputEventReceiver;
+
+ BubblesNavBarGestureTracker(Context context, BubblePositioner positioner) {
+ mContext = context;
+ mPositioner = positioner;
+ }
+
+ /**
+ * Start tracking gestures
+ *
+ * @param listener listener that is notified of touch events
+ */
+ void start(MotionEventListener listener) {
+ if (BubbleDebugConfig.DEBUG_BUBBLE_GESTURE) {
+ Log.d(TAG, "start monitoring bubbles swipe up gesture");
+ }
+
+ stopInternal();
+
+ mInputMonitor = InputManager.getInstance().monitorGestureInput(GESTURE_MONITOR,
+ mContext.getDisplayId());
+ InputChannel inputChannel = mInputMonitor.getInputChannel();
+
+ BubblesNavBarMotionEventHandler motionEventHandler =
+ new BubblesNavBarMotionEventHandler(mContext, mPositioner,
+ this::onInterceptTouch, listener);
+ mInputEventReceiver = new BubblesNavBarInputEventReceiver(inputChannel,
+ Choreographer.getInstance(), motionEventHandler);
+ }
+
+ void stop() {
+ if (BubbleDebugConfig.DEBUG_BUBBLE_GESTURE) {
+ Log.d(TAG, "stop monitoring bubbles swipe up gesture");
+ }
+ stopInternal();
+ }
+
+ private void stopInternal() {
+ if (mInputEventReceiver != null) {
+ mInputEventReceiver.dispose();
+ mInputEventReceiver = null;
+ }
+ if (mInputMonitor != null) {
+ mInputMonitor.dispose();
+ mInputMonitor = null;
+ }
+ }
+
+ private void onInterceptTouch() {
+ if (BubbleDebugConfig.DEBUG_BUBBLE_GESTURE) {
+ Log.d(TAG, "intercept touch event");
+ }
+ if (mInputMonitor != null) {
+ mInputMonitor.pilferPointers();
+ }
+ }
+}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubblesNavBarInputEventReceiver.java b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubblesNavBarInputEventReceiver.java
new file mode 100644
index 000000000000..45037b87830f
--- /dev/null
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubblesNavBarInputEventReceiver.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.wm.shell.bubbles;
+
+import android.os.Looper;
+import android.view.BatchedInputEventReceiver;
+import android.view.Choreographer;
+import android.view.InputChannel;
+import android.view.InputEvent;
+import android.view.MotionEvent;
+
+/**
+ * Bubbles {@link BatchedInputEventReceiver} for monitoring touches from navbar gesture area
+ */
+class BubblesNavBarInputEventReceiver extends BatchedInputEventReceiver {
+
+ private final BubblesNavBarMotionEventHandler mMotionEventHandler;
+
+ BubblesNavBarInputEventReceiver(InputChannel inputChannel,
+ Choreographer choreographer, BubblesNavBarMotionEventHandler motionEventHandler) {
+ super(inputChannel, Looper.myLooper(), choreographer);
+ mMotionEventHandler = motionEventHandler;
+ }
+
+ @Override
+ public void onInputEvent(InputEvent event) {
+ boolean handled = false;
+ try {
+ if (!(event instanceof MotionEvent)) {
+ return;
+ }
+ handled = mMotionEventHandler.onMotionEvent((MotionEvent) event);
+ } finally {
+ finishInputEvent(event, handled);
+ }
+ }
+}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubblesNavBarMotionEventHandler.java b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubblesNavBarMotionEventHandler.java
new file mode 100644
index 000000000000..844526ca0f35
--- /dev/null
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubblesNavBarMotionEventHandler.java
@@ -0,0 +1,175 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.wm.shell.bubbles;
+
+import static com.android.wm.shell.bubbles.BubbleDebugConfig.DEBUG_BUBBLE_GESTURE;
+import static com.android.wm.shell.bubbles.BubbleDebugConfig.TAG_BUBBLES;
+import static com.android.wm.shell.bubbles.BubbleDebugConfig.TAG_WITH_CLASS_NAME;
+
+import android.content.Context;
+import android.graphics.PointF;
+import android.util.Log;
+import android.view.MotionEvent;
+import android.view.VelocityTracker;
+import android.view.ViewConfiguration;
+
+import androidx.annotation.Nullable;
+
+/**
+ * Handles {@link MotionEvent}s for bubbles that begin in the nav bar area
+ */
+class BubblesNavBarMotionEventHandler {
+ private static final String TAG =
+ TAG_WITH_CLASS_NAME ? "BubblesNavBarMotionEventHandler" : TAG_BUBBLES;
+ private static final int VELOCITY_UNITS = 1000;
+
+ private final Runnable mOnInterceptTouch;
+ private final MotionEventListener mMotionEventListener;
+ private final int mTouchSlop;
+ private final BubblePositioner mPositioner;
+ private final PointF mTouchDown = new PointF();
+ private boolean mTrackingTouches;
+ private boolean mInterceptingTouches;
+ @Nullable
+ private VelocityTracker mVelocityTracker;
+
+ BubblesNavBarMotionEventHandler(Context context, BubblePositioner positioner,
+ Runnable onInterceptTouch, MotionEventListener motionEventListener) {
+ mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
+ mPositioner = positioner;
+ mOnInterceptTouch = onInterceptTouch;
+ mMotionEventListener = motionEventListener;
+ }
+
+ /**
+ * Handle {@link MotionEvent} and forward it to {@code motionEventListener} defined in
+ * constructor
+ *
+ * @return {@code true} if this {@link MotionEvent} is handled (it started in the gesture area)
+ */
+ public boolean onMotionEvent(MotionEvent motionEvent) {
+ float dx = motionEvent.getX() - mTouchDown.x;
+ float dy = motionEvent.getY() - mTouchDown.y;
+
+ switch (motionEvent.getAction()) {
+ case MotionEvent.ACTION_DOWN:
+ if (isInGestureRegion(motionEvent)) {
+ mTouchDown.set(motionEvent.getX(), motionEvent.getY());
+ mMotionEventListener.onDown(motionEvent.getX(), motionEvent.getY());
+ mTrackingTouches = true;
+ return true;
+ }
+ break;
+ case MotionEvent.ACTION_MOVE:
+ if (mTrackingTouches) {
+ if (!mInterceptingTouches && Math.hypot(dx, dy) > mTouchSlop) {
+ mInterceptingTouches = true;
+ mOnInterceptTouch.run();
+ }
+ if (mInterceptingTouches) {
+ getVelocityTracker().addMovement(motionEvent);
+ mMotionEventListener.onMove(dx, dy);
+ }
+ return true;
+ }
+ break;
+ case MotionEvent.ACTION_CANCEL:
+ if (mTrackingTouches) {
+ mMotionEventListener.onCancel();
+ finishTracking();
+ return true;
+ }
+ break;
+ case MotionEvent.ACTION_UP:
+ if (mTrackingTouches) {
+ if (mInterceptingTouches) {
+ getVelocityTracker().computeCurrentVelocity(VELOCITY_UNITS);
+ mMotionEventListener.onUp(getVelocityTracker().getXVelocity(),
+ getVelocityTracker().getYVelocity());
+ }
+ finishTracking();
+ return true;
+ }
+ break;
+ }
+ return false;
+ }
+
+ private boolean isInGestureRegion(MotionEvent ev) {
+ // Only handles touch events beginning in navigation bar system gesture zone
+ if (mPositioner.getNavBarGestureZone().contains((int) ev.getX(), (int) ev.getY())) {
+ if (DEBUG_BUBBLE_GESTURE) {
+ Log.d(TAG, "handling touch y=" + ev.getY()
+ + " navBarGestureZone=" + mPositioner.getNavBarGestureZone());
+ }
+ return true;
+ }
+ return false;
+ }
+
+ private VelocityTracker getVelocityTracker() {
+ if (mVelocityTracker == null) {
+ mVelocityTracker = VelocityTracker.obtain();
+ }
+ return mVelocityTracker;
+ }
+
+ private void finishTracking() {
+ mTouchDown.set(0, 0);
+ mTrackingTouches = false;
+ mInterceptingTouches = false;
+ if (mVelocityTracker != null) {
+ mVelocityTracker.recycle();
+ mVelocityTracker = null;
+ }
+ }
+
+ /**
+ * Callback for receiving {@link MotionEvent} updates
+ */
+ interface MotionEventListener {
+ /**
+ * Touch down action.
+ *
+ * @param x x coordinate
+ * @param y y coordinate
+ */
+ void onDown(float x, float y);
+
+ /**
+ * Move action.
+ * Reports distance from point reported in {@link #onDown(float, float)}
+ *
+ * @param dx distance moved on x-axis from starting point, in pixels
+ * @param dy distance moved on y-axis from starting point, in pixels
+ */
+ void onMove(float dx, float dy);
+
+ /**
+ * Touch up action.
+ *
+ * @param velX velocity of the move action on x axis
+ * @param velY velocity of the move actin on y axis
+ */
+ void onUp(float velX, float velY);
+
+ /**
+ * Motion action was cancelled.
+ */
+ void onCancel();
+ }
+}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/RelativeTouchListener.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/RelativeTouchListener.kt
index cf0cefec401a..ea9d065d5f53 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/RelativeTouchListener.kt
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/RelativeTouchListener.kt
@@ -17,8 +17,6 @@
package com.android.wm.shell.bubbles
import android.graphics.PointF
-import android.os.Handler
-import android.os.Looper
import android.view.MotionEvent
import android.view.VelocityTracker
import android.view.View
@@ -146,6 +144,12 @@ abstract class RelativeTouchListener : View.OnTouchListener {
velocityTracker.clear()
movedEnough = false
}
+
+ MotionEvent.ACTION_CANCEL -> {
+ v.handler.removeCallbacksAndMessages(null)
+ velocityTracker.clear()
+ movedEnough = false
+ }
}
return true
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/ExpandedAnimationController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/ExpandedAnimationController.java
index 573f42468512..c24efb9f5534 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/ExpandedAnimationController.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/ExpandedAnimationController.java
@@ -17,11 +17,13 @@
package com.android.wm.shell.bubbles.animation;
import static com.android.wm.shell.bubbles.BubblePositioner.NUM_VISIBLE_WHEN_RESTING;
+import static com.android.wm.shell.bubbles.BubbleStackView.HOME_GESTURE_ENABLED;
import android.content.res.Resources;
import android.graphics.Path;
import android.graphics.PointF;
import android.view.View;
+import android.view.animation.Interpolator;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
@@ -61,7 +63,10 @@ public class ExpandedAnimationController
private static final float DAMPING_RATIO_MEDIUM_LOW_BOUNCY = 0.65f;
/** Stiffness for the expand/collapse path-following animation. */
- private static final int EXPAND_COLLAPSE_ANIM_STIFFNESS = 1000;
+ private static final int EXPAND_COLLAPSE_ANIM_STIFFNESS = 400;
+
+ /** Stiffness for the expand/collapse animation when home gesture handling is off */
+ private static final int EXPAND_COLLAPSE_ANIM_STIFFNESS_WITHOUT_HOME_GESTURE = 1000;
/**
* Velocity required to dismiss an individual bubble without dragging it into the dismiss
@@ -73,6 +78,11 @@ public class ExpandedAnimationController
new PhysicsAnimator.SpringConfig(
EXPAND_COLLAPSE_ANIM_STIFFNESS, SpringForce.DAMPING_RATIO_NO_BOUNCY);
+ private final PhysicsAnimator.SpringConfig mAnimateOutSpringConfigWithoutHomeGesture =
+ new PhysicsAnimator.SpringConfig(
+ EXPAND_COLLAPSE_ANIM_STIFFNESS_WITHOUT_HOME_GESTURE,
+ SpringForce.DAMPING_RATIO_NO_BOUNCY);
+
/** Horizontal offset between bubbles, which we need to know to re-stack them. */
private float mStackOffsetPx;
/** Size of each bubble. */
@@ -278,11 +288,20 @@ public class ExpandedAnimationController
(firstBubbleLeads && index == 0)
|| (!firstBubbleLeads && index == mLayout.getChildCount() - 1);
+ Interpolator interpolator;
+ if (HOME_GESTURE_ENABLED) {
+ // When home gesture is enabled, we use a different animation timing for collapse
+ interpolator = expanding
+ ? Interpolators.EMPHASIZED_ACCELERATE : Interpolators.EMPHASIZED_DECELERATE;
+ } else {
+ interpolator = Interpolators.LINEAR;
+ }
+
animation
.followAnimatedTargetAlongPath(
path,
EXPAND_COLLAPSE_TARGET_ANIM_DURATION /* targetAnimDuration */,
- Interpolators.LINEAR /* targetAnimInterpolator */,
+ interpolator /* targetAnimInterpolator */,
isLeadBubble ? mLeadBubbleEndAction : null /* endAction */,
() -> mLeadBubbleEndAction = null /* endAction */)
.withStartDelay(startDelay)
@@ -525,10 +544,16 @@ public class ExpandedAnimationController
finishRemoval.run();
mOnBubbleAnimatedOutAction.run();
} else {
+ PhysicsAnimator.SpringConfig springConfig;
+ if (HOME_GESTURE_ENABLED) {
+ springConfig = mAnimateOutSpringConfig;
+ } else {
+ springConfig = mAnimateOutSpringConfigWithoutHomeGesture;
+ }
PhysicsAnimator.getInstance(child)
.spring(DynamicAnimation.ALPHA, 0f)
- .spring(DynamicAnimation.SCALE_X, 0f, mAnimateOutSpringConfig)
- .spring(DynamicAnimation.SCALE_Y, 0f, mAnimateOutSpringConfig)
+ .spring(DynamicAnimation.SCALE_X, 0f, springConfig)
+ .spring(DynamicAnimation.SCALE_Y, 0f, springConfig)
.withEndActions(finishRemoval, mOnBubbleAnimatedOutAction)
.start();
}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/ExpandedViewAnimationController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/ExpandedViewAnimationController.java
new file mode 100644
index 000000000000..8a33780bc8d5
--- /dev/null
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/ExpandedViewAnimationController.java
@@ -0,0 +1,75 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.wm.shell.bubbles.animation;
+
+import com.android.wm.shell.bubbles.BubbleExpandedView;
+
+/**
+ * Animation controller for bubble expanded view collapsing
+ */
+public interface ExpandedViewAnimationController {
+ /**
+ * Set expanded view that this controller is working with.
+ */
+ void setExpandedView(BubbleExpandedView expandedView);
+
+ /**
+ * Set current collapse value, in pixels.
+ *
+ * @param distance pixels that user dragged the view by
+ */
+ void updateDrag(float distance);
+
+ /**
+ * Set current swipe velocity.
+ * Velocity is directional:
+ * <ul>
+ * <li>velocity < 0 means swipe direction is up</li>
+ * <li>velocity > 0 means swipe direction is down</li>
+ * </ul>
+ */
+ void setSwipeVelocity(float velocity);
+
+ /**
+ * Check if view is dragged past collapse threshold or swipe up velocity exceeds min velocity
+ * required to collapse the view
+ */
+ boolean shouldCollapse();
+
+ /**
+ * Animate view to collapsed state
+ *
+ * @param startStackCollapse runnable that is triggered when bubbles can start moving back to
+ * their collapsed location
+ * @param after runnable to run after animation is complete
+ */
+ void animateCollapse(Runnable startStackCollapse, Runnable after);
+
+ /**
+ * Animate the view back to fully expanded state.
+ */
+ void animateBackToExpanded();
+
+ /**
+ * Animate view for IME visibility change
+ */
+ void animateForImeVisibilityChange(boolean visible);
+
+ /**
+ * Reset the view to fully expanded state
+ */
+ void reset();
+}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/ExpandedViewAnimationControllerImpl.java b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/ExpandedViewAnimationControllerImpl.java
new file mode 100644
index 000000000000..ca54232c95b5
--- /dev/null
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/ExpandedViewAnimationControllerImpl.java
@@ -0,0 +1,432 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.wm.shell.bubbles.animation;
+
+import static android.view.View.ALPHA;
+
+import static com.android.wm.shell.bubbles.BubbleDebugConfig.DEBUG_COLLAPSE_ANIMATOR;
+import static com.android.wm.shell.bubbles.BubbleDebugConfig.DEBUG_EXPANDED_VIEW_DRAGGING;
+import static com.android.wm.shell.bubbles.BubbleDebugConfig.TAG_BUBBLES;
+import static com.android.wm.shell.bubbles.BubbleDebugConfig.TAG_WITH_CLASS_NAME;
+import static com.android.wm.shell.bubbles.BubbleExpandedView.BOTTOM_CLIP_PROPERTY;
+import static com.android.wm.shell.bubbles.BubbleExpandedView.CONTENT_ALPHA;
+import static com.android.wm.shell.bubbles.BubbleExpandedView.MANAGE_BUTTON_ALPHA;
+
+import android.animation.Animator;
+import android.animation.AnimatorListenerAdapter;
+import android.animation.AnimatorSet;
+import android.animation.ObjectAnimator;
+import android.animation.ValueAnimator;
+import android.annotation.SuppressLint;
+import android.content.Context;
+import android.util.Log;
+import android.view.HapticFeedbackConstants;
+import android.view.ViewConfiguration;
+
+import androidx.annotation.Nullable;
+import androidx.dynamicanimation.animation.DynamicAnimation;
+import androidx.dynamicanimation.animation.FloatPropertyCompat;
+import androidx.dynamicanimation.animation.SpringAnimation;
+import androidx.dynamicanimation.animation.SpringForce;
+
+import com.android.wm.shell.animation.FlingAnimationUtils;
+import com.android.wm.shell.animation.Interpolators;
+import com.android.wm.shell.bubbles.BubbleExpandedView;
+import com.android.wm.shell.bubbles.BubblePositioner;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Implementation of {@link ExpandedViewAnimationController} that uses a collapse animation to
+ * hide the {@link BubbleExpandedView}
+ */
+public class ExpandedViewAnimationControllerImpl implements ExpandedViewAnimationController {
+
+ private static final String TAG = TAG_WITH_CLASS_NAME ? "ExpandedViewAnimCtrl" : TAG_BUBBLES;
+
+ private static final float COLLAPSE_THRESHOLD = 0.02f;
+
+ private static final int COLLAPSE_DURATION_MS = 250;
+
+ private static final int MANAGE_BUTTON_ANIM_DURATION_MS = 78;
+
+ private static final int CONTENT_OPACITY_ANIM_DELAY_MS = 93;
+ private static final int CONTENT_OPACITY_ANIM_DURATION_MS = 78;
+
+ private static final int BACKGROUND_OPACITY_ANIM_DELAY_MS = 172;
+ private static final int BACKGROUND_OPACITY_ANIM_DURATION_MS = 78;
+
+ /** Animation fraction threshold for content alpha animation when stack collapse should begin */
+ private static final float STACK_COLLAPSE_THRESHOLD = 0.5f;
+
+ private static final FloatPropertyCompat<ExpandedViewAnimationControllerImpl>
+ COLLAPSE_HEIGHT_PROPERTY =
+ new FloatPropertyCompat<ExpandedViewAnimationControllerImpl>("CollapseSpring") {
+ @Override
+ public float getValue(ExpandedViewAnimationControllerImpl controller) {
+ return controller.getCollapsedAmount();
+ }
+
+ @Override
+ public void setValue(ExpandedViewAnimationControllerImpl controller,
+ float value) {
+ controller.setCollapsedAmount(value);
+ }
+ };
+
+ private final int mMinFlingVelocity;
+ private float mSwipeUpVelocity;
+ private float mSwipeDownVelocity;
+ private final BubblePositioner mPositioner;
+ private final FlingAnimationUtils mFlingAnimationUtils;
+ private int mDraggedAmount;
+ private float mCollapsedAmount;
+ @Nullable
+ private BubbleExpandedView mExpandedView;
+ @Nullable
+ private AnimatorSet mCollapseAnimation;
+ private boolean mNotifiedAboutThreshold;
+ private SpringAnimation mBackToExpandedAnimation;
+ @Nullable
+ private ObjectAnimator mBottomClipAnim;
+
+ public ExpandedViewAnimationControllerImpl(Context context, BubblePositioner positioner) {
+ mFlingAnimationUtils = new FlingAnimationUtils(context.getResources().getDisplayMetrics(),
+ COLLAPSE_DURATION_MS / 1000f);
+ mMinFlingVelocity = ViewConfiguration.get(context).getScaledMinimumFlingVelocity();
+ mPositioner = positioner;
+ }
+
+ private static void adjustAnimatorSetDuration(AnimatorSet animatorSet,
+ float durationAdjustment) {
+ for (Animator animator : animatorSet.getChildAnimations()) {
+ animator.setStartDelay((long) (animator.getStartDelay() * durationAdjustment));
+ animator.setDuration((long) (animator.getDuration() * durationAdjustment));
+ }
+ }
+
+ @Override
+ public void setExpandedView(BubbleExpandedView expandedView) {
+ if (mExpandedView != null) {
+ if (DEBUG_COLLAPSE_ANIMATOR) {
+ Log.d(TAG, "updating expandedView, resetting previous");
+ }
+ if (mCollapseAnimation != null) {
+ mCollapseAnimation.cancel();
+ }
+ if (mBackToExpandedAnimation != null) {
+ mBackToExpandedAnimation.cancel();
+ }
+ reset();
+ }
+ mExpandedView = expandedView;
+ }
+
+ @Override
+ public void updateDrag(float distance) {
+ if (mExpandedView != null) {
+ mDraggedAmount = OverScroll.dampedScroll(distance, mExpandedView.getContentHeight());
+
+ if (DEBUG_COLLAPSE_ANIMATOR && DEBUG_EXPANDED_VIEW_DRAGGING) {
+ Log.d(TAG, "updateDrag: distance=" + distance + " dragged=" + mDraggedAmount);
+ }
+
+ setCollapsedAmount(mDraggedAmount);
+
+ if (!mNotifiedAboutThreshold && isPastCollapseThreshold()) {
+ mNotifiedAboutThreshold = true;
+ if (DEBUG_COLLAPSE_ANIMATOR) {
+ Log.d(TAG, "notifying over collapse threshold");
+ }
+ vibrateIfEnabled();
+ }
+ }
+ }
+
+ @Override
+ public void setSwipeVelocity(float velocity) {
+ if (velocity < 0) {
+ mSwipeUpVelocity = Math.abs(velocity);
+ mSwipeDownVelocity = 0;
+ } else {
+ mSwipeUpVelocity = 0;
+ mSwipeDownVelocity = velocity;
+ }
+ }
+
+ @Override
+ public boolean shouldCollapse() {
+ if (mSwipeDownVelocity > mMinFlingVelocity) {
+ // Swipe velocity is positive and over fling velocity.
+ // This is a swipe down, always reset to expanded state, regardless of dragged amount.
+ if (DEBUG_COLLAPSE_ANIMATOR) {
+ Log.d(TAG,
+ "not collapsing expanded view, swipe down velocity: " + mSwipeDownVelocity
+ + " minV: " + mMinFlingVelocity);
+ }
+ return false;
+ }
+
+ if (mSwipeUpVelocity > mMinFlingVelocity) {
+ // Swiping up and over fling velocity, collapse the view.
+ if (DEBUG_COLLAPSE_ANIMATOR) {
+ Log.d(TAG,
+ "collapse expanded view, swipe up velocity: " + mSwipeUpVelocity + " minV: "
+ + mMinFlingVelocity);
+ }
+ return true;
+ }
+
+ if (isPastCollapseThreshold()) {
+ if (DEBUG_COLLAPSE_ANIMATOR) {
+ Log.d(TAG, "collapse expanded view, past threshold, dragged: " + mDraggedAmount);
+ }
+ return true;
+ }
+
+ if (DEBUG_COLLAPSE_ANIMATOR) {
+ Log.d(TAG, "not collapsing expanded view");
+ }
+
+ return false;
+ }
+
+ @Override
+ public void animateCollapse(Runnable startStackCollapse, Runnable after) {
+ if (DEBUG_COLLAPSE_ANIMATOR) {
+ Log.d(TAG,
+ "expandedView animate collapse swipeVel=" + mSwipeUpVelocity + " minFlingVel="
+ + mMinFlingVelocity);
+ }
+ if (mExpandedView != null) {
+ // Mark it as animating immediately to avoid updates to the view before animation starts
+ mExpandedView.setAnimating(true);
+
+ if (mCollapseAnimation != null) {
+ mCollapseAnimation.cancel();
+ }
+ mCollapseAnimation = createCollapseAnimation(mExpandedView, startStackCollapse, after);
+
+ if (mSwipeUpVelocity >= mMinFlingVelocity) {
+ int contentHeight = mExpandedView.getContentHeight();
+
+ // Use a temp animator to get adjusted duration value for swipe.
+ // This new value will be used to adjust animation times proportionally in the
+ // animator set. If we adjust animator set duration directly, all child animations
+ // will get the same animation time.
+ ValueAnimator tempAnimator = new ValueAnimator();
+ mFlingAnimationUtils.applyDismissing(tempAnimator, mCollapsedAmount, contentHeight,
+ mSwipeUpVelocity, (contentHeight - mCollapsedAmount));
+
+ float durationAdjustment =
+ (float) tempAnimator.getDuration() / COLLAPSE_DURATION_MS;
+
+ adjustAnimatorSetDuration(mCollapseAnimation, durationAdjustment);
+ mCollapseAnimation.setInterpolator(tempAnimator.getInterpolator());
+ }
+ mCollapseAnimation.start();
+ }
+ }
+
+ @Override
+ public void animateBackToExpanded() {
+ if (DEBUG_COLLAPSE_ANIMATOR) {
+ Log.d(TAG, "expandedView animate back to expanded");
+ }
+ BubbleExpandedView expandedView = mExpandedView;
+ if (expandedView == null) {
+ return;
+ }
+
+ expandedView.setAnimating(true);
+
+ mBackToExpandedAnimation = new SpringAnimation(this, COLLAPSE_HEIGHT_PROPERTY);
+ mBackToExpandedAnimation.setSpring(new SpringForce()
+ .setStiffness(SpringForce.STIFFNESS_LOW)
+ .setDampingRatio(SpringForce.DAMPING_RATIO_LOW_BOUNCY)
+ );
+ mBackToExpandedAnimation.addEndListener(new OneTimeEndListener() {
+ @Override
+ public void onAnimationEnd(DynamicAnimation animation, boolean canceled, float value,
+ float velocity) {
+ super.onAnimationEnd(animation, canceled, value, velocity);
+ mNotifiedAboutThreshold = false;
+ mBackToExpandedAnimation = null;
+ expandedView.setAnimating(false);
+ }
+ });
+ mBackToExpandedAnimation.setStartValue(mCollapsedAmount);
+ mBackToExpandedAnimation.animateToFinalPosition(0);
+ }
+
+ @Override
+ public void animateForImeVisibilityChange(boolean visible) {
+ if (mExpandedView != null) {
+ if (mBottomClipAnim != null) {
+ mBottomClipAnim.cancel();
+ }
+ int clip = 0;
+ if (visible) {
+ // Clip the expanded view at the top of the IME view
+ clip = mExpandedView.getContentBottomOnScreen() - mPositioner.getImeTop();
+ // Don't allow negative clip value
+ clip = Math.max(clip, 0);
+ }
+ mBottomClipAnim = ObjectAnimator.ofInt(mExpandedView, BOTTOM_CLIP_PROPERTY, clip);
+ mBottomClipAnim.addListener(new AnimatorListenerAdapter() {
+ @Override
+ public void onAnimationEnd(Animator animation) {
+ mBottomClipAnim = null;
+ }
+ });
+ mBottomClipAnim.start();
+ }
+ }
+
+ @Override
+ public void reset() {
+ if (DEBUG_COLLAPSE_ANIMATOR) {
+ Log.d(TAG, "reset expandedView collapsed state");
+ }
+ if (mExpandedView == null) {
+ return;
+ }
+ mExpandedView.setAnimating(false);
+
+ if (mCollapseAnimation != null) {
+ mCollapseAnimation.cancel();
+ }
+ if (mBackToExpandedAnimation != null) {
+ mBackToExpandedAnimation.cancel();
+ }
+ mExpandedView.setContentAlpha(1);
+ mExpandedView.setAlpha(1);
+ mExpandedView.setManageButtonAlpha(1);
+ setCollapsedAmount(0);
+ mExpandedView.setBottomClip(0);
+ mExpandedView.movePointerBy(0, 0);
+ mCollapsedAmount = 0;
+ mDraggedAmount = 0;
+ mSwipeUpVelocity = 0;
+ mSwipeDownVelocity = 0;
+ mNotifiedAboutThreshold = false;
+ }
+
+ private float getCollapsedAmount() {
+ return mCollapsedAmount;
+ }
+
+ private void setCollapsedAmount(float collapsed) {
+ if (mCollapsedAmount != collapsed) {
+ float previous = mCollapsedAmount;
+ mCollapsedAmount = collapsed;
+
+ if (mExpandedView != null) {
+ if (previous == 0) {
+ // View was not collapsed before. Apply z order change
+ mExpandedView.setSurfaceZOrderedOnTop(true);
+ mExpandedView.setAnimating(true);
+ }
+
+ mExpandedView.setTopClip((int) mCollapsedAmount);
+ // Move up with translationY. Use negative collapsed value
+ mExpandedView.setContentTranslationY(-mCollapsedAmount);
+ mExpandedView.setManageButtonTranslationY(-mCollapsedAmount);
+
+ if (mCollapsedAmount == 0) {
+ // View is no longer collapsed. Revert z order change
+ mExpandedView.setSurfaceZOrderedOnTop(false);
+ mExpandedView.setAnimating(false);
+ }
+ }
+ }
+ }
+
+ private boolean isPastCollapseThreshold() {
+ if (mExpandedView != null) {
+ return mDraggedAmount > mExpandedView.getContentHeight() * COLLAPSE_THRESHOLD;
+ }
+ return false;
+ }
+
+ private AnimatorSet createCollapseAnimation(BubbleExpandedView expandedView,
+ Runnable startStackCollapse, Runnable after) {
+ List<Animator> animatorList = new ArrayList<>();
+ animatorList.add(createHeightAnimation(expandedView));
+ animatorList.add(createManageButtonAnimation());
+ ObjectAnimator contentAlphaAnimation = createContentAlphaAnimation();
+ final boolean[] notified = {false};
+ contentAlphaAnimation.addUpdateListener(animation -> {
+ if (!notified[0] && animation.getAnimatedFraction() > STACK_COLLAPSE_THRESHOLD) {
+ notified[0] = true;
+ // Notify bubbles that they can start moving back to the collapsed position
+ startStackCollapse.run();
+ }
+ });
+ animatorList.add(contentAlphaAnimation);
+ animatorList.add(createBackgroundAlphaAnimation());
+
+ AnimatorSet animatorSet = new AnimatorSet();
+ animatorSet.addListener(new AnimatorListenerAdapter() {
+ @Override
+ public void onAnimationEnd(Animator animation) {
+ after.run();
+ }
+ });
+ animatorSet.playTogether(animatorList);
+ return animatorSet;
+ }
+
+ private ValueAnimator createHeightAnimation(BubbleExpandedView expandedView) {
+ ValueAnimator animator = ValueAnimator.ofInt((int) mCollapsedAmount,
+ expandedView.getContentHeight());
+ animator.setInterpolator(Interpolators.EMPHASIZED_ACCELERATE);
+ animator.setDuration(COLLAPSE_DURATION_MS);
+ animator.addUpdateListener(anim -> setCollapsedAmount((int) anim.getAnimatedValue()));
+ return animator;
+ }
+
+ private ObjectAnimator createManageButtonAnimation() {
+ ObjectAnimator animator = ObjectAnimator.ofFloat(mExpandedView, MANAGE_BUTTON_ALPHA, 0f);
+ animator.setDuration(MANAGE_BUTTON_ANIM_DURATION_MS);
+ animator.setInterpolator(Interpolators.LINEAR);
+ return animator;
+ }
+
+ private ObjectAnimator createContentAlphaAnimation() {
+ ObjectAnimator animator = ObjectAnimator.ofFloat(mExpandedView, CONTENT_ALPHA, 0f);
+ animator.setDuration(CONTENT_OPACITY_ANIM_DURATION_MS);
+ animator.setInterpolator(Interpolators.LINEAR);
+ animator.setStartDelay(CONTENT_OPACITY_ANIM_DELAY_MS);
+ return animator;
+ }
+
+ private ObjectAnimator createBackgroundAlphaAnimation() {
+ ObjectAnimator animator = ObjectAnimator.ofFloat(mExpandedView, ALPHA, 0f);
+ animator.setDuration(BACKGROUND_OPACITY_ANIM_DURATION_MS);
+ animator.setInterpolator(Interpolators.LINEAR);
+ animator.setStartDelay(BACKGROUND_OPACITY_ANIM_DELAY_MS);
+ return animator;
+ }
+
+ @SuppressLint("MissingPermission")
+ private void vibrateIfEnabled() {
+ if (mExpandedView != null) {
+ mExpandedView.performHapticFeedback(HapticFeedbackConstants.DRAG_CROSSING);
+ }
+ }
+}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/ExpandedViewAnimationControllerStub.java b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/ExpandedViewAnimationControllerStub.java
new file mode 100644
index 000000000000..bb8a3aaaf551
--- /dev/null
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/ExpandedViewAnimationControllerStub.java
@@ -0,0 +1,57 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.wm.shell.bubbles.animation;
+
+import com.android.wm.shell.bubbles.BubbleExpandedView;
+
+/**
+ * Stub implementation {@link ExpandedViewAnimationController} that does not animate the
+ * {@link BubbleExpandedView}
+ */
+public class ExpandedViewAnimationControllerStub implements ExpandedViewAnimationController {
+ @Override
+ public void setExpandedView(BubbleExpandedView expandedView) {
+ }
+
+ @Override
+ public void updateDrag(float distance) {
+ }
+
+ @Override
+ public void setSwipeVelocity(float velocity) {
+ }
+
+ @Override
+ public boolean shouldCollapse() {
+ return false;
+ }
+
+ @Override
+ public void animateCollapse(Runnable startStackCollapse, Runnable after) {
+ }
+
+ @Override
+ public void animateBackToExpanded() {
+ }
+
+ @Override
+ public void animateForImeVisibilityChange(boolean visible) {
+ }
+
+ @Override
+ public void reset() {
+ }
+}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/OverScroll.java b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/OverScroll.java
new file mode 100644
index 000000000000..d4e76ed0282e
--- /dev/null
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/OverScroll.java
@@ -0,0 +1,57 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.wm.shell.bubbles.animation;
+
+/**
+ * Utility methods for overscroll damping and related effect.
+ *
+ * Copied from packages/apps/Launcher3/src/com/android/launcher3/touch/OverScroll.java
+ */
+public class OverScroll {
+
+ private static final float OVERSCROLL_DAMP_FACTOR = 0.07f;
+
+ /**
+ * This curve determines how the effect of scrolling over the limits of the page diminishes
+ * as the user pulls further and further from the bounds
+ *
+ * @param f The percentage of how much the user has overscrolled.
+ * @return A transformed percentage based on the influence curve.
+ */
+ private static float overScrollInfluenceCurve(float f) {
+ f -= 1.0f;
+ return f * f * f + 1.0f;
+ }
+
+ /**
+ * @param amount The original amount overscrolled.
+ * @param max The maximum amount that the View can overscroll.
+ * @return The dampened overscroll amount.
+ */
+ public static int dampedScroll(float amount, int max) {
+ if (Float.compare(amount, 0) == 0) return 0;
+
+ float f = amount / max;
+ f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
+
+ // Clamp this factor, f, to -1 < f < 1
+ if (Math.abs(f) >= 1) {
+ f /= Math.abs(f);
+ }
+
+ return Math.round(OVERSCROLL_DAMP_FACTOR * f * max);
+ }
+}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/common/DisplayChangeController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/common/DisplayChangeController.java
index c32733d4f73c..28c7367662a2 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/common/DisplayChangeController.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/common/DisplayChangeController.java
@@ -16,11 +16,13 @@
package com.android.wm.shell.common;
+import android.annotation.Nullable;
import android.os.RemoteException;
import android.util.Slog;
-import android.view.IDisplayWindowRotationCallback;
-import android.view.IDisplayWindowRotationController;
+import android.view.IDisplayChangeWindowCallback;
+import android.view.IDisplayChangeWindowController;
import android.view.IWindowManager;
+import android.window.DisplayAreaInfo;
import android.window.WindowContainerTransaction;
import androidx.annotation.BinderThread;
@@ -40,17 +42,17 @@ public class DisplayChangeController {
private final ShellExecutor mMainExecutor;
private final IWindowManager mWmService;
- private final IDisplayWindowRotationController mControllerImpl;
+ private final IDisplayChangeWindowController mControllerImpl;
- private final CopyOnWriteArrayList<OnDisplayChangingListener> mRotationListener =
+ private final CopyOnWriteArrayList<OnDisplayChangingListener> mDisplayChangeListener =
new CopyOnWriteArrayList<>();
public DisplayChangeController(IWindowManager wmService, ShellExecutor mainExecutor) {
mMainExecutor = mainExecutor;
mWmService = wmService;
- mControllerImpl = new DisplayWindowRotationControllerImpl();
+ mControllerImpl = new DisplayChangeWindowControllerImpl();
try {
- mWmService.setDisplayWindowRotationController(mControllerImpl);
+ mWmService.setDisplayChangeWindowController(mControllerImpl);
} catch (RemoteException e) {
throw new RuntimeException("Unable to register rotation controller");
}
@@ -59,63 +61,64 @@ public class DisplayChangeController {
/**
* Adds a display rotation controller.
*/
- public void addRotationListener(OnDisplayChangingListener listener) {
- mRotationListener.add(listener);
+ public void addDisplayChangeListener(OnDisplayChangingListener listener) {
+ mDisplayChangeListener.add(listener);
}
/**
* Removes a display rotation controller.
*/
- public void removeRotationListener(OnDisplayChangingListener listener) {
- mRotationListener.remove(listener);
+ public void removeDisplayChangeListener(OnDisplayChangingListener listener) {
+ mDisplayChangeListener.remove(listener);
}
- /** Query all listeners for changes that should happen on rotation. */
- public void dispatchOnRotateDisplay(WindowContainerTransaction outWct, int displayId,
- final int fromRotation, final int toRotation) {
- for (OnDisplayChangingListener c : mRotationListener) {
- c.onRotateDisplay(displayId, fromRotation, toRotation, outWct);
+ /** Query all listeners for changes that should happen on display change. */
+ public void dispatchOnDisplayChange(WindowContainerTransaction outWct, int displayId,
+ int fromRotation, int toRotation, DisplayAreaInfo newDisplayAreaInfo) {
+ for (OnDisplayChangingListener c : mDisplayChangeListener) {
+ c.onDisplayChange(displayId, fromRotation, toRotation, newDisplayAreaInfo, outWct);
}
}
- private void onRotateDisplay(int displayId, final int fromRotation, final int toRotation,
- IDisplayWindowRotationCallback callback) {
+ private void onDisplayChange(int displayId, int fromRotation, int toRotation,
+ DisplayAreaInfo newDisplayAreaInfo, IDisplayChangeWindowCallback callback) {
WindowContainerTransaction t = new WindowContainerTransaction();
- dispatchOnRotateDisplay(t, displayId, fromRotation, toRotation);
+ dispatchOnDisplayChange(t, displayId, fromRotation, toRotation, newDisplayAreaInfo);
try {
- callback.continueRotateDisplay(toRotation, t);
+ callback.continueDisplayChange(t);
} catch (RemoteException e) {
- Slog.e(TAG, "Failed to continue rotation", e);
+ Slog.e(TAG, "Failed to continue handling display change", e);
}
}
@BinderThread
- private class DisplayWindowRotationControllerImpl
- extends IDisplayWindowRotationController.Stub {
+ private class DisplayChangeWindowControllerImpl
+ extends IDisplayChangeWindowController.Stub {
@Override
- public void onRotateDisplay(int displayId, final int fromRotation,
- final int toRotation, IDisplayWindowRotationCallback callback) {
- mMainExecutor.execute(() -> {
- DisplayChangeController.this.onRotateDisplay(displayId, fromRotation, toRotation,
- callback);
- });
+ public void onDisplayChange(int displayId, int fromRotation, int toRotation,
+ DisplayAreaInfo newDisplayAreaInfo, IDisplayChangeWindowCallback callback) {
+ mMainExecutor.execute(() -> DisplayChangeController.this
+ .onDisplayChange(displayId, fromRotation, toRotation,
+ newDisplayAreaInfo, callback));
}
}
/**
* Give a listener a chance to queue up configuration changes to execute as part of a
- * display rotation. The contents of {@link #onRotateDisplay} must run synchronously.
+ * display rotation. The contents of {@link #onDisplayChange} must run synchronously.
*/
@ShellMainThread
public interface OnDisplayChangingListener {
/**
- * Called before the display is rotated. Contents of this method must run synchronously.
- * @param displayId Id of display that is rotating.
- * @param fromRotation starting rotation of the display.
- * @param toRotation target rotation of the display (after rotating).
+ * Called before the display size has changed.
+ * Contents of this method must run synchronously.
+ * @param displayId display id of the display that is under the change
+ * @param fromRotation rotation before the change
+ * @param toRotation rotation after the change
+ * @param newDisplayAreaInfo display area info after applying the update
* @param t A task transaction to populate.
*/
- void onRotateDisplay(int displayId, int fromRotation, int toRotation,
- WindowContainerTransaction t);
+ void onDisplayChange(int displayId, int fromRotation, int toRotation,
+ @Nullable DisplayAreaInfo newDisplayAreaInfo, WindowContainerTransaction t);
}
}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/common/DisplayController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/common/DisplayController.java
index 4ba32e93fb3d..764936cceb01 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/common/DisplayController.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/common/DisplayController.java
@@ -156,14 +156,14 @@ public class DisplayController {
* Adds a display rotation controller.
*/
public void addDisplayChangingController(OnDisplayChangingListener controller) {
- mChangeController.addRotationListener(controller);
+ mChangeController.addDisplayChangeListener(controller);
}
/**
* Removes a display rotation controller.
*/
public void removeDisplayChangingController(OnDisplayChangingListener controller) {
- mChangeController.removeRotationListener(controller);
+ mChangeController.removeDisplayChangeListener(controller);
}
private void onDisplayAdded(int displayId) {
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/common/DisplayImeController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/common/DisplayImeController.java
index 3b83f1586d8c..6a2acf438302 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/common/DisplayImeController.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/common/DisplayImeController.java
@@ -498,6 +498,11 @@ public class DisplayImeController implements DisplayController.OnDisplaysChanged
dispatchVisibilityChanged(mDisplayId, isShowing);
}
}
+
+ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
+ public InsetsSourceControl getImeSourceControl() {
+ return mImeSourceControl;
+ }
}
void removeImeSurface() {
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/TvPipModule.java b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/TvPipModule.java
index dfd4362e2373..1ea5e21a2c1e 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/TvPipModule.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/TvPipModule.java
@@ -18,6 +18,7 @@ package com.android.wm.shell.dagger;
import android.content.Context;
import android.os.Handler;
+import android.os.SystemClock;
import com.android.wm.shell.ShellTaskOrganizer;
import com.android.wm.shell.WindowManagerShellWrapper;
@@ -39,6 +40,7 @@ import com.android.wm.shell.pip.PipTransitionController;
import com.android.wm.shell.pip.PipTransitionState;
import com.android.wm.shell.pip.PipUiEventLogger;
import com.android.wm.shell.pip.tv.TvPipBoundsAlgorithm;
+import com.android.wm.shell.pip.tv.TvPipBoundsController;
import com.android.wm.shell.pip.tv.TvPipBoundsState;
import com.android.wm.shell.pip.tv.TvPipController;
import com.android.wm.shell.pip.tv.TvPipMenuController;
@@ -64,6 +66,7 @@ public abstract class TvPipModule {
Context context,
TvPipBoundsState tvPipBoundsState,
TvPipBoundsAlgorithm tvPipBoundsAlgorithm,
+ TvPipBoundsController tvPipBoundsController,
PipAppOpsListener pipAppOpsListener,
PipTaskOrganizer pipTaskOrganizer,
TvPipMenuController tvPipMenuController,
@@ -74,13 +77,13 @@ public abstract class TvPipModule {
PipParamsChangedForwarder pipParamsChangedForwarder,
DisplayController displayController,
WindowManagerShellWrapper windowManagerShellWrapper,
- @ShellMainThread ShellExecutor mainExecutor,
- @ShellMainThread Handler mainHandler) {
+ @ShellMainThread ShellExecutor mainExecutor) {
return Optional.of(
TvPipController.create(
context,
tvPipBoundsState,
tvPipBoundsAlgorithm,
+ tvPipBoundsController,
pipAppOpsListener,
pipTaskOrganizer,
pipTransitionController,
@@ -91,8 +94,22 @@ public abstract class TvPipModule {
pipParamsChangedForwarder,
displayController,
windowManagerShellWrapper,
- mainExecutor,
- mainHandler));
+ mainExecutor));
+ }
+
+ @WMSingleton
+ @Provides
+ static TvPipBoundsController provideTvPipBoundsController(
+ Context context,
+ @ShellMainThread Handler mainHandler,
+ TvPipBoundsState tvPipBoundsState,
+ TvPipBoundsAlgorithm tvPipBoundsAlgorithm) {
+ return new TvPipBoundsController(
+ context,
+ SystemClock::uptimeMillis,
+ mainHandler,
+ tvPipBoundsState,
+ tvPipBoundsAlgorithm);
}
@WMSingleton
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellBaseModule.java b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellBaseModule.java
index 67c41f06fd01..1d10bbe37438 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellBaseModule.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellBaseModule.java
@@ -38,8 +38,6 @@ import com.android.wm.shell.TaskViewFactory;
import com.android.wm.shell.TaskViewFactoryController;
import com.android.wm.shell.TaskViewTransitions;
import com.android.wm.shell.WindowManagerShellWrapper;
-import com.android.wm.shell.apppairs.AppPairs;
-import com.android.wm.shell.apppairs.AppPairsController;
import com.android.wm.shell.back.BackAnimation;
import com.android.wm.shell.back.BackAnimationController;
import com.android.wm.shell.bubbles.BubbleController;
@@ -560,17 +558,6 @@ public abstract class WMShellBaseModule {
return Optional.empty();
}
- // App Pairs (optional feature)
-
- @WMSingleton
- @Provides
- static Optional<AppPairs> provideAppPairs(Optional<AppPairsController> appPairsController) {
- return appPairsController.map((controller) -> controller.asAppPairs());
- }
-
- @BindsOptionalOf
- abstract AppPairsController optionalAppPairs();
-
//
// Starting window
//
@@ -651,7 +638,6 @@ public abstract class WMShellBaseModule {
KidsModeTaskOrganizer kidsModeTaskOrganizer,
Optional<BubbleController> bubblesOptional,
Optional<SplitScreenController> splitScreenOptional,
- Optional<AppPairsController> appPairsOptional,
Optional<PipTouchHandler> pipTouchHandlerOptional,
FullscreenTaskListener fullscreenTaskListener,
Optional<FullscreenUnfoldController> appUnfoldTransitionController,
@@ -669,7 +655,6 @@ public abstract class WMShellBaseModule {
kidsModeTaskOrganizer,
bubblesOptional,
splitScreenOptional,
- appPairsOptional,
pipTouchHandlerOptional,
fullscreenTaskListener,
appUnfoldTransitionController,
@@ -700,12 +685,11 @@ public abstract class WMShellBaseModule {
Optional<Pip> pipOptional,
Optional<OneHandedController> oneHandedOptional,
Optional<HideDisplayCutoutController> hideDisplayCutout,
- Optional<AppPairsController> appPairsOptional,
Optional<RecentTasksController> recentTasksOptional,
@ShellMainThread ShellExecutor mainExecutor) {
return new ShellCommandHandlerImpl(shellTaskOrganizer, kidsModeTaskOrganizer,
splitScreenOptional, pipOptional, oneHandedOptional, hideDisplayCutout,
- appPairsOptional, recentTasksOptional, mainExecutor);
+ recentTasksOptional, mainExecutor);
}
@WMSingleton
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellModule.java b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellModule.java
index 9c4ec5313c50..7ee2f5e811c3 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellModule.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellModule.java
@@ -29,7 +29,6 @@ import com.android.wm.shell.RootTaskDisplayAreaOrganizer;
import com.android.wm.shell.ShellTaskOrganizer;
import com.android.wm.shell.TaskViewTransitions;
import com.android.wm.shell.WindowManagerShellWrapper;
-import com.android.wm.shell.apppairs.AppPairsController;
import com.android.wm.shell.bubbles.BubbleController;
import com.android.wm.shell.common.DisplayController;
import com.android.wm.shell.common.DisplayImeController;
@@ -41,6 +40,7 @@ import com.android.wm.shell.common.SyncTransactionQueue;
import com.android.wm.shell.common.SystemWindows;
import com.android.wm.shell.common.TaskStackListenerImpl;
import com.android.wm.shell.common.TransactionPool;
+import com.android.wm.shell.common.annotations.ShellBackgroundThread;
import com.android.wm.shell.common.annotations.ShellMainThread;
import com.android.wm.shell.draganddrop.DragAndDropController;
import com.android.wm.shell.freeform.FreeformTaskListener;
@@ -113,13 +113,15 @@ public class WMShellModule {
DragAndDropController dragAndDropController,
@ShellMainThread ShellExecutor mainExecutor,
@ShellMainThread Handler mainHandler,
+ @ShellBackgroundThread ShellExecutor bgExecutor,
TaskViewTransitions taskViewTransitions,
SyncTransactionQueue syncQueue) {
return BubbleController.create(context, null /* synchronizer */,
floatingContentCoordinator, statusBarService, windowManager,
windowManagerShellWrapper, launcherApps, taskStackListener,
uiEventLogger, organizer, displayController, oneHandedOptional,
- dragAndDropController, mainExecutor, mainHandler, taskViewTransitions, syncQueue);
+ dragAndDropController, mainExecutor, mainHandler, bgExecutor,
+ taskViewTransitions, syncQueue);
}
//
@@ -176,17 +178,6 @@ public class WMShellModule {
recentTasks, stageTaskUnfoldControllerProvider);
}
- @WMSingleton
- @Provides
- static AppPairsController provideAppPairs(ShellTaskOrganizer shellTaskOrganizer,
- SyncTransactionQueue syncQueue, DisplayController displayController,
- @ShellMainThread ShellExecutor mainExecutor,
- DisplayImeController displayImeController,
- DisplayInsetsController displayInsetsController) {
- return new AppPairsController(shellTaskOrganizer, syncQueue, displayController,
- mainExecutor, displayImeController, displayInsetsController);
- }
-
//
// Pip
//
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/onehanded/OneHandedController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/onehanded/OneHandedController.java
index 179b725ab210..1d8ac2b576e9 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/onehanded/OneHandedController.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/onehanded/OneHandedController.java
@@ -39,6 +39,7 @@ import android.provider.Settings;
import android.util.Slog;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityManager;
+import android.window.DisplayAreaInfo;
import android.window.WindowContainerTransaction;
import androidx.annotation.NonNull;
@@ -659,11 +660,11 @@ public class OneHandedController implements RemoteCallable<OneHandedController>,
}
/**
- * Handles rotation based on OnDisplayChangingListener callback
+ * Handles display change based on OnDisplayChangingListener callback
*/
@Override
- public void onRotateDisplay(int displayId, int fromRotation, int toRotation,
- WindowContainerTransaction wct) {
+ public void onDisplayChange(int displayId, int fromRotation, int toRotation,
+ DisplayAreaInfo newDisplayAreaInfo, WindowContainerTransaction wct) {
if (!isInitialized()) {
return;
}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipTaskOrganizer.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipTaskOrganizer.java
index 57d7168b1d3c..b3eb0e155a34 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipTaskOrganizer.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipTaskOrganizer.java
@@ -1296,7 +1296,8 @@ public class PipTaskOrganizer implements ShellTaskOrganizer.TaskListener,
*/
public void scheduleOffsetPip(Rect originalBounds, int offset, int duration,
Consumer<Rect> updateBoundsCallback) {
- if (mPipTransitionState.shouldBlockResizeRequest()) {
+ if (mPipTransitionState.shouldBlockResizeRequest()
+ || mPipTransitionState.getInSwipePipToHomeTransition()) {
return;
}
if (mWaitForFixedRotation) {
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipTransition.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipTransition.java
index dfd34f8b7bc6..9adfbfeb8b28 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipTransition.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipTransition.java
@@ -336,11 +336,27 @@ public class PipTransition extends PipTransitionController {
// (likely a remote like launcher), so don't fire the finish-callback here -- wait until
// the exit transition is merged.
if ((mExitTransition == null || isAnimatingLocally()) && mFinishCallback != null) {
- WindowContainerTransaction wct = new WindowContainerTransaction();
- prepareFinishResizeTransaction(taskInfo, destinationBounds,
- direction, wct);
- if (tx != null) {
- wct.setBoundsChangeTransaction(taskInfo.token, tx);
+ WindowContainerTransaction wct = null;
+ if (isOutPipDirection(direction)) {
+ // Only need to reset surface properties. The server-side operations were already
+ // done at the start.
+ if (tx != null) {
+ mFinishTransaction.merge(tx);
+ }
+ } else {
+ wct = new WindowContainerTransaction();
+ if (isInPipDirection(direction)) {
+ // If we are animating from fullscreen using a bounds animation, then reset the
+ // activity windowing mode, and set the task bounds to the final bounds
+ wct.setActivityWindowingMode(taskInfo.token, WINDOWING_MODE_UNDEFINED);
+ wct.scheduleFinishEnterPip(taskInfo.token, destinationBounds);
+ wct.setBounds(taskInfo.token, destinationBounds);
+ } else {
+ wct.setBounds(taskInfo.token, null /* bounds */);
+ }
+ if (tx != null) {
+ wct.setBoundsChangeTransaction(taskInfo.token, tx);
+ }
}
final SurfaceControl leash = mPipOrganizer.getSurfaceControl();
final int displayRotation = taskInfo.getConfiguration().windowConfiguration
@@ -876,27 +892,4 @@ public class PipTransition extends PipTransitionController {
mPipMenuController.movePipMenu(null, null, destinationBounds);
mPipMenuController.updateMenuBounds(destinationBounds);
}
-
- private void prepareFinishResizeTransaction(TaskInfo taskInfo, Rect destinationBounds,
- @PipAnimationController.TransitionDirection int direction,
- WindowContainerTransaction wct) {
- Rect taskBounds = null;
- if (isInPipDirection(direction)) {
- // If we are animating from fullscreen using a bounds animation, then reset the
- // activity windowing mode set by WM, and set the task bounds to the final bounds
- taskBounds = destinationBounds;
- wct.setActivityWindowingMode(taskInfo.token, WINDOWING_MODE_UNDEFINED);
- wct.scheduleFinishEnterPip(taskInfo.token, destinationBounds);
- } else if (isOutPipDirection(direction)) {
- // If we are animating to fullscreen, then we need to reset the override bounds
- // on the task to ensure that the task "matches" the parent's bounds.
- taskBounds = (direction == TRANSITION_DIRECTION_LEAVE_PIP)
- ? null : destinationBounds;
- wct.setWindowingMode(taskInfo.token, getOutPipWindowingMode());
- // Simply reset the activity mode set prior to the animation running.
- wct.setActivityWindowingMode(taskInfo.token, WINDOWING_MODE_UNDEFINED);
- }
-
- wct.setBounds(taskInfo.token, taskBounds);
- }
}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipController.java
index 4b1e5f8c0d7c..60b406c7c3d9 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipController.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipController.java
@@ -156,7 +156,7 @@ public class PipController implements PipTransitionController.PipTransitionCallb
* Handler for display rotation changes.
*/
private final DisplayChangeController.OnDisplayChangingListener mRotationController = (
- int displayId, int fromRotation, int toRotation, WindowContainerTransaction t) -> {
+ displayId, fromRotation, toRotation, newDisplayAreaInfo, t) -> {
if (mPipTransitionController.handleRotateDisplay(fromRotation, toRotation, t)) {
return;
}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipBoundsAlgorithm.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipBoundsAlgorithm.java
index 21d5d401835d..a2eadcdf6210 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipBoundsAlgorithm.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipBoundsAlgorithm.java
@@ -29,7 +29,6 @@ import android.content.Context;
import android.content.res.Resources;
import android.graphics.Insets;
import android.graphics.Rect;
-import android.os.SystemClock;
import android.util.ArraySet;
import android.util.Size;
import android.view.Gravity;
@@ -66,7 +65,7 @@ public class TvPipBoundsAlgorithm extends PipBoundsAlgorithm {
@NonNull PipSnapAlgorithm pipSnapAlgorithm) {
super(context, tvPipBoundsState, pipSnapAlgorithm);
this.mTvPipBoundsState = tvPipBoundsState;
- this.mKeepClearAlgorithm = new TvPipKeepClearAlgorithm(SystemClock::uptimeMillis);
+ this.mKeepClearAlgorithm = new TvPipKeepClearAlgorithm();
reloadResources(context);
}
@@ -80,7 +79,6 @@ public class TvPipBoundsAlgorithm extends PipBoundsAlgorithm {
res.getDimensionPixelSize(R.dimen.pip_keep_clear_area_padding));
mKeepClearAlgorithm.setMaxRestrictedDistanceFraction(
res.getFraction(R.fraction.config_pipMaxRestrictedMoveDistance, 1, 1));
- mKeepClearAlgorithm.setStashDuration(res.getInteger(R.integer.config_pipStashDuration));
}
@Override
@@ -104,7 +102,7 @@ public class TvPipBoundsAlgorithm extends PipBoundsAlgorithm {
updateGravityOnExpandToggled(Gravity.NO_GRAVITY, true);
}
mTvPipBoundsState.setTvPipExpanded(isPipExpanded);
- return getTvPipBounds().getBounds();
+ return adjustBoundsForTemporaryDecor(getTvPipPlacement().getBounds());
}
/** Returns the current bounds adjusted to the new aspect ratio, if valid. */
@@ -114,13 +112,27 @@ public class TvPipBoundsAlgorithm extends PipBoundsAlgorithm {
ProtoLog.d(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
"%s: getAdjustedDestinationBounds: %f", TAG, newAspectRatio);
}
- return getTvPipBounds().getBounds();
+ return adjustBoundsForTemporaryDecor(getTvPipPlacement().getBounds());
+ }
+
+ Rect adjustBoundsForTemporaryDecor(Rect bounds) {
+ Rect boundsWithDecor = new Rect(bounds);
+ Insets decorInset = mTvPipBoundsState.getPipMenuTemporaryDecorInsets();
+ Insets pipDecorReverseInsets = Insets.subtract(Insets.NONE, decorInset);
+ boundsWithDecor.inset(decorInset);
+ Gravity.apply(mTvPipBoundsState.getTvPipGravity(),
+ boundsWithDecor.width(), boundsWithDecor.height(), bounds, boundsWithDecor);
+
+ // remove temporary decoration again
+ boundsWithDecor.inset(pipDecorReverseInsets);
+ return boundsWithDecor;
}
/**
* Calculates the PiP bounds.
*/
- public Placement getTvPipBounds() {
+ @NonNull
+ public Placement getTvPipPlacement() {
final Size pipSize = getPipSize();
final Rect displayBounds = mTvPipBoundsState.getDisplayBounds();
final Size screenSize = new Size(displayBounds.width(), displayBounds.height());
@@ -153,8 +165,6 @@ public class TvPipBoundsAlgorithm extends PipBoundsAlgorithm {
mKeepClearAlgorithm.setStashOffset(mTvPipBoundsState.getStashOffset());
mKeepClearAlgorithm.setPipPermanentDecorInsets(
mTvPipBoundsState.getPipMenuPermanentDecorInsets());
- mKeepClearAlgorithm.setPipTemporaryDecorInsets(
- mTvPipBoundsState.getPipMenuTemporaryDecorInsets());
final Placement placement = mKeepClearAlgorithm.calculatePipPosition(
pipSize,
@@ -407,8 +417,4 @@ public class TvPipBoundsAlgorithm extends PipBoundsAlgorithm {
TAG, expandedSize.getWidth(), expandedSize.getHeight());
}
}
-
- void keepUnstashedForCurrentKeepClearAreas() {
- mKeepClearAlgorithm.keepUnstashedForCurrentKeepClearAreas();
- }
}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipBoundsController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipBoundsController.java
new file mode 100644
index 000000000000..3a6ce81821ec
--- /dev/null
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipBoundsController.java
@@ -0,0 +1,253 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.wm.shell.pip.tv;
+
+import static com.android.wm.shell.pip.PipBoundsState.STASH_TYPE_NONE;
+
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.content.Context;
+import android.content.res.Resources;
+import android.graphics.Rect;
+import android.os.Handler;
+
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.protolog.common.ProtoLog;
+import com.android.wm.shell.R;
+import com.android.wm.shell.pip.tv.TvPipKeepClearAlgorithm.Placement;
+import com.android.wm.shell.protolog.ShellProtoLogGroup;
+
+import java.util.Objects;
+import java.util.function.Supplier;
+
+/**
+ * Controller managing the PiP's position.
+ * Manages debouncing of PiP movements and scheduling of unstashing.
+ */
+public class TvPipBoundsController {
+ private static final boolean DEBUG = false;
+ private static final String TAG = "TvPipBoundsController";
+
+ /**
+ * Time the calculated PiP position needs to be stable before PiP is moved there,
+ * to avoid erratic movement.
+ * Some changes will cause the PiP to be repositioned immediately, such as changes to
+ * unrestricted keep clear areas.
+ */
+ @VisibleForTesting
+ static final long POSITION_DEBOUNCE_TIMEOUT_MILLIS = 300L;
+
+ private final Context mContext;
+ private final Supplier<Long> mClock;
+ private final Handler mMainHandler;
+ private final TvPipBoundsState mTvPipBoundsState;
+ private final TvPipBoundsAlgorithm mTvPipBoundsAlgorithm;
+
+ @Nullable
+ private PipBoundsListener mListener;
+
+ private int mResizeAnimationDuration;
+ private int mStashDurationMs;
+ private Rect mCurrentPlacementBounds;
+ private Rect mPipTargetBounds;
+
+ private final Runnable mApplyPendingPlacementRunnable = this::applyPendingPlacement;
+ private boolean mPendingStash;
+ private Placement mPendingPlacement;
+ private int mPendingPlacementAnimationDuration;
+ private Runnable mUnstashRunnable;
+
+ public TvPipBoundsController(
+ Context context,
+ Supplier<Long> clock,
+ Handler mainHandler,
+ TvPipBoundsState tvPipBoundsState,
+ TvPipBoundsAlgorithm tvPipBoundsAlgorithm) {
+ mContext = context;
+ mClock = clock;
+ mMainHandler = mainHandler;
+ mTvPipBoundsState = tvPipBoundsState;
+ mTvPipBoundsAlgorithm = tvPipBoundsAlgorithm;
+
+ loadConfigurations();
+ }
+
+ private void loadConfigurations() {
+ final Resources res = mContext.getResources();
+ mResizeAnimationDuration = res.getInteger(R.integer.config_pipResizeAnimationDuration);
+ mStashDurationMs = res.getInteger(R.integer.config_pipStashDuration);
+ }
+
+ void setListener(PipBoundsListener listener) {
+ mListener = listener;
+ }
+
+ /**
+ * Update the PiP bounds based on the state of the PiP, decors, and keep clear areas.
+ * Unless {@code immediate} is {@code true}, the PiP does not move immediately to avoid
+ * keep clear areas, but waits for a new position to stay uncontested for
+ * {@link #POSITION_DEBOUNCE_TIMEOUT_MILLIS} before moving to it.
+ * Temporary decor changes are applied immediately.
+ *
+ * @param stayAtAnchorPosition If true, PiP will be placed at the anchor position
+ * @param disallowStashing If true, PiP will not be placed off-screen in a stashed position
+ * @param animationDuration Duration of the animation to the new position
+ * @param immediate If true, PiP will move immediately to avoid keep clear areas
+ */
+ @VisibleForTesting
+ void recalculatePipBounds(boolean stayAtAnchorPosition, boolean disallowStashing,
+ int animationDuration, boolean immediate) {
+ final Placement placement = mTvPipBoundsAlgorithm.getTvPipPlacement();
+
+ final int stashType = disallowStashing ? STASH_TYPE_NONE : placement.getStashType();
+ mTvPipBoundsState.setStashed(stashType);
+ if (stayAtAnchorPosition) {
+ cancelScheduledPlacement();
+ applyPlacementBounds(placement.getAnchorBounds(), animationDuration);
+ } else if (disallowStashing) {
+ cancelScheduledPlacement();
+ applyPlacementBounds(placement.getUnstashedBounds(), animationDuration);
+ } else if (immediate) {
+ cancelScheduledPlacement();
+ applyPlacementBounds(placement.getBounds(), animationDuration);
+ scheduleUnstashIfNeeded(placement);
+ } else {
+ applyPlacementBounds(mCurrentPlacementBounds, animationDuration);
+ schedulePinnedStackPlacement(placement, animationDuration);
+ }
+ }
+
+ private void schedulePinnedStackPlacement(@NonNull final Placement placement,
+ int animationDuration) {
+ if (DEBUG) {
+ ProtoLog.d(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
+ "%s: schedulePinnedStackPlacement() - pip bounds: %s",
+ TAG, placement.getBounds().toShortString());
+ }
+
+ if (mPendingPlacement != null && Objects.equals(mPendingPlacement.getBounds(),
+ placement.getBounds())) {
+ mPendingStash = mPendingStash || placement.getTriggerStash();
+ return;
+ }
+
+ mPendingStash = placement.getStashType() != STASH_TYPE_NONE
+ && (mPendingStash || placement.getTriggerStash());
+
+ mMainHandler.removeCallbacks(mApplyPendingPlacementRunnable);
+ mPendingPlacement = placement;
+ mPendingPlacementAnimationDuration = animationDuration;
+ mMainHandler.postAtTime(mApplyPendingPlacementRunnable,
+ mClock.get() + POSITION_DEBOUNCE_TIMEOUT_MILLIS);
+ }
+
+ private void scheduleUnstashIfNeeded(final Placement placement) {
+ if (mUnstashRunnable != null) {
+ mMainHandler.removeCallbacks(mUnstashRunnable);
+ mUnstashRunnable = null;
+ }
+ if (placement.getUnstashDestinationBounds() != null) {
+ mUnstashRunnable = () -> {
+ applyPlacementBounds(placement.getUnstashDestinationBounds(),
+ mResizeAnimationDuration);
+ mUnstashRunnable = null;
+ };
+ mMainHandler.postAtTime(mUnstashRunnable, mClock.get() + mStashDurationMs);
+ }
+ }
+
+ private void applyPendingPlacement() {
+ if (DEBUG) {
+ ProtoLog.d(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
+ "%s: applyPendingPlacement()", TAG);
+ }
+ if (mPendingPlacement != null) {
+ if (mPendingStash) {
+ mPendingStash = false;
+ scheduleUnstashIfNeeded(mPendingPlacement);
+ }
+
+ if (mUnstashRunnable != null) {
+ // currently stashed, use stashed pos
+ applyPlacementBounds(mPendingPlacement.getBounds(),
+ mPendingPlacementAnimationDuration);
+ } else {
+ applyPlacementBounds(mPendingPlacement.getUnstashedBounds(),
+ mPendingPlacementAnimationDuration);
+ }
+ }
+
+ mPendingPlacement = null;
+ }
+
+ void onPipDismissed() {
+ mCurrentPlacementBounds = null;
+ mPipTargetBounds = null;
+ cancelScheduledPlacement();
+ }
+
+ private void cancelScheduledPlacement() {
+ mMainHandler.removeCallbacks(mApplyPendingPlacementRunnable);
+ mPendingPlacement = null;
+
+ if (mUnstashRunnable != null) {
+ mMainHandler.removeCallbacks(mUnstashRunnable);
+ mUnstashRunnable = null;
+ }
+ }
+
+ private void applyPlacementBounds(Rect bounds, int animationDuration) {
+ if (bounds == null) {
+ return;
+ }
+
+ mCurrentPlacementBounds = bounds;
+ Rect adjustedBounds = mTvPipBoundsAlgorithm.adjustBoundsForTemporaryDecor(bounds);
+ movePipTo(adjustedBounds, animationDuration);
+ }
+
+ /** Animates the PiP to the given bounds with the given animation duration. */
+ private void movePipTo(Rect bounds, int animationDuration) {
+ if (Objects.equals(mPipTargetBounds, bounds)) {
+ return;
+ }
+
+ mPipTargetBounds = bounds;
+ if (DEBUG) {
+ ProtoLog.d(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
+ "%s: movePipTo() - new pip bounds: %s", TAG, bounds.toShortString());
+ }
+
+ if (mListener != null) {
+ mListener.onPipTargetBoundsChange(bounds, animationDuration);
+ }
+ }
+
+ /**
+ * Interface being notified of changes to the PiP bounds as calculated by
+ * @link TvPipBoundsController}.
+ */
+ public interface PipBoundsListener {
+ /**
+ * Called when the calculated PiP bounds are changing.
+ *
+ * @param newTargetBounds The new bounds of the PiP.
+ * @param animationDuration The animation duration for the PiP movement.
+ */
+ void onPipTargetBoundsChange(Rect newTargetBounds, int animationDuration);
+ }
+}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipController.java
index 766779413094..fa48def9c7d7 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipController.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipController.java
@@ -25,12 +25,10 @@ import android.app.ActivityTaskManager;
import android.app.PendingIntent;
import android.app.RemoteAction;
import android.app.TaskInfo;
-import android.content.ComponentName;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Rect;
-import android.os.Handler;
import android.os.RemoteException;
import android.view.Gravity;
@@ -46,25 +44,24 @@ import com.android.wm.shell.pip.PinnedStackListenerForwarder;
import com.android.wm.shell.pip.Pip;
import com.android.wm.shell.pip.PipAnimationController;
import com.android.wm.shell.pip.PipAppOpsListener;
-import com.android.wm.shell.pip.PipBoundsState;
import com.android.wm.shell.pip.PipMediaController;
import com.android.wm.shell.pip.PipParamsChangedForwarder;
import com.android.wm.shell.pip.PipTaskOrganizer;
import com.android.wm.shell.pip.PipTransitionController;
-import com.android.wm.shell.pip.tv.TvPipKeepClearAlgorithm.Placement;
import com.android.wm.shell.protolog.ShellProtoLogGroup;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.List;
+import java.util.Objects;
import java.util.Set;
/**
* Manages the picture-in-picture (PIP) UI and states.
*/
public class TvPipController implements PipTransitionController.PipTransitionCallback,
- TvPipMenuController.Delegate, TvPipNotificationController.Delegate,
- DisplayController.OnDisplaysChangedListener {
+ TvPipBoundsController.PipBoundsListener, TvPipMenuController.Delegate,
+ TvPipNotificationController.Delegate, DisplayController.OnDisplaysChangedListener {
private static final String TAG = "TvPipController";
static final boolean DEBUG = false;
@@ -98,19 +95,18 @@ public class TvPipController implements PipTransitionController.PipTransitionCal
private final TvPipBoundsState mTvPipBoundsState;
private final TvPipBoundsAlgorithm mTvPipBoundsAlgorithm;
+ private final TvPipBoundsController mTvPipBoundsController;
private final PipAppOpsListener mAppOpsListener;
private final PipTaskOrganizer mPipTaskOrganizer;
private final PipMediaController mPipMediaController;
private final TvPipNotificationController mPipNotificationController;
private final TvPipMenuController mTvPipMenuController;
private final ShellExecutor mMainExecutor;
- private final Handler mMainHandler;
private final TvPipImpl mImpl = new TvPipImpl();
private @State int mState = STATE_NO_PIP;
private int mPreviousGravity = TvPipBoundsState.DEFAULT_TV_GRAVITY;
private int mPinnedTaskId = NONEXISTENT_TASK_ID;
- private Runnable mUnstashRunnable;
private RemoteAction mCloseAction;
// How long the shell will wait for the app to close the PiP if a custom action is set.
@@ -123,6 +119,7 @@ public class TvPipController implements PipTransitionController.PipTransitionCal
Context context,
TvPipBoundsState tvPipBoundsState,
TvPipBoundsAlgorithm tvPipBoundsAlgorithm,
+ TvPipBoundsController tvPipBoundsController,
PipAppOpsListener pipAppOpsListener,
PipTaskOrganizer pipTaskOrganizer,
PipTransitionController pipTransitionController,
@@ -133,12 +130,12 @@ public class TvPipController implements PipTransitionController.PipTransitionCal
PipParamsChangedForwarder pipParamsChangedForwarder,
DisplayController displayController,
WindowManagerShellWrapper wmShell,
- ShellExecutor mainExecutor,
- Handler mainHandler) {
+ ShellExecutor mainExecutor) {
return new TvPipController(
context,
tvPipBoundsState,
tvPipBoundsAlgorithm,
+ tvPipBoundsController,
pipAppOpsListener,
pipTaskOrganizer,
pipTransitionController,
@@ -149,14 +146,14 @@ public class TvPipController implements PipTransitionController.PipTransitionCal
pipParamsChangedForwarder,
displayController,
wmShell,
- mainExecutor,
- mainHandler).mImpl;
+ mainExecutor).mImpl;
}
private TvPipController(
Context context,
TvPipBoundsState tvPipBoundsState,
TvPipBoundsAlgorithm tvPipBoundsAlgorithm,
+ TvPipBoundsController tvPipBoundsController,
PipAppOpsListener pipAppOpsListener,
PipTaskOrganizer pipTaskOrganizer,
PipTransitionController pipTransitionController,
@@ -167,16 +164,16 @@ public class TvPipController implements PipTransitionController.PipTransitionCal
PipParamsChangedForwarder pipParamsChangedForwarder,
DisplayController displayController,
WindowManagerShellWrapper wmShell,
- ShellExecutor mainExecutor,
- Handler mainHandler) {
+ ShellExecutor mainExecutor) {
mContext = context;
mMainExecutor = mainExecutor;
- mMainHandler = mainHandler;
mTvPipBoundsState = tvPipBoundsState;
mTvPipBoundsState.setDisplayId(context.getDisplayId());
mTvPipBoundsState.setDisplayLayout(new DisplayLayout(context, context.getDisplay()));
mTvPipBoundsAlgorithm = tvPipBoundsAlgorithm;
+ mTvPipBoundsController = tvPipBoundsController;
+ mTvPipBoundsController.setListener(this);
mPipMediaController = pipMediaController;
@@ -227,7 +224,7 @@ public class TvPipController implements PipTransitionController.PipTransitionCal
/**
* Starts the process if bringing up the Pip menu if by issuing a command to move Pip
* task/window to the "Menu" position. We'll show the actual Menu UI (eg. actions) once the Pip
- * task/window is properly positioned in {@link #onPipTransitionFinished(ComponentName, int)}.
+ * task/window is properly positioned in {@link #onPipTransitionFinished(int)}.
*/
@Override
public void showPictureInPictureMenu() {
@@ -256,7 +253,6 @@ public class TvPipController implements PipTransitionController.PipTransitionCal
"%s: closeMenu(), state before=%s", TAG, stateToName(mState));
}
setState(STATE_PIP);
- mTvPipBoundsAlgorithm.keepUnstashedForCurrentKeepClearAreas();
updatePinnedStackBounds();
}
@@ -331,68 +327,35 @@ public class TvPipController implements PipTransitionController.PipTransitionCal
public void onKeepClearAreasChanged(int displayId, Set<Rect> restricted,
Set<Rect> unrestricted) {
if (mTvPipBoundsState.getDisplayId() == displayId) {
+ boolean unrestrictedAreasChanged = !Objects.equals(unrestricted,
+ mTvPipBoundsState.getUnrestrictedKeepClearAreas());
mTvPipBoundsState.setKeepClearAreas(restricted, unrestricted);
- updatePinnedStackBounds();
+ updatePinnedStackBounds(mResizeAnimationDuration, unrestrictedAreasChanged);
}
}
private void updatePinnedStackBounds() {
- updatePinnedStackBounds(mResizeAnimationDuration);
+ updatePinnedStackBounds(mResizeAnimationDuration, true);
}
/**
* Update the PiP bounds based on the state of the PiP and keep clear areas.
- * Animates to the current PiP bounds, and schedules unstashing the PiP if necessary.
*/
- private void updatePinnedStackBounds(int animationDuration) {
+ private void updatePinnedStackBounds(int animationDuration, boolean immediate) {
if (mState == STATE_NO_PIP) {
return;
}
-
final boolean stayAtAnchorPosition = mTvPipMenuController.isInMoveMode();
final boolean disallowStashing = mState == STATE_PIP_MENU || stayAtAnchorPosition;
- final Placement placement = mTvPipBoundsAlgorithm.getTvPipBounds();
-
- int stashType =
- disallowStashing ? PipBoundsState.STASH_TYPE_NONE : placement.getStashType();
- mTvPipBoundsState.setStashed(stashType);
-
- if (stayAtAnchorPosition) {
- movePinnedStackTo(placement.getAnchorBounds());
- } else if (disallowStashing) {
- movePinnedStackTo(placement.getUnstashedBounds());
- } else {
- movePinnedStackTo(placement.getBounds());
- }
-
- if (mUnstashRunnable != null) {
- mMainHandler.removeCallbacks(mUnstashRunnable);
- mUnstashRunnable = null;
- }
- if (!disallowStashing && placement.getUnstashDestinationBounds() != null) {
- mUnstashRunnable = () -> {
- movePinnedStackTo(placement.getUnstashDestinationBounds(), animationDuration);
- };
- mMainHandler.postAtTime(mUnstashRunnable, placement.getUnstashTime());
- }
- }
-
- /** Animates the PiP to the given bounds. */
- private void movePinnedStackTo(Rect bounds) {
- movePinnedStackTo(bounds, mResizeAnimationDuration);
+ mTvPipBoundsController.recalculatePipBounds(stayAtAnchorPosition, disallowStashing,
+ animationDuration, immediate);
}
- /** Animates the PiP to the given bounds with the given animation duration. */
- private void movePinnedStackTo(Rect bounds, int animationDuration) {
- if (DEBUG) {
- ProtoLog.d(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
- "%s: movePinnedStack() - new pip bounds: %s", TAG, bounds.toShortString());
- }
- mPipTaskOrganizer.scheduleAnimateResizePip(bounds,
- animationDuration, rect -> {
- mTvPipMenuController.updateExpansionState();
- });
- mTvPipMenuController.onPipTransitionStarted(bounds);
+ @Override
+ public void onPipTargetBoundsChange(Rect newTargetBounds, int animationDuration) {
+ mPipTaskOrganizer.scheduleAnimateResizePip(newTargetBounds,
+ animationDuration, rect -> mTvPipMenuController.updateExpansionState());
+ mTvPipMenuController.onPipTransitionStarted(newTargetBounds);
}
/**
@@ -431,7 +394,7 @@ public class TvPipController implements PipTransitionController.PipTransitionCal
@Override
public void closeEduText() {
- updatePinnedStackBounds(mEduTextWindowExitAnimationDurationMs);
+ updatePinnedStackBounds(mEduTextWindowExitAnimationDurationMs, false);
}
private void registerSessionListenerForCurrentUser() {
@@ -473,6 +436,7 @@ public class TvPipController implements PipTransitionController.PipTransitionCal
mPipNotificationController.dismiss();
mTvPipMenuController.closeMenu();
mTvPipBoundsState.resetTvPipState();
+ mTvPipBoundsController.onPipDismissed();
setState(STATE_NO_PIP);
mPinnedTaskId = NONEXISTENT_TASK_ID;
}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipKeepClearAlgorithm.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipKeepClearAlgorithm.kt
index 07dccd58abfd..1e54436ebce9 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipKeepClearAlgorithm.kt
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipKeepClearAlgorithm.kt
@@ -33,17 +33,14 @@ import kotlin.math.min
import kotlin.math.roundToInt
private const val DEFAULT_PIP_MARGINS = 48
-private const val DEFAULT_STASH_DURATION = 5000L
private const val RELAX_DEPTH = 1
private const val DEFAULT_MAX_RESTRICTED_DISTANCE_FRACTION = 0.15
/**
* This class calculates an appropriate position for a Picture-In-Picture (PiP) window, taking
* into account app defined keep clear areas.
- *
- * @param clock A function returning a current timestamp (in milliseconds)
*/
-class TvPipKeepClearAlgorithm(private val clock: () -> Long) {
+class TvPipKeepClearAlgorithm() {
/**
* Result of the positioning algorithm.
*
@@ -51,17 +48,17 @@ class TvPipKeepClearAlgorithm(private val clock: () -> Long) {
* @param anchorBounds The bounds of the PiP anchor position
* (where the PiP would be placed if there were no keep clear areas)
* @param stashType Where the PiP has been stashed, if at all
- * @param unstashDestinationBounds If stashed, the PiP should move to this position after
- * [stashDuration] has passed.
- * @param unstashTime If stashed, the time at which the PiP should move
- * to [unstashDestinationBounds]
+ * @param unstashDestinationBounds If stashed, the PiP should move to this position when
+ * unstashing.
+ * @param triggerStash Whether this placement should trigger the PiP to stash, or extend
+ * the unstash timeout if already stashed.
*/
data class Placement(
val bounds: Rect,
val anchorBounds: Rect,
@PipBoundsState.StashType val stashType: Int = STASH_TYPE_NONE,
val unstashDestinationBounds: Rect? = null,
- val unstashTime: Long = 0L
+ val triggerStash: Boolean = false
) {
/** Bounds to use if the PiP should not be stashed. */
fun getUnstashedBounds() = unstashDestinationBounds ?: bounds
@@ -79,12 +76,6 @@ class TvPipKeepClearAlgorithm(private val clock: () -> Long) {
/** The distance the PiP peeks into the screen when stashed */
var stashOffset = DEFAULT_PIP_MARGINS
- /**
- * How long (in milliseconds) the PiP should stay stashed for after the last time the
- * keep clear areas causing the PiP to stash have changed.
- */
- var stashDuration = DEFAULT_STASH_DURATION
-
/** The fraction of screen width/height restricted keep clear areas can move the PiP */
var maxRestrictedDistanceFraction = DEFAULT_MAX_RESTRICTED_DISTANCE_FRACTION
@@ -93,14 +84,10 @@ class TvPipKeepClearAlgorithm(private val clock: () -> Long) {
private var transformedMovementBounds = Rect()
private var lastAreasOverlappingUnstashPosition: Set<Rect> = emptySet()
- private var lastStashTime: Long = Long.MIN_VALUE
/** Spaces around the PiP that we should leave space for when placing the PiP. Permanent PiP
* decorations are relevant for calculating intersecting keep clear areas */
private var pipPermanentDecorInsets = Insets.NONE
- /** Spaces around the PiP that we should leave space for when placing the PiP. Temporary PiP
- * decorations are not relevant for calculating intersecting keep clear areas */
- private var pipTemporaryDecorInsets = Insets.NONE
/**
* Calculates the position the PiP should be placed at, taking into consideration the
@@ -113,8 +100,8 @@ class TvPipKeepClearAlgorithm(private val clock: () -> Long) {
* always try to respect these areas.
*
* If no free space the PiP is allowed to move to can be found, a stashed position is returned
- * as [Placement.bounds], along with a position to move to once [Placement.unstashTime] has
- * passed as [Placement.unstashDestinationBounds].
+ * as [Placement.bounds], along with a position to move to when the PiP unstashes
+ * as [Placement.unstashDestinationBounds].
*
* @param pipSize The size of the PiP window
* @param restrictedAreas The restricted keep clear areas
@@ -130,13 +117,11 @@ class TvPipKeepClearAlgorithm(private val clock: () -> Long) {
val transformedUnrestrictedAreas = transformAndFilterAreas(unrestrictedAreas)
val pipSizeWithAllDecors = addDecors(pipSize)
- val pipAnchorBoundsWithAllDecors =
+ val pipAnchorBoundsWithDecors =
getNormalPipAnchorBounds(pipSizeWithAllDecors, transformedMovementBounds)
- val pipAnchorBoundsWithPermanentDecors =
- removeTemporaryDecorsTransformed(pipAnchorBoundsWithAllDecors)
val result = calculatePipPositionTransformed(
- pipAnchorBoundsWithPermanentDecors,
+ pipAnchorBoundsWithDecors,
transformedRestrictedAreas,
transformedUnrestrictedAreas
)
@@ -152,7 +137,7 @@ class TvPipKeepClearAlgorithm(private val clock: () -> Long) {
anchorBounds,
getStashType(pipBounds, unstashedDestBounds),
unstashedDestBounds,
- result.unstashTime
+ result.triggerStash
)
}
@@ -213,26 +198,13 @@ class TvPipKeepClearAlgorithm(private val clock: () -> Long) {
!lastAreasOverlappingUnstashPosition.containsAll(areasOverlappingUnstashPosition)
lastAreasOverlappingUnstashPosition = areasOverlappingUnstashPosition
- val now = clock()
- if (areasOverlappingUnstashPositionChanged) {
- lastStashTime = now
- }
-
- // If overlapping areas haven't changed and the stash duration has passed, we can
- // place the PiP at the unstash position
- val unstashTime = lastStashTime + stashDuration
- if (now >= unstashTime) {
- return Placement(unstashBounds, pipAnchorBounds)
- }
-
- // Otherwise, we'll stash it close to the unstash position
val stashedBounds = getNearbyStashedPosition(unstashBounds, keepClearAreas)
return Placement(
stashedBounds,
pipAnchorBounds,
getStashType(stashedBounds, unstashBounds),
unstashBounds,
- unstashTime
+ areasOverlappingUnstashPositionChanged
)
}
@@ -439,14 +411,6 @@ class TvPipKeepClearAlgorithm(private val clock: () -> Long) {
}
/**
- * Prevents the PiP from being stashed for the current set of keep clear areas.
- * The PiP may stash again if keep clear areas change.
- */
- fun keepUnstashedForCurrentKeepClearAreas() {
- lastStashTime = Long.MIN_VALUE
- }
-
- /**
* Updates the size of the screen.
*
* @param size The new size of the screen
@@ -492,10 +456,6 @@ class TvPipKeepClearAlgorithm(private val clock: () -> Long) {
pipPermanentDecorInsets = insets
}
- fun setPipTemporaryDecorInsets(insets: Insets) {
- pipTemporaryDecorInsets = insets
- }
-
/**
* @param open Whether this event marks the opening of an occupied segment
* @param pos The coordinate of this event
@@ -790,7 +750,6 @@ class TvPipKeepClearAlgorithm(private val clock: () -> Long) {
private fun addDecors(size: Size): Size {
val bounds = Rect(0, 0, size.width, size.height)
bounds.inset(pipPermanentDecorInsets)
- bounds.inset(pipTemporaryDecorInsets)
return Size(bounds.width(), bounds.height())
}
@@ -805,19 +764,6 @@ class TvPipKeepClearAlgorithm(private val clock: () -> Long) {
return bounds
}
- /**
- * Removes the space that was reserved for temporary decorations around the PiP
- * @param bounds the bounds (in base case) to remove the insets from
- */
- private fun removeTemporaryDecorsTransformed(bounds: Rect): Rect {
- if (pipTemporaryDecorInsets == Insets.NONE) return bounds
-
- val reverseInsets = Insets.subtract(Insets.NONE, pipTemporaryDecorInsets)
- val boundsInScreenSpace = fromTransformedSpace(bounds)
- boundsInScreenSpace.inset(reverseInsets)
- return toTransformedSpace(boundsInScreenSpace)
- }
-
private fun Rect.offsetCopy(dx: Int, dy: Int) = Rect(this).apply { offset(dx, dy) }
private fun Rect.intersectsX(other: Rect) = right >= other.left && left <= other.right
private fun Rect.intersectsY(other: Rect) = bottom >= other.top && top <= other.bottom
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipMenuController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipMenuController.java
index 132c04481bce..4ce45e142c64 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipMenuController.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipMenuController.java
@@ -209,7 +209,7 @@ public class TvPipMenuController implements PipMenuController, TvPipMenuView.Lis
ProtoLog.d(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
"%s: showMovementMenuOnly()", TAG);
}
- mInMoveMode = true;
+ setInMoveMode(true);
mCloseAfterExitMoveMenu = true;
showMenuInternal();
}
@@ -219,7 +219,7 @@ public class TvPipMenuController implements PipMenuController, TvPipMenuView.Lis
if (DEBUG) {
ProtoLog.d(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE, "%s: showMenu()", TAG);
}
- mInMoveMode = false;
+ setInMoveMode(false);
mCloseAfterExitMoveMenu = false;
showMenuInternal();
}
@@ -293,6 +293,17 @@ public class TvPipMenuController implements PipMenuController, TvPipMenuView.Lis
return mInMoveMode;
}
+ private void setInMoveMode(boolean moveMode) {
+ if (mInMoveMode == moveMode) {
+ return;
+ }
+
+ mInMoveMode = moveMode;
+ if (mDelegate != null) {
+ mDelegate.onInMoveModeChanged();
+ }
+ }
+
@Override
public void onEnterMoveMode() {
if (DEBUG) {
@@ -300,7 +311,7 @@ public class TvPipMenuController implements PipMenuController, TvPipMenuView.Lis
"%s: onEnterMoveMode - %b, close when exiting move menu: %b", TAG, mInMoveMode,
mCloseAfterExitMoveMenu);
}
- mInMoveMode = true;
+ setInMoveMode(true);
mPipMenuView.showMoveMenu(mDelegate.getPipGravity());
}
@@ -312,13 +323,13 @@ public class TvPipMenuController implements PipMenuController, TvPipMenuView.Lis
mCloseAfterExitMoveMenu);
}
if (mCloseAfterExitMoveMenu) {
- mInMoveMode = false;
+ setInMoveMode(false);
mCloseAfterExitMoveMenu = false;
closeMenu();
return true;
}
if (mInMoveMode) {
- mInMoveMode = false;
+ setInMoveMode(false);
mPipMenuView.showButtonsMenu();
return true;
}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/StageCoordinator.java b/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/StageCoordinator.java
index 6274d6fa00ee..5671fec8adfd 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/StageCoordinator.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/StageCoordinator.java
@@ -83,6 +83,7 @@ import android.view.RemoteAnimationTarget;
import android.view.SurfaceControl;
import android.view.SurfaceSession;
import android.view.WindowManager;
+import android.window.DisplayAreaInfo;
import android.window.RemoteTransition;
import android.window.TransitionInfo;
import android.window.TransitionRequestInfo;
@@ -980,6 +981,9 @@ public class StageCoordinator implements SplitLayout.SplitLayoutHandler,
updateUnfoldBounds();
return;
}
+ // Clear the divider remote animating flag as the divider will be re-rendered to apply
+ // the new rotation config.
+ mIsDividerRemoteAnimating = false;
mSplitLayout.update(null /* t */);
onLayoutSizeChanged(mSplitLayout);
}
@@ -1112,7 +1116,7 @@ public class StageCoordinator implements SplitLayout.SplitLayoutHandler,
final SurfaceControl.Transaction transaction = mTransactionPool.acquire();
mDividerFadeInAnimator = ValueAnimator.ofFloat(0f, 1f);
mDividerFadeInAnimator.addUpdateListener(animation -> {
- if (dividerLeash == null) {
+ if (dividerLeash == null || !dividerLeash.isValid()) {
mDividerFadeInAnimator.cancel();
return;
}
@@ -1122,7 +1126,7 @@ public class StageCoordinator implements SplitLayout.SplitLayoutHandler,
mDividerFadeInAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
- if (dividerLeash == null) {
+ if (dividerLeash == null || !dividerLeash.isValid()) {
mDividerFadeInAnimator.cancel();
return;
}
@@ -1315,7 +1319,7 @@ public class StageCoordinator implements SplitLayout.SplitLayoutHandler,
if (displayId != DEFAULT_DISPLAY) {
return;
}
- mDisplayController.addDisplayChangingController(this::onRotateDisplay);
+ mDisplayController.addDisplayChangingController(this::onDisplayChange);
}
@Override
@@ -1326,14 +1330,17 @@ public class StageCoordinator implements SplitLayout.SplitLayoutHandler,
mDisplayLayout.set(mDisplayController.getDisplayLayout(displayId));
}
- private void onRotateDisplay(int displayId, int fromRotation, int toRotation,
- WindowContainerTransaction wct) {
+ private void onDisplayChange(int displayId, int fromRotation, int toRotation,
+ @Nullable DisplayAreaInfo newDisplayAreaInfo, WindowContainerTransaction wct) {
if (!mMainStage.isActive()) return;
// Only do this when shell transition
if (!ENABLE_SHELL_TRANSITIONS) return;
mDisplayLayout.rotateTo(mContext.getResources(), toRotation);
mSplitLayout.rotateTo(toRotation, mDisplayLayout.stableInsets());
+ if (newDisplayAreaInfo != null) {
+ mSplitLayout.updateConfiguration(newDisplayAreaInfo.configuration);
+ }
updateWindowBounds(mSplitLayout, wct);
updateUnfoldBounds();
}
@@ -1441,8 +1448,9 @@ public class StageCoordinator implements SplitLayout.SplitLayoutHandler,
// Enter overview panel, so start recent transition.
mSplitTransitions.setRecentTransition(transition,
request.getRemoteTransition());
- } else {
- // Occluded by the other fullscreen task, so dismiss both.
+ } else if (mSplitTransitions.mPendingRecent == null) {
+ // If split-task is not controlled by recents animation
+ // and occluded by the other fullscreen task, dismiss both.
prepareExitSplitScreen(STAGE_TYPE_UNDEFINED, out);
mSplitTransitions.setDismissTransition(transition,
STAGE_TYPE_UNDEFINED, EXIT_REASON_UNKNOWN);
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/startingsurface/SplashscreenContentDrawer.java b/libs/WindowManager/Shell/src/com/android/wm/shell/startingsurface/SplashscreenContentDrawer.java
index d89ddd2074f0..8cee4f1dc8fb 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/startingsurface/SplashscreenContentDrawer.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/startingsurface/SplashscreenContentDrawer.java
@@ -35,6 +35,8 @@ import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
+import android.content.pm.PackageManager;
+import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
@@ -53,6 +55,7 @@ import android.os.SystemClock;
import android.os.Trace;
import android.os.UserHandle;
import android.util.ArrayMap;
+import android.util.DisplayMetrics;
import android.util.Slog;
import android.view.ContextThemeWrapper;
import android.view.SurfaceControl;
@@ -68,7 +71,6 @@ import com.android.internal.graphics.palette.VariationalKMeansQuantizer;
import com.android.internal.protolog.common.ProtoLog;
import com.android.launcher3.icons.BaseIconFactory;
import com.android.launcher3.icons.IconProvider;
-import com.android.wm.shell.common.ShellExecutor;
import com.android.wm.shell.common.TransactionPool;
import com.android.wm.shell.protolog.ShellProtoLogGroup;
@@ -102,7 +104,7 @@ public class SplashscreenContentDrawer {
*/
private static final float NO_BACKGROUND_SCALE = 192f / 160;
private final Context mContext;
- private final IconProvider mIconProvider;
+ private final HighResIconProvider mHighResIconProvider;
private int mIconSize;
private int mDefaultIconSize;
@@ -115,12 +117,10 @@ public class SplashscreenContentDrawer {
private final Handler mSplashscreenWorkerHandler;
@VisibleForTesting
final ColorCache mColorCache;
- private final ShellExecutor mSplashScreenExecutor;
- SplashscreenContentDrawer(Context context, IconProvider iconProvider, TransactionPool pool,
- ShellExecutor splashScreenExecutor) {
+ SplashscreenContentDrawer(Context context, IconProvider iconProvider, TransactionPool pool) {
mContext = context;
- mIconProvider = iconProvider;
+ mHighResIconProvider = new HighResIconProvider(mContext, iconProvider);
mTransactionPool = pool;
// Initialize Splashscreen worker thread
@@ -131,7 +131,6 @@ public class SplashscreenContentDrawer {
shellSplashscreenWorkerThread.start();
mSplashscreenWorkerHandler = shellSplashscreenWorkerThread.getThreadHandler();
mColorCache = new ColorCache(mContext, mSplashscreenWorkerHandler);
- mSplashScreenExecutor = splashScreenExecutor;
}
/**
@@ -416,18 +415,16 @@ public class SplashscreenContentDrawer {
|| mTmpAttrs.mIconBgColor == mThemeColor) {
mFinalIconSize *= NO_BACKGROUND_SCALE;
}
- createIconDrawable(iconDrawable, false);
+ createIconDrawable(iconDrawable, false /* legacy */, false /* loadInDetail */);
} else {
final float iconScale = (float) mIconSize / (float) mDefaultIconSize;
final int densityDpi = mContext.getResources().getConfiguration().densityDpi;
final int scaledIconDpi =
(int) (0.5f + iconScale * densityDpi * NO_BACKGROUND_SCALE);
Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "getIcon");
- iconDrawable = mIconProvider.getIcon(mActivityInfo, scaledIconDpi);
+ iconDrawable = mHighResIconProvider.getIcon(
+ mActivityInfo, densityDpi, scaledIconDpi);
Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
- if (iconDrawable == null) {
- iconDrawable = mContext.getPackageManager().getDefaultActivityIcon();
- }
if (!processAdaptiveIcon(iconDrawable)) {
ProtoLog.v(ShellProtoLogGroup.WM_SHELL_STARTING_WINDOW,
"The icon is not an AdaptiveIconDrawable");
@@ -437,7 +434,8 @@ public class SplashscreenContentDrawer {
scaledIconDpi, mFinalIconSize);
final Bitmap bitmap = factory.createScaledBitmapWithoutShadow(iconDrawable);
Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
- createIconDrawable(new BitmapDrawable(bitmap), true);
+ createIconDrawable(new BitmapDrawable(bitmap), true,
+ mHighResIconProvider.mLoadInDetail);
}
}
@@ -450,14 +448,16 @@ public class SplashscreenContentDrawer {
}
}
- private void createIconDrawable(Drawable iconDrawable, boolean legacy) {
+ private void createIconDrawable(Drawable iconDrawable, boolean legacy,
+ boolean loadInDetail) {
if (legacy) {
mFinalIconDrawables = SplashscreenIconDrawableFactory.makeLegacyIconDrawable(
- iconDrawable, mDefaultIconSize, mFinalIconSize, mSplashscreenWorkerHandler);
+ iconDrawable, mDefaultIconSize, mFinalIconSize, loadInDetail,
+ mSplashscreenWorkerHandler);
} else {
mFinalIconDrawables = SplashscreenIconDrawableFactory.makeIconDrawable(
mTmpAttrs.mIconBgColor, mThemeColor, iconDrawable, mDefaultIconSize,
- mFinalIconSize, mSplashscreenWorkerHandler);
+ mFinalIconSize, loadInDetail, mSplashscreenWorkerHandler);
}
}
@@ -506,11 +506,11 @@ public class SplashscreenContentDrawer {
// Using AdaptiveIconDrawable here can help keep the shape consistent with the
// current settings.
mFinalIconSize = (int) (0.5f + mIconSize * noBgScale);
- createIconDrawable(iconForeground, false);
+ createIconDrawable(iconForeground, false, mHighResIconProvider.mLoadInDetail);
} else {
ProtoLog.v(ShellProtoLogGroup.WM_SHELL_STARTING_WINDOW,
"processAdaptiveIcon: draw whole icon");
- createIconDrawable(iconDrawable, false);
+ createIconDrawable(iconDrawable, false, mHighResIconProvider.mLoadInDetail);
}
Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
return true;
@@ -1015,4 +1015,77 @@ public class SplashscreenContentDrawer {
playAnimation.run();
}
}
+
+ /**
+ * When loading a BitmapDrawable object with specific density, there will decode the image based
+ * on the density from display metrics, so even when load with higher override density, the
+ * final intrinsic size of a BitmapDrawable can still not big enough to draw on expect size.
+ *
+ * So here we use a standalone IconProvider object to load the Drawable object for higher
+ * density, and the resources object won't affect the entire system.
+ *
+ */
+ private static class HighResIconProvider {
+ private final Context mSharedContext;
+ private final IconProvider mSharedIconProvider;
+ private boolean mLoadInDetail;
+
+ // only create standalone icon provider when the density dpi is low.
+ private Context mStandaloneContext;
+ private IconProvider mStandaloneIconProvider;
+
+ HighResIconProvider(Context context, IconProvider sharedIconProvider) {
+ mSharedContext = context;
+ mSharedIconProvider = sharedIconProvider;
+ }
+
+ Drawable getIcon(ActivityInfo activityInfo, int currentDpi, int iconDpi) {
+ mLoadInDetail = false;
+ Drawable drawable;
+ if (currentDpi < iconDpi && currentDpi < DisplayMetrics.DENSITY_XHIGH) {
+ drawable = loadFromStandalone(activityInfo, currentDpi, iconDpi);
+ } else {
+ drawable = mSharedIconProvider.getIcon(activityInfo, iconDpi);
+ }
+
+ if (drawable == null) {
+ drawable = mSharedContext.getPackageManager().getDefaultActivityIcon();
+ }
+ return drawable;
+ }
+
+ private Drawable loadFromStandalone(ActivityInfo activityInfo, int currentDpi,
+ int iconDpi) {
+ if (mStandaloneContext == null) {
+ final Configuration defConfig = mSharedContext.getResources().getConfiguration();
+ mStandaloneContext = mSharedContext.createConfigurationContext(defConfig);
+ mStandaloneIconProvider = new IconProvider(mStandaloneContext);
+ }
+ Resources resources;
+ try {
+ resources = mStandaloneContext.getPackageManager()
+ .getResourcesForApplication(activityInfo.applicationInfo);
+ } catch (PackageManager.NameNotFoundException | Resources.NotFoundException exc) {
+ resources = null;
+ }
+ if (resources != null) {
+ updateResourcesDpi(resources, iconDpi);
+ }
+ final Drawable drawable = mStandaloneIconProvider.getIcon(activityInfo, iconDpi);
+ mLoadInDetail = true;
+ // reset density dpi
+ if (resources != null) {
+ updateResourcesDpi(resources, currentDpi);
+ }
+ return drawable;
+ }
+
+ private void updateResourcesDpi(Resources resources, int densityDpi) {
+ final Configuration config = resources.getConfiguration();
+ final DisplayMetrics displayMetrics = resources.getDisplayMetrics();
+ config.densityDpi = densityDpi;
+ displayMetrics.densityDpi = densityDpi;
+ resources.updateConfiguration(config, displayMetrics);
+ }
+ }
}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/startingsurface/SplashscreenIconDrawableFactory.java b/libs/WindowManager/Shell/src/com/android/wm/shell/startingsurface/SplashscreenIconDrawableFactory.java
index 5f52071bf950..7f6bfd23f72b 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/startingsurface/SplashscreenIconDrawableFactory.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/startingsurface/SplashscreenIconDrawableFactory.java
@@ -62,7 +62,7 @@ public class SplashscreenIconDrawableFactory {
*/
static Drawable[] makeIconDrawable(@ColorInt int backgroundColor, @ColorInt int themeColor,
@NonNull Drawable foregroundDrawable, int srcIconSize, int iconSize,
- Handler splashscreenWorkerHandler) {
+ boolean loadInDetail, Handler splashscreenWorkerHandler) {
Drawable foreground;
Drawable background = null;
boolean drawBackground =
@@ -74,13 +74,13 @@ public class SplashscreenIconDrawableFactory {
// If the icon is Adaptive, we already use the icon background.
drawBackground = false;
foreground = new ImmobileIconDrawable(foregroundDrawable,
- srcIconSize, iconSize, splashscreenWorkerHandler);
+ srcIconSize, iconSize, loadInDetail, splashscreenWorkerHandler);
} else {
// Adaptive icon don't handle transparency so we draw the background of the adaptive
// icon with the same color as the window background color instead of using two layers
foreground = new ImmobileIconDrawable(
new AdaptiveForegroundDrawable(foregroundDrawable),
- srcIconSize, iconSize, splashscreenWorkerHandler);
+ srcIconSize, iconSize, loadInDetail, splashscreenWorkerHandler);
}
if (drawBackground) {
@@ -91,9 +91,9 @@ public class SplashscreenIconDrawableFactory {
}
static Drawable[] makeLegacyIconDrawable(@NonNull Drawable iconDrawable, int srcIconSize,
- int iconSize, Handler splashscreenWorkerHandler) {
+ int iconSize, boolean loadInDetail, Handler splashscreenWorkerHandler) {
return new Drawable[]{new ImmobileIconDrawable(iconDrawable, srcIconSize, iconSize,
- splashscreenWorkerHandler)};
+ loadInDetail, splashscreenWorkerHandler)};
}
/**
@@ -106,11 +106,16 @@ public class SplashscreenIconDrawableFactory {
private final Matrix mMatrix = new Matrix();
private Bitmap mIconBitmap;
- ImmobileIconDrawable(Drawable drawable, int srcIconSize, int iconSize,
+ ImmobileIconDrawable(Drawable drawable, int srcIconSize, int iconSize, boolean loadInDetail,
Handler splashscreenWorkerHandler) {
- final float scale = (float) iconSize / srcIconSize;
- mMatrix.setScale(scale, scale);
- splashscreenWorkerHandler.post(() -> preDrawIcon(drawable, srcIconSize));
+ // This icon has lower density, don't scale it.
+ if (loadInDetail) {
+ splashscreenWorkerHandler.post(() -> preDrawIcon(drawable, iconSize));
+ } else {
+ final float scale = (float) iconSize / srcIconSize;
+ mMatrix.setScale(scale, scale);
+ splashscreenWorkerHandler.post(() -> preDrawIcon(drawable, srcIconSize));
+ }
}
private void preDrawIcon(Drawable drawable, int size) {
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/startingsurface/StartingSurfaceDrawer.java b/libs/WindowManager/Shell/src/com/android/wm/shell/startingsurface/StartingSurfaceDrawer.java
index 464ab1ae2a8c..54d62edf2570 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/startingsurface/StartingSurfaceDrawer.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/startingsurface/StartingSurfaceDrawer.java
@@ -153,8 +153,7 @@ public class StartingSurfaceDrawer {
mContext = context;
mDisplayManager = mContext.getSystemService(DisplayManager.class);
mSplashScreenExecutor = splashScreenExecutor;
- mSplashscreenContentDrawer = new SplashscreenContentDrawer(mContext, iconProvider, pool,
- mSplashScreenExecutor);
+ mSplashscreenContentDrawer = new SplashscreenContentDrawer(mContext, iconProvider, pool);
mSplashScreenExecutor.execute(() -> mChoreographer = Choreographer.getInstance());
mWindowManagerGlobal = WindowManagerGlobal.getInstance();
mDisplayManager.getDisplay(DEFAULT_DISPLAY);
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/transition/Transitions.java b/libs/WindowManager/Shell/src/com/android/wm/shell/transition/Transitions.java
index 98eee7ba33a0..de0f47fa0a6b 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/transition/Transitions.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/transition/Transitions.java
@@ -23,6 +23,7 @@ import static android.view.WindowManager.TRANSIT_KEYGUARD_GOING_AWAY;
import static android.view.WindowManager.TRANSIT_OPEN;
import static android.view.WindowManager.TRANSIT_TO_BACK;
import static android.view.WindowManager.TRANSIT_TO_FRONT;
+import static android.window.TransitionInfo.FLAG_IS_INPUT_METHOD;
import static android.window.TransitionInfo.FLAG_IS_WALLPAPER;
import static android.window.TransitionInfo.FLAG_STARTING_WINDOW_TRANSFER_RECIPIENT;
@@ -287,12 +288,14 @@ public class Transitions implements RemoteCallable<Transitions> {
finishT.setAlpha(leash, 1.f);
}
} else if (mode == TRANSIT_CLOSE || mode == TRANSIT_TO_BACK) {
- // Wallpaper is a bit of an anomaly: it's visibility is tied to other WindowStates.
- // As a result, we actually can't hide it's WindowToken because there may not be a
- // transition associated with it becoming visible again. Fortunately, since it is
- // always z-ordered to the back, we don't have to worry about it flickering to the
- // front during reparenting, so the hide here isn't necessary for it.
- if ((change.getFlags() & FLAG_IS_WALLPAPER) == 0) {
+ // Wallpaper/IME are anomalies: their visibility is tied to other WindowStates.
+ // As a result, we actually can't hide their WindowTokens because there may not be a
+ // transition associated with them becoming visible again. Fortunately, since
+ // wallpapers are always z-ordered to the back, we don't have to worry about it
+ // flickering to the front during reparenting. Similarly, the IME is reparented to
+ // the associated app, so its visibility is coupled. So, an explicit hide is not
+ // needed visually anyways.
+ if ((change.getFlags() & (FLAG_IS_WALLPAPER | FLAG_IS_INPUT_METHOD)) == 0) {
finishT.hide(leash);
}
}
@@ -309,13 +312,14 @@ public class Transitions implements RemoteCallable<Transitions> {
if (info.getRootLeash().isValid()) {
t.show(info.getRootLeash());
}
+ final int numChanges = info.getChanges().size();
// Put animating stuff above this line and put static stuff below it.
- int zSplitLine = info.getChanges().size();
+ final int zSplitLine = numChanges + 1;
// changes should be ordered top-to-bottom in z
- for (int i = info.getChanges().size() - 1; i >= 0; --i) {
+ for (int i = numChanges - 1; i >= 0; --i) {
final TransitionInfo.Change change = info.getChanges().get(i);
final SurfaceControl leash = change.getLeash();
- final int mode = info.getChanges().get(i).getMode();
+ final int mode = change.getMode();
// Don't reparent anything that isn't independent within its parents
if (!TransitionInfo.isIndependent(change, info)) {
@@ -329,26 +333,31 @@ public class Transitions implements RemoteCallable<Transitions> {
t.setPosition(leash, change.getStartAbsBounds().left - info.getRootOffset().x,
change.getStartAbsBounds().top - info.getRootOffset().y);
}
+ final int layer;
// Put all the OPEN/SHOW on top
- if (mode == TRANSIT_OPEN || mode == TRANSIT_TO_FRONT) {
+ if ((change.getFlags() & FLAG_IS_WALLPAPER) != 0) {
+ // Wallpaper is always at the bottom.
+ layer = 0;
+ } else if (mode == TRANSIT_OPEN || mode == TRANSIT_TO_FRONT) {
if (isOpening) {
// put on top
- t.setLayer(leash, zSplitLine + info.getChanges().size() - i);
+ layer = zSplitLine + numChanges - i;
} else {
// put on bottom
- t.setLayer(leash, zSplitLine - i);
+ layer = zSplitLine - i;
}
} else if (mode == TRANSIT_CLOSE || mode == TRANSIT_TO_BACK) {
if (isOpening) {
// put on bottom and leave visible
- t.setLayer(leash, zSplitLine - i);
+ layer = zSplitLine - i;
} else {
// put on top
- t.setLayer(leash, zSplitLine + info.getChanges().size() - i);
+ layer = zSplitLine + numChanges - i;
}
} else { // CHANGE or other
- t.setLayer(leash, zSplitLine + info.getChanges().size() - i);
+ layer = zSplitLine + numChanges - i;
}
+ t.setLayer(leash, layer);
}
}
@@ -626,8 +635,9 @@ public class Transitions implements RemoteCallable<Transitions> {
if (wct == null) {
wct = new WindowContainerTransaction();
}
- mDisplayController.getChangeController().dispatchOnRotateDisplay(wct,
- change.getDisplayId(), change.getStartRotation(), change.getEndRotation());
+ mDisplayController.getChangeController().dispatchOnDisplayChange(wct,
+ change.getDisplayId(), change.getStartRotation(), change.getEndRotation(),
+ null /* newDisplayAreaInfo */);
}
}
active.mToken = mOrganizer.startTransition(
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/unfold/UnfoldTransitionHandler.java b/libs/WindowManager/Shell/src/com/android/wm/shell/unfold/UnfoldTransitionHandler.java
index af78f2d7d870..8e45e7d36b86 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/unfold/UnfoldTransitionHandler.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/unfold/UnfoldTransitionHandler.java
@@ -127,7 +127,8 @@ public class UnfoldTransitionHandler implements TransitionHandler, UnfoldListene
@Override
public WindowContainerTransaction handleRequest(@NonNull IBinder transition,
@NonNull TransitionRequestInfo request) {
- if (request.getType() == TRANSIT_CHANGE && request.getDisplayChange() != null) {
+ if (request.getType() == TRANSIT_CHANGE && request.getDisplayChange() != null
+ && request.getDisplayChange().isPhysicalDisplayChanged()) {
mTransition = transition;
return new WindowContainerTransaction();
}
diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/apppairs/AppPairsTestCannotPairNonResizeableApps.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/apppairs/AppPairsTestCannotPairNonResizeableApps.kt
deleted file mode 100644
index c9cab39b7d8b..000000000000
--- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/apppairs/AppPairsTestCannotPairNonResizeableApps.kt
+++ /dev/null
@@ -1,115 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.wm.shell.flicker.apppairs
-
-import androidx.test.filters.RequiresDevice
-import com.android.server.wm.flicker.FlickerParametersRunnerFactory
-import com.android.server.wm.flicker.FlickerTestParameter
-import com.android.server.wm.flicker.FlickerTestParameterFactory
-import com.android.server.wm.flicker.annotation.Group1
-import com.android.server.wm.flicker.dsl.FlickerBuilder
-import com.android.wm.shell.flicker.appPairsDividerIsInvisibleAtEnd
-import com.android.wm.shell.flicker.helpers.AppPairsHelper
-import com.android.wm.shell.flicker.helpers.MultiWindowHelper.Companion.resetMultiWindowConfig
-import com.android.wm.shell.flicker.helpers.MultiWindowHelper.Companion.setSupportsNonResizableMultiWindow
-import org.junit.After
-import org.junit.Before
-import org.junit.FixMethodOrder
-import org.junit.Ignore
-import org.junit.Test
-import org.junit.runner.RunWith
-import org.junit.runners.MethodSorters
-import org.junit.runners.Parameterized
-
-/**
- * Test cold launch app from launcher. When the device doesn't support non-resizable in multi window
- * {@link Settings.Global.DEVELOPMENT_ENABLE_NON_RESIZABLE_MULTI_WINDOW}, app pairs should not pair
- * non-resizable apps.
- *
- * To run this test: `atest WMShellFlickerTests:AppPairsTestCannotPairNonResizeableApps`
- */
-@RequiresDevice
-@RunWith(Parameterized::class)
-@Parameterized.UseParametersRunnerFactory(FlickerParametersRunnerFactory::class)
-@FixMethodOrder(MethodSorters.NAME_ASCENDING)
-@Group1
-class AppPairsTestCannotPairNonResizeableApps(
- testSpec: FlickerTestParameter
-) : AppPairsTransition(testSpec) {
-
- override val transition: FlickerBuilder.() -> Unit
- get() = {
- super.transition(this)
- transitions {
- nonResizeableApp?.launchViaIntent(wmHelper)
- // TODO pair apps through normal UX flow
- executeShellCommand(
- composePairsCommand(primaryTaskId, nonResizeableTaskId, pair = true))
- nonResizeableApp?.run { wmHelper.waitForFullScreenApp(nonResizeableApp.component) }
- }
- }
-
- @Before
- override fun setup() {
- super.setup()
- setSupportsNonResizableMultiWindow(instrumentation, -1)
- }
-
- @After
- override fun teardown() {
- super.teardown()
- resetMultiWindowConfig(instrumentation)
- }
-
- @Ignore
- @Test
- override fun navBarLayerRotatesAndScales() = super.navBarLayerRotatesAndScales()
-
- @Ignore
- @Test
- override fun statusBarLayerRotatesScales() = super.statusBarLayerRotatesScales()
-
- @Ignore
- @Test
- override fun navBarLayerIsVisible() = super.navBarLayerIsVisible()
-
- @Ignore
- @Test
- fun appPairsDividerIsInvisibleAtEnd() = testSpec.appPairsDividerIsInvisibleAtEnd()
-
- @Ignore
- @Test
- fun onlyResizeableAppWindowVisible() {
- val nonResizeableApp = nonResizeableApp
- require(nonResizeableApp != null) {
- "Non resizeable app not initialized"
- }
- testSpec.assertWmEnd {
- isAppWindowVisible(nonResizeableApp.component)
- isAppWindowInvisible(primaryApp.component)
- }
- }
-
- companion object {
- @Parameterized.Parameters(name = "{0}")
- @JvmStatic
- fun getParams(): List<FlickerTestParameter> {
- return FlickerTestParameterFactory.getInstance().getConfigNonRotationTests(
- repetitions = AppPairsHelper.TEST_REPETITIONS)
- }
- }
-} \ No newline at end of file
diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/apppairs/AppPairsTestPairPrimaryAndSecondaryApps.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/apppairs/AppPairsTestPairPrimaryAndSecondaryApps.kt
deleted file mode 100644
index 60c32c99d1ff..000000000000
--- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/apppairs/AppPairsTestPairPrimaryAndSecondaryApps.kt
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.wm.shell.flicker.apppairs
-
-import androidx.test.filters.RequiresDevice
-import com.android.server.wm.flicker.FlickerParametersRunnerFactory
-import com.android.server.wm.flicker.FlickerTestParameter
-import com.android.server.wm.flicker.FlickerTestParameterFactory
-import com.android.server.wm.flicker.annotation.Group1
-import com.android.server.wm.flicker.dsl.FlickerBuilder
-import com.android.wm.shell.flicker.APP_PAIR_SPLIT_DIVIDER_COMPONENT
-import com.android.wm.shell.flicker.appPairsDividerIsVisibleAtEnd
-import com.android.wm.shell.flicker.helpers.AppPairsHelper
-import com.android.wm.shell.flicker.helpers.AppPairsHelper.Companion.waitAppsShown
-import org.junit.FixMethodOrder
-import org.junit.Ignore
-import org.junit.Test
-import org.junit.runner.RunWith
-import org.junit.runners.MethodSorters
-import org.junit.runners.Parameterized
-
-/**
- * Test cold launch app from launcher.
- * To run this test: `atest WMShellFlickerTests:AppPairsTestPairPrimaryAndSecondaryApps`
- */
-@RequiresDevice
-@RunWith(Parameterized::class)
-@Parameterized.UseParametersRunnerFactory(FlickerParametersRunnerFactory::class)
-@FixMethodOrder(MethodSorters.NAME_ASCENDING)
-@Group1
-class AppPairsTestPairPrimaryAndSecondaryApps(
- testSpec: FlickerTestParameter
-) : AppPairsTransition(testSpec) {
- override val transition: FlickerBuilder.() -> Unit
- get() = {
- super.transition(this)
- transitions {
- // TODO pair apps through normal UX flow
- executeShellCommand(
- composePairsCommand(primaryTaskId, secondaryTaskId, pair = true))
- waitAppsShown(primaryApp, secondaryApp)
- }
- }
-
- @Ignore
- @Test
- override fun navBarLayerIsVisible() = super.navBarLayerIsVisible()
-
- @Ignore
- @Test
- override fun navBarLayerRotatesAndScales() = super.navBarLayerRotatesAndScales()
-
- @Ignore
- @Test
- override fun statusBarLayerRotatesScales() = super.statusBarLayerRotatesScales()
-
- @Ignore
- @Test
- fun appPairsDividerIsVisibleAtEnd() = testSpec.appPairsDividerIsVisibleAtEnd()
-
- @Ignore
- @Test
- fun bothAppWindowsVisible() {
- testSpec.assertWmEnd {
- isAppWindowVisible(primaryApp.component)
- isAppWindowVisible(secondaryApp.component)
- }
- }
-
- @Ignore
- @Test
- fun appsEndingBounds() {
- testSpec.assertLayersEnd {
- val dividerRegion = layer(APP_PAIR_SPLIT_DIVIDER_COMPONENT).visibleRegion.region
- visibleRegion(primaryApp.component)
- .coversExactly(appPairsHelper.getPrimaryBounds(dividerRegion))
- visibleRegion(secondaryApp.component)
- .coversExactly(appPairsHelper.getSecondaryBounds(dividerRegion))
- }
- }
-
- companion object {
- @Parameterized.Parameters(name = "{0}")
- @JvmStatic
- fun getParams(): List<FlickerTestParameter> {
- return FlickerTestParameterFactory.getInstance().getConfigNonRotationTests(
- repetitions = AppPairsHelper.TEST_REPETITIONS)
- }
- }
-}
diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/apppairs/AppPairsTestSupportPairNonResizeableApps.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/apppairs/AppPairsTestSupportPairNonResizeableApps.kt
deleted file mode 100644
index 24869a802167..000000000000
--- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/apppairs/AppPairsTestSupportPairNonResizeableApps.kt
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.wm.shell.flicker.apppairs
-
-import android.view.Display
-import androidx.test.filters.RequiresDevice
-import com.android.server.wm.flicker.FlickerParametersRunnerFactory
-import com.android.server.wm.flicker.FlickerTestParameter
-import com.android.server.wm.flicker.FlickerTestParameterFactory
-import com.android.server.wm.flicker.annotation.Group1
-import com.android.server.wm.flicker.dsl.FlickerBuilder
-import com.android.server.wm.traces.common.WindowManagerConditionsFactory
-import com.android.wm.shell.flicker.appPairsDividerIsVisibleAtEnd
-import com.android.wm.shell.flicker.helpers.AppPairsHelper
-import com.android.wm.shell.flicker.helpers.MultiWindowHelper.Companion.resetMultiWindowConfig
-import com.android.wm.shell.flicker.helpers.MultiWindowHelper.Companion.setSupportsNonResizableMultiWindow
-import org.junit.After
-import org.junit.Before
-import org.junit.FixMethodOrder
-import org.junit.Ignore
-import org.junit.Test
-import org.junit.runner.RunWith
-import org.junit.runners.MethodSorters
-import org.junit.runners.Parameterized
-
-/**
- * Test cold launch app from launcher. When the device supports non-resizable in multi window
- * {@link Settings.Global.DEVELOPMENT_ENABLE_NON_RESIZABLE_MULTI_WINDOW}, app pairs can pair
- * non-resizable apps.
- *
- * To run this test: `atest WMShellFlickerTests:AppPairsTestSupportPairNonResizeableApps`
- */
-@RequiresDevice
-@RunWith(Parameterized::class)
-@Parameterized.UseParametersRunnerFactory(FlickerParametersRunnerFactory::class)
-@FixMethodOrder(MethodSorters.NAME_ASCENDING)
-@Group1
-class AppPairsTestSupportPairNonResizeableApps(
- testSpec: FlickerTestParameter
-) : AppPairsTransition(testSpec) {
-
- override val transition: FlickerBuilder.() -> Unit
- get() = {
- super.transition(this)
- transitions {
- nonResizeableApp?.launchViaIntent(wmHelper)
- // TODO pair apps through normal UX flow
- executeShellCommand(
- composePairsCommand(primaryTaskId, nonResizeableTaskId, pair = true))
- val waitConditions = mutableListOf(
- WindowManagerConditionsFactory.isWindowVisible(primaryApp.component),
- WindowManagerConditionsFactory.isLayerVisible(primaryApp.component),
- WindowManagerConditionsFactory.isAppTransitionIdle(Display.DEFAULT_DISPLAY))
-
- nonResizeableApp?.let {
- waitConditions.add(
- WindowManagerConditionsFactory.isWindowVisible(nonResizeableApp.component))
- waitConditions.add(
- WindowManagerConditionsFactory.isLayerVisible(nonResizeableApp.component))
- }
- wmHelper.waitFor(*waitConditions.toTypedArray())
- }
- }
-
- @Before
- override fun setup() {
- super.setup()
- setSupportsNonResizableMultiWindow(instrumentation, 1)
- }
-
- @After
- override fun teardown() {
- super.teardown()
- resetMultiWindowConfig(instrumentation)
- }
-
- @Ignore
- @Test
- override fun navBarLayerIsVisible() = super.navBarLayerIsVisible()
-
- @Ignore
- @Test
- override fun navBarLayerRotatesAndScales() = super.navBarLayerRotatesAndScales()
-
- @Ignore
- @Test
- override fun statusBarLayerRotatesScales() = super.statusBarLayerRotatesScales()
-
- @Ignore
- @Test
- fun appPairsDividerIsVisibleAtEnd() = testSpec.appPairsDividerIsVisibleAtEnd()
-
- @Ignore
- @Test
- fun bothAppWindowVisible() {
- val nonResizeableApp = nonResizeableApp
- require(nonResizeableApp != null) {
- "Non resizeable app not initialized"
- }
- testSpec.assertWmEnd {
- isAppWindowVisible(nonResizeableApp.component)
- isAppWindowVisible(primaryApp.component)
- }
- }
-
- companion object {
- @Parameterized.Parameters(name = "{0}")
- @JvmStatic
- fun getParams(): List<FlickerTestParameter> {
- return FlickerTestParameterFactory.getInstance().getConfigNonRotationTests(
- repetitions = AppPairsHelper.TEST_REPETITIONS)
- }
- }
-} \ No newline at end of file
diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/apppairs/AppPairsTestUnpairPrimaryAndSecondaryApps.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/apppairs/AppPairsTestUnpairPrimaryAndSecondaryApps.kt
deleted file mode 100644
index 007415d19860..000000000000
--- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/apppairs/AppPairsTestUnpairPrimaryAndSecondaryApps.kt
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.wm.shell.flicker.apppairs
-
-import android.os.SystemClock
-import androidx.test.filters.RequiresDevice
-import com.android.server.wm.flicker.FlickerParametersRunnerFactory
-import com.android.server.wm.flicker.FlickerTestParameter
-import com.android.server.wm.flicker.FlickerTestParameterFactory
-import com.android.server.wm.flicker.annotation.Group1
-import com.android.server.wm.flicker.dsl.FlickerBuilder
-import com.android.wm.shell.flicker.APP_PAIR_SPLIT_DIVIDER_COMPONENT
-import com.android.wm.shell.flicker.appPairsDividerIsInvisibleAtEnd
-import com.android.wm.shell.flicker.helpers.AppPairsHelper
-import com.android.wm.shell.flicker.helpers.AppPairsHelper.Companion.waitAppsShown
-import org.junit.FixMethodOrder
-import org.junit.Ignore
-import org.junit.Test
-import org.junit.runner.RunWith
-import org.junit.runners.MethodSorters
-import org.junit.runners.Parameterized
-
-/**
- * Test cold launch app from launcher.
- * To run this test: `atest WMShellFlickerTests:AppPairsTestUnpairPrimaryAndSecondaryApps`
- */
-@RequiresDevice
-@RunWith(Parameterized::class)
-@Parameterized.UseParametersRunnerFactory(FlickerParametersRunnerFactory::class)
-@FixMethodOrder(MethodSorters.NAME_ASCENDING)
-@Group1
-class AppPairsTestUnpairPrimaryAndSecondaryApps(
- testSpec: FlickerTestParameter
-) : AppPairsTransition(testSpec) {
- override val transition: FlickerBuilder.() -> Unit
- get() = {
- super.transition(this)
- setup {
- eachRun {
- executeShellCommand(
- composePairsCommand(primaryTaskId, secondaryTaskId, pair = true))
- waitAppsShown(primaryApp, secondaryApp)
- }
- }
- transitions {
- // TODO pair apps through normal UX flow
- executeShellCommand(
- composePairsCommand(primaryTaskId, secondaryTaskId, pair = false))
- SystemClock.sleep(AppPairsHelper.TIMEOUT_MS)
- }
- }
-
- @Ignore
- @Test
- override fun navBarLayerRotatesAndScales() = super.navBarLayerRotatesAndScales()
-
- @Ignore
- @Test
- override fun statusBarLayerRotatesScales() = super.statusBarLayerRotatesScales()
-
- @Ignore
- @Test
- fun appPairsDividerIsInvisibleAtEnd() = testSpec.appPairsDividerIsInvisibleAtEnd()
-
- @Ignore
- @Test
- fun bothAppWindowsInvisible() {
- testSpec.assertWmEnd {
- isAppWindowInvisible(primaryApp.component)
- isAppWindowInvisible(secondaryApp.component)
- }
- }
-
- @Ignore
- @Test
- fun appsStartingBounds() {
- testSpec.assertLayersStart {
- val dividerRegion = layer(APP_PAIR_SPLIT_DIVIDER_COMPONENT).visibleRegion.region
- visibleRegion(primaryApp.component)
- .coversExactly(appPairsHelper.getPrimaryBounds(dividerRegion))
- visibleRegion(secondaryApp.component)
- .coversExactly(appPairsHelper.getSecondaryBounds(dividerRegion))
- }
- }
-
- @Ignore
- @Test
- fun appsEndingBounds() {
- testSpec.assertLayersEnd {
- notContains(primaryApp.component)
- notContains(secondaryApp.component)
- }
- }
-
- @Ignore
- @Test
- override fun navBarLayerIsVisible() = super.navBarLayerIsVisible()
-
- companion object {
- @Parameterized.Parameters(name = "{0}")
- @JvmStatic
- fun getParams(): List<FlickerTestParameter> {
- return FlickerTestParameterFactory.getInstance().getConfigNonRotationTests(
- repetitions = AppPairsHelper.TEST_REPETITIONS)
- }
- }
-}
diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/apppairs/AppPairsTransition.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/apppairs/AppPairsTransition.kt
deleted file mode 100644
index 3e17948b4a84..000000000000
--- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/apppairs/AppPairsTransition.kt
+++ /dev/null
@@ -1,178 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.wm.shell.flicker.apppairs
-
-import android.app.Instrumentation
-import android.content.Context
-import android.system.helpers.ActivityHelper
-import androidx.test.platform.app.InstrumentationRegistry
-import com.android.server.wm.flicker.FlickerBuilderProvider
-import com.android.server.wm.flicker.FlickerTestParameter
-import com.android.server.wm.flicker.dsl.FlickerBuilder
-import com.android.server.wm.flicker.helpers.setRotation
-import com.android.server.wm.flicker.helpers.wakeUpAndGoToHomeScreen
-import com.android.server.wm.flicker.navBarLayerIsVisible
-import com.android.server.wm.flicker.navBarLayerRotatesAndScales
-import com.android.server.wm.flicker.navBarWindowIsVisible
-import com.android.server.wm.flicker.statusBarLayerIsVisible
-import com.android.server.wm.flicker.statusBarLayerRotatesScales
-import com.android.server.wm.flicker.statusBarWindowIsVisible
-import com.android.server.wm.traces.parser.toFlickerComponent
-import com.android.wm.shell.flicker.helpers.AppPairsHelper
-import com.android.wm.shell.flicker.helpers.BaseAppHelper
-import com.android.wm.shell.flicker.helpers.MultiWindowHelper.Companion.getDevEnableNonResizableMultiWindow
-import com.android.wm.shell.flicker.helpers.MultiWindowHelper.Companion.setDevEnableNonResizableMultiWindow
-import com.android.wm.shell.flicker.helpers.SplitScreenHelper
-import com.android.wm.shell.flicker.testapp.Components
-import org.junit.After
-import org.junit.Before
-import org.junit.Ignore
-import org.junit.Test
-
-abstract class AppPairsTransition(protected val testSpec: FlickerTestParameter) {
- protected val instrumentation: Instrumentation = InstrumentationRegistry.getInstrumentation()
- protected val context: Context = instrumentation.context
- protected val activityHelper = ActivityHelper.getInstance()
- protected val appPairsHelper = AppPairsHelper(instrumentation,
- Components.SplitScreenActivity.LABEL,
- Components.SplitScreenActivity.COMPONENT.toFlickerComponent())
-
- protected val primaryApp = SplitScreenHelper.getPrimary(instrumentation)
- protected val secondaryApp = SplitScreenHelper.getSecondary(instrumentation)
- protected open val nonResizeableApp: SplitScreenHelper? =
- SplitScreenHelper.getNonResizeable(instrumentation)
- protected var primaryTaskId = ""
- protected var secondaryTaskId = ""
- protected var nonResizeableTaskId = ""
- private var prevDevEnableNonResizableMultiWindow = 0
-
- @Before
- open fun setup() {
- prevDevEnableNonResizableMultiWindow = getDevEnableNonResizableMultiWindow(context)
- if (prevDevEnableNonResizableMultiWindow != 0) {
- // Turn off the development option
- setDevEnableNonResizableMultiWindow(context, 0)
- }
- }
-
- @After
- open fun teardown() {
- setDevEnableNonResizableMultiWindow(context, prevDevEnableNonResizableMultiWindow)
- }
-
- @FlickerBuilderProvider
- fun buildFlicker(): FlickerBuilder {
- return FlickerBuilder(instrumentation).apply {
- transition(this)
- }
- }
-
- internal open val transition: FlickerBuilder.() -> Unit
- get() = {
- setup {
- test {
- device.wakeUpAndGoToHomeScreen()
- }
- eachRun {
- this.setRotation(testSpec.startRotation)
- primaryApp.launchViaIntent(wmHelper)
- secondaryApp.launchViaIntent(wmHelper)
- nonResizeableApp?.launchViaIntent(wmHelper)
- updateTasksId()
- }
- }
- teardown {
- eachRun {
- executeShellCommand(composePairsCommand(
- primaryTaskId, secondaryTaskId, pair = false))
- executeShellCommand(composePairsCommand(
- primaryTaskId, nonResizeableTaskId, pair = false))
- primaryApp.exit(wmHelper)
- secondaryApp.exit(wmHelper)
- nonResizeableApp?.exit(wmHelper)
- }
- }
- }
-
- protected fun updateTasksId() {
- primaryTaskId = getTaskIdForActivity(
- primaryApp.component.packageName, primaryApp.component.className).toString()
- secondaryTaskId = getTaskIdForActivity(
- secondaryApp.component.packageName, secondaryApp.component.className).toString()
- val nonResizeableApp = nonResizeableApp
- if (nonResizeableApp != null) {
- nonResizeableTaskId = getTaskIdForActivity(
- nonResizeableApp.component.packageName,
- nonResizeableApp.component.className).toString()
- }
- }
-
- private fun getTaskIdForActivity(pkgName: String, activityName: String): Int {
- return activityHelper.getTaskIdForActivity(pkgName, activityName)
- }
-
- internal fun executeShellCommand(cmd: String) {
- BaseAppHelper.executeShellCommand(instrumentation, cmd)
- }
-
- internal fun composePairsCommand(
- primaryApp: String,
- secondaryApp: String,
- pair: Boolean
- ): String = buildString {
- // dumpsys activity service SystemUIService WMShell {pair|unpair} ${TASK_ID_1} ${TASK_ID_2}
- append("dumpsys activity service SystemUIService WMShell ")
- if (pair) {
- append("pair ")
- } else {
- append("unpair ")
- }
- append("$primaryApp $secondaryApp")
- }
-
- @Ignore
- @Test
- open fun navBarLayerIsVisible() {
- testSpec.navBarLayerIsVisible()
- }
-
- @Ignore
- @Test
- open fun statusBarLayerIsVisible() {
- testSpec.statusBarLayerIsVisible()
- }
-
- @Ignore
- @Test
- open fun navBarWindowIsVisible() {
- testSpec.navBarWindowIsVisible()
- }
-
- @Ignore
- @Test
- open fun statusBarWindowIsVisible() {
- testSpec.statusBarWindowIsVisible()
- }
-
- @Ignore
- @Test
- open fun navBarLayerRotatesAndScales() = testSpec.navBarLayerRotatesAndScales()
-
- @Ignore
- @Test
- open fun statusBarLayerRotatesScales() = testSpec.statusBarLayerRotatesScales()
-} \ No newline at end of file
diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/apppairs/OWNERS b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/apppairs/OWNERS
deleted file mode 100644
index 8446b37dbf06..000000000000
--- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/apppairs/OWNERS
+++ /dev/null
@@ -1,2 +0,0 @@
-# window manager > wm shell > Split Screen
-# Bug component: 928697
diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/apppairs/RotateTwoLaunchedAppsInAppPairsMode.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/apppairs/RotateTwoLaunchedAppsInAppPairsMode.kt
deleted file mode 100644
index b0c3ba20d948..000000000000
--- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/apppairs/RotateTwoLaunchedAppsInAppPairsMode.kt
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.wm.shell.flicker.apppairs
-
-import android.view.Surface
-import androidx.test.filters.RequiresDevice
-import com.android.server.wm.flicker.FlickerParametersRunnerFactory
-import com.android.server.wm.flicker.FlickerTestParameter
-import com.android.server.wm.flicker.FlickerTestParameterFactory
-import com.android.server.wm.flicker.annotation.Group1
-import com.android.server.wm.flicker.dsl.FlickerBuilder
-import com.android.server.wm.flicker.helpers.setRotation
-import com.android.wm.shell.flicker.appPairsDividerIsVisibleAtEnd
-import com.android.wm.shell.flicker.appPairsPrimaryBoundsIsVisibleAtEnd
-import com.android.wm.shell.flicker.appPairsSecondaryBoundsIsVisibleAtEnd
-import com.android.wm.shell.flicker.helpers.AppPairsHelper.Companion.waitAppsShown
-import com.android.wm.shell.flicker.helpers.SplitScreenHelper
-import org.junit.FixMethodOrder
-import org.junit.Ignore
-import org.junit.Test
-import org.junit.runner.RunWith
-import org.junit.runners.MethodSorters
-import org.junit.runners.Parameterized
-
-/**
- * Test open apps to app pairs and rotate.
- * To run this test: `atest WMShellFlickerTests:RotateTwoLaunchedAppsInAppPairsMode`
- */
-@RequiresDevice
-@RunWith(Parameterized::class)
-@Parameterized.UseParametersRunnerFactory(FlickerParametersRunnerFactory::class)
-@FixMethodOrder(MethodSorters.NAME_ASCENDING)
-@Group1
-class RotateTwoLaunchedAppsInAppPairsMode(
- testSpec: FlickerTestParameter
-) : RotateTwoLaunchedAppsTransition(testSpec) {
- override val transition: FlickerBuilder.() -> Unit
- get() = {
- super.transition(this)
- transitions {
- executeShellCommand(composePairsCommand(
- primaryTaskId, secondaryTaskId, true /* pair */))
- waitAppsShown(primaryApp, secondaryApp)
- setRotation(testSpec.endRotation)
- }
- }
-
- @Ignore
- @Test
- override fun navBarLayerIsVisible() = super.navBarLayerIsVisible()
-
- @Ignore
- @Test
- override fun statusBarLayerIsVisible() = super.statusBarLayerIsVisible()
-
- @Ignore
- @Test
- fun bothAppWindowsVisible() {
- testSpec.assertWmEnd {
- isAppWindowVisible(primaryApp.component)
- isAppWindowVisible(secondaryApp.component)
- }
- }
-
- @Ignore
- @Test
- fun appPairsDividerIsVisibleAtEnd() = testSpec.appPairsDividerIsVisibleAtEnd()
-
- @Ignore
- @Test
- fun appPairsPrimaryBoundsIsVisibleAtEnd() =
- testSpec.appPairsPrimaryBoundsIsVisibleAtEnd(testSpec.endRotation,
- primaryApp.component)
-
- @Ignore
- @Test
- fun appPairsSecondaryBoundsIsVisibleAtEnd() =
- testSpec.appPairsSecondaryBoundsIsVisibleAtEnd(testSpec.endRotation,
- secondaryApp.component)
-
- @Ignore
- @Test
- override fun statusBarLayerRotatesScales() = super.statusBarLayerRotatesScales()
-
- companion object {
- @Parameterized.Parameters(name = "{0}")
- @JvmStatic
- fun getParams(): Collection<FlickerTestParameter> {
- return FlickerTestParameterFactory.getInstance().getConfigNonRotationTests(
- repetitions = SplitScreenHelper.TEST_REPETITIONS,
- supportedRotations = listOf(Surface.ROTATION_90, Surface.ROTATION_270)
- )
- }
- }
-} \ No newline at end of file
diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/apppairs/RotateTwoLaunchedAppsRotateAndEnterAppPairsMode.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/apppairs/RotateTwoLaunchedAppsRotateAndEnterAppPairsMode.kt
deleted file mode 100644
index ae56c7732a4d..000000000000
--- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/apppairs/RotateTwoLaunchedAppsRotateAndEnterAppPairsMode.kt
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.wm.shell.flicker.apppairs
-
-import android.view.Surface
-import androidx.test.filters.RequiresDevice
-import com.android.server.wm.flicker.FlickerParametersRunnerFactory
-import com.android.server.wm.flicker.FlickerTestParameter
-import com.android.server.wm.flicker.FlickerTestParameterFactory
-import com.android.server.wm.flicker.annotation.Group1
-import com.android.server.wm.flicker.dsl.FlickerBuilder
-import com.android.server.wm.flicker.helpers.setRotation
-import com.android.wm.shell.flicker.appPairsDividerIsVisibleAtEnd
-import com.android.wm.shell.flicker.appPairsPrimaryBoundsIsVisibleAtEnd
-import com.android.wm.shell.flicker.appPairsSecondaryBoundsIsVisibleAtEnd
-import com.android.wm.shell.flicker.helpers.AppPairsHelper.Companion.waitAppsShown
-import com.android.wm.shell.flicker.helpers.SplitScreenHelper
-import org.junit.FixMethodOrder
-import org.junit.Ignore
-import org.junit.Test
-import org.junit.runner.RunWith
-import org.junit.runners.MethodSorters
-import org.junit.runners.Parameterized
-
-/**
- * Test open apps to app pairs and rotate.
- * To run this test: `atest WMShellFlickerTests:RotateTwoLaunchedAppsRotateAndEnterAppPairsMode`
- */
-@RequiresDevice
-@RunWith(Parameterized::class)
-@Parameterized.UseParametersRunnerFactory(FlickerParametersRunnerFactory::class)
-@FixMethodOrder(MethodSorters.NAME_ASCENDING)
-@Group1
-class RotateTwoLaunchedAppsRotateAndEnterAppPairsMode(
- testSpec: FlickerTestParameter
-) : RotateTwoLaunchedAppsTransition(testSpec) {
- override val transition: FlickerBuilder.() -> Unit
- get() = {
- super.transition(this)
- transitions {
- this.setRotation(testSpec.endRotation)
- executeShellCommand(
- composePairsCommand(primaryTaskId, secondaryTaskId, pair = true))
- waitAppsShown(primaryApp, secondaryApp)
- }
- }
-
- @Ignore
- @Test
- fun appPairsDividerIsVisibleAtEnd() = testSpec.appPairsDividerIsVisibleAtEnd()
-
- @Ignore
- @Test
- override fun navBarWindowIsVisible() = super.navBarWindowIsVisible()
-
- @Ignore
- @Test
- override fun navBarLayerIsVisible() = super.navBarLayerIsVisible()
-
- @Ignore
- @Test
- override fun statusBarWindowIsVisible() = super.statusBarWindowIsVisible()
-
- @Ignore
- @Test
- override fun statusBarLayerIsVisible() = super.statusBarLayerIsVisible()
-
- @Ignore
- @Test
- override fun statusBarLayerRotatesScales() = super.statusBarLayerRotatesScales()
-
- @Ignore
- @Test
- fun bothAppWindowsVisible() {
- testSpec.assertWmEnd {
- isAppWindowVisible(primaryApp.component)
- isAppWindowVisible(secondaryApp.component)
- }
- }
-
- @Ignore
- @Test
- fun appPairsPrimaryBoundsIsVisibleAtEnd() =
- testSpec.appPairsPrimaryBoundsIsVisibleAtEnd(testSpec.endRotation,
- primaryApp.component)
-
- @Ignore
- @Test
- fun appPairsSecondaryBoundsIsVisibleAtEnd() =
- testSpec.appPairsSecondaryBoundsIsVisibleAtEnd(testSpec.endRotation,
- secondaryApp.component)
-
- companion object {
- @Parameterized.Parameters(name = "{0}")
- @JvmStatic
- fun getParams(): Collection<FlickerTestParameter> {
- return FlickerTestParameterFactory.getInstance().getConfigNonRotationTests(
- repetitions = SplitScreenHelper.TEST_REPETITIONS,
- supportedRotations = listOf(Surface.ROTATION_90, Surface.ROTATION_270)
- )
- }
- }
-}
diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/apppairs/RotateTwoLaunchedAppsTransition.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/apppairs/RotateTwoLaunchedAppsTransition.kt
deleted file mode 100644
index b1f1c9e539df..000000000000
--- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/apppairs/RotateTwoLaunchedAppsTransition.kt
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.wm.shell.flicker.apppairs
-
-import android.view.Surface
-import com.android.server.wm.flicker.FlickerTestParameter
-import com.android.server.wm.flicker.dsl.FlickerBuilder
-import com.android.server.wm.flicker.helpers.setRotation
-import com.android.server.wm.flicker.helpers.wakeUpAndGoToHomeScreen
-import com.android.wm.shell.flicker.helpers.BaseAppHelper.Companion.isShellTransitionsEnabled
-import com.android.wm.shell.flicker.helpers.SplitScreenHelper
-import org.junit.Assume.assumeFalse
-import org.junit.Before
-import org.junit.Ignore
-import org.junit.Test
-
-abstract class RotateTwoLaunchedAppsTransition(
- testSpec: FlickerTestParameter
-) : AppPairsTransition(testSpec) {
- override val nonResizeableApp: SplitScreenHelper?
- get() = null
-
- override val transition: FlickerBuilder.() -> Unit
- get() = {
- setup {
- test {
- device.wakeUpAndGoToHomeScreen()
- this.setRotation(Surface.ROTATION_0)
- primaryApp.launchViaIntent(wmHelper)
- secondaryApp.launchViaIntent(wmHelper)
- updateTasksId()
- }
- }
- teardown {
- eachRun {
- executeShellCommand(composePairsCommand(
- primaryTaskId, secondaryTaskId, pair = false))
- primaryApp.exit(wmHelper)
- secondaryApp.exit(wmHelper)
- }
- }
- }
-
- @Before
- override fun setup() {
- // AppPairs hasn't been updated to Shell Transition. There will be conflict on rotation.
- assumeFalse(isShellTransitionsEnabled())
- super.setup()
- }
-
- @Ignore
- @Test
- override fun navBarLayerIsVisible() {
- super.navBarLayerIsVisible()
- }
-
- @Ignore
- @Test
- override fun navBarLayerRotatesAndScales() {
- super.navBarLayerRotatesAndScales()
- }
-} \ No newline at end of file
diff --git a/libs/WindowManager/Shell/tests/unittest/Android.bp b/libs/WindowManager/Shell/tests/unittest/Android.bp
index a899709c1405..ea10be564351 100644
--- a/libs/WindowManager/Shell/tests/unittest/Android.bp
+++ b/libs/WindowManager/Shell/tests/unittest/Android.bp
@@ -37,6 +37,7 @@ android_test {
"androidx.test.ext.junit",
"androidx.dynamicanimation_dynamicanimation",
"dagger2",
+ "frameworks-base-testutils",
"kotlinx-coroutines-android",
"kotlinx-coroutines-core",
"mockito-target-extended-minus-junit4",
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/apppairs/AppPairTests.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/apppairs/AppPairTests.java
deleted file mode 100644
index e73d9aaf190a..000000000000
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/apppairs/AppPairTests.java
+++ /dev/null
@@ -1,123 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.wm.shell.apppairs;
-
-import static android.view.Display.DEFAULT_DISPLAY;
-
-import static com.android.dx.mockito.inline.extended.ExtendedMockito.spyOn;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import static org.mockito.ArgumentMatchers.anyInt;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-import android.app.ActivityManager;
-import android.hardware.display.DisplayManager;
-
-import androidx.test.annotation.UiThreadTest;
-import androidx.test.ext.junit.runners.AndroidJUnit4;
-import androidx.test.filters.SmallTest;
-
-import com.android.wm.shell.ShellTaskOrganizer;
-import com.android.wm.shell.ShellTestCase;
-import com.android.wm.shell.TestRunningTaskInfoBuilder;
-import com.android.wm.shell.common.DisplayController;
-import com.android.wm.shell.common.SyncTransactionQueue;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-/**
- * Tests for {@link AppPair}
- * Build/Install/Run:
- * atest WMShellUnitTests:AppPairTests
- */
-@SmallTest
-@RunWith(AndroidJUnit4.class)
-public class AppPairTests extends ShellTestCase {
-
- private AppPairsController mController;
- @Mock private SyncTransactionQueue mSyncQueue;
- @Mock private ShellTaskOrganizer mTaskOrganizer;
- @Mock private DisplayController mDisplayController;
-
- @Before
- public void setUp() {
- MockitoAnnotations.initMocks(this);
- when(mDisplayController.getDisplayContext(anyInt())).thenReturn(mContext);
- when(mDisplayController.getDisplay(anyInt())).thenReturn(
- mContext.getSystemService(DisplayManager.class).getDisplay(DEFAULT_DISPLAY));
- mController = new TestAppPairsController(
- mTaskOrganizer,
- mSyncQueue,
- mDisplayController);
- spyOn(mController);
- }
-
- @After
- public void tearDown() {}
-
- @Test
- @UiThreadTest
- public void testContains() {
- final ActivityManager.RunningTaskInfo task1 = new TestRunningTaskInfoBuilder().build();
- final ActivityManager.RunningTaskInfo task2 = new TestRunningTaskInfoBuilder().build();
-
- final AppPair pair = mController.pairInner(task1, task2);
- assertThat(pair.contains(task1.taskId)).isTrue();
- assertThat(pair.contains(task2.taskId)).isTrue();
-
- pair.unpair();
- assertThat(pair.contains(task1.taskId)).isFalse();
- assertThat(pair.contains(task2.taskId)).isFalse();
- }
-
- @Test
- @UiThreadTest
- public void testVanishUnpairs() {
- final ActivityManager.RunningTaskInfo task1 = new TestRunningTaskInfoBuilder().build();
- final ActivityManager.RunningTaskInfo task2 = new TestRunningTaskInfoBuilder().build();
-
- final AppPair pair = mController.pairInner(task1, task2);
- assertThat(pair.contains(task1.taskId)).isTrue();
- assertThat(pair.contains(task2.taskId)).isTrue();
-
- pair.onTaskVanished(task1);
- assertThat(pair.contains(task1.taskId)).isFalse();
- assertThat(pair.contains(task2.taskId)).isFalse();
- }
-
- @Test
- @UiThreadTest
- public void testOnTaskInfoChanged_notSupportsMultiWindow() {
- final ActivityManager.RunningTaskInfo task1 = new TestRunningTaskInfoBuilder().build();
- final ActivityManager.RunningTaskInfo task2 = new TestRunningTaskInfoBuilder().build();
-
- final AppPair pair = mController.pairInner(task1, task2);
- assertThat(pair.contains(task1.taskId)).isTrue();
- assertThat(pair.contains(task2.taskId)).isTrue();
-
- task1.supportsMultiWindow = false;
- pair.onTaskInfoChanged(task1);
- verify(mController).unpair(pair.getRootTaskId());
- }
-}
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/apppairs/AppPairsControllerTests.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/apppairs/AppPairsControllerTests.java
deleted file mode 100644
index 505c153eff9c..000000000000
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/apppairs/AppPairsControllerTests.java
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.wm.shell.apppairs;
-
-import static android.view.Display.DEFAULT_DISPLAY;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import static org.mockito.ArgumentMatchers.anyInt;
-import static org.mockito.Mockito.when;
-
-import android.app.ActivityManager;
-import android.hardware.display.DisplayManager;
-
-import androidx.test.annotation.UiThreadTest;
-import androidx.test.ext.junit.runners.AndroidJUnit4;
-import androidx.test.filters.SmallTest;
-
-import com.android.wm.shell.ShellTaskOrganizer;
-import com.android.wm.shell.ShellTestCase;
-import com.android.wm.shell.TestRunningTaskInfoBuilder;
-import com.android.wm.shell.common.DisplayController;
-import com.android.wm.shell.common.SyncTransactionQueue;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-/** Tests for {@link AppPairsController} */
-@SmallTest
-@RunWith(AndroidJUnit4.class)
-public class AppPairsControllerTests extends ShellTestCase {
- private TestAppPairsController mController;
- private TestAppPairsPool mPool;
- @Mock private SyncTransactionQueue mSyncQueue;
- @Mock private ShellTaskOrganizer mTaskOrganizer;
- @Mock private DisplayController mDisplayController;
-
- @Before
- public void setUp() {
- MockitoAnnotations.initMocks(this);
- when(mDisplayController.getDisplayContext(anyInt())).thenReturn(mContext);
- when(mDisplayController.getDisplay(anyInt())).thenReturn(
- mContext.getSystemService(DisplayManager.class).getDisplay(DEFAULT_DISPLAY));
- mController = new TestAppPairsController(
- mTaskOrganizer,
- mSyncQueue,
- mDisplayController);
- mPool = mController.getPool();
- }
-
- @After
- public void tearDown() {}
-
- @Test
- @UiThreadTest
- public void testPairUnpair() {
- final ActivityManager.RunningTaskInfo task1 = new TestRunningTaskInfoBuilder().build();
- final ActivityManager.RunningTaskInfo task2 = new TestRunningTaskInfoBuilder().build();
-
- final AppPair pair = mController.pairInner(task1, task2);
- assertThat(pair.contains(task1.taskId)).isTrue();
- assertThat(pair.contains(task2.taskId)).isTrue();
- assertThat(mPool.poolSize()).isGreaterThan(0);
-
- mController.unpair(task2.taskId);
- assertThat(pair.contains(task1.taskId)).isFalse();
- assertThat(pair.contains(task2.taskId)).isFalse();
- assertThat(mPool.poolSize()).isGreaterThan(1);
- }
-
- @Test
- @UiThreadTest
- public void testUnpair_DontReleaseToPool() {
- final ActivityManager.RunningTaskInfo task1 = new TestRunningTaskInfoBuilder().build();
- final ActivityManager.RunningTaskInfo task2 = new TestRunningTaskInfoBuilder().build();
-
- final AppPair pair = mController.pairInner(task1, task2);
- assertThat(pair.contains(task1.taskId)).isTrue();
- assertThat(pair.contains(task2.taskId)).isTrue();
-
- mController.unpair(task2.taskId, false /* releaseToPool */);
- assertThat(pair.contains(task1.taskId)).isFalse();
- assertThat(pair.contains(task2.taskId)).isFalse();
- assertThat(mPool.poolSize()).isEqualTo(1);
- }
-}
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/apppairs/AppPairsPoolTests.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/apppairs/AppPairsPoolTests.java
deleted file mode 100644
index a3f134ee97ed..000000000000
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/apppairs/AppPairsPoolTests.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.wm.shell.apppairs;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import static org.mockito.ArgumentMatchers.anyInt;
-import static org.mockito.Mockito.when;
-
-import androidx.test.ext.junit.runners.AndroidJUnit4;
-import androidx.test.filters.SmallTest;
-
-import com.android.wm.shell.ShellTaskOrganizer;
-import com.android.wm.shell.ShellTestCase;
-import com.android.wm.shell.common.DisplayController;
-import com.android.wm.shell.common.SyncTransactionQueue;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-/** Tests for {@link AppPairsPool} */
-@SmallTest
-@RunWith(AndroidJUnit4.class)
-public class AppPairsPoolTests extends ShellTestCase {
- private TestAppPairsController mController;
- private TestAppPairsPool mPool;
- @Mock private SyncTransactionQueue mSyncQueue;
- @Mock private ShellTaskOrganizer mTaskOrganizer;
- @Mock private DisplayController mDisplayController;
-
- @Before
- public void setUp() {
- MockitoAnnotations.initMocks(this);
- when(mDisplayController.getDisplayContext(anyInt())).thenReturn(mContext);
- mController = new TestAppPairsController(
- mTaskOrganizer,
- mSyncQueue,
- mDisplayController);
- mPool = mController.getPool();
- }
-
- @After
- public void tearDown() {}
-
- @Test
- public void testInitialState() {
- // Pool should always start off with at least 1 entry.
- assertThat(mPool.poolSize()).isGreaterThan(0);
- }
-
- @Test
- public void testAcquireRelease() {
- assertThat(mPool.poolSize()).isGreaterThan(0);
- final AppPair appPair = mPool.acquire();
- assertThat(mPool.poolSize()).isGreaterThan(0);
- mPool.release(appPair);
- assertThat(mPool.poolSize()).isGreaterThan(1);
- }
-}
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/apppairs/TestAppPairsController.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/apppairs/TestAppPairsController.java
deleted file mode 100644
index 294bc1276291..000000000000
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/apppairs/TestAppPairsController.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.wm.shell.apppairs;
-
-import static org.mockito.Mockito.mock;
-
-import com.android.wm.shell.ShellTaskOrganizer;
-import com.android.wm.shell.common.DisplayController;
-import com.android.wm.shell.common.DisplayImeController;
-import com.android.wm.shell.common.DisplayInsetsController;
-import com.android.wm.shell.common.ShellExecutor;
-import com.android.wm.shell.common.SyncTransactionQueue;
-
-public class TestAppPairsController extends AppPairsController {
- private TestAppPairsPool mPool;
-
- public TestAppPairsController(ShellTaskOrganizer organizer, SyncTransactionQueue syncQueue,
- DisplayController displayController) {
- super(organizer, syncQueue, displayController, mock(ShellExecutor.class),
- mock(DisplayImeController.class), mock(DisplayInsetsController.class));
- mPool = new TestAppPairsPool(this);
- setPairsPool(mPool);
- }
-
- TestAppPairsPool getPool() {
- return mPool;
- }
-}
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/apppairs/TestAppPairsPool.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/apppairs/TestAppPairsPool.java
deleted file mode 100644
index 1ee7fff44892..000000000000
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/apppairs/TestAppPairsPool.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.wm.shell.apppairs;
-
-import android.app.ActivityManager;
-
-import com.android.wm.shell.TestRunningTaskInfoBuilder;
-
-public class TestAppPairsPool extends AppPairsPool{
- TestAppPairsPool(AppPairsController controller) {
- super(controller);
- }
-
- @Override
- void incrementPool() {
- final AppPair entry = new AppPair(mController);
- final ActivityManager.RunningTaskInfo info =
- new TestRunningTaskInfoBuilder().build();
- entry.onTaskAppeared(info, null /* leash */);
- release(entry);
- }
-}
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/bubbles/BubblesNavBarMotionEventHandlerTest.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/bubbles/BubblesNavBarMotionEventHandlerTest.java
new file mode 100644
index 000000000000..44ff35466ae2
--- /dev/null
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/bubbles/BubblesNavBarMotionEventHandlerTest.java
@@ -0,0 +1,142 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.wm.shell.bubbles;
+
+import static android.view.MotionEvent.ACTION_CANCEL;
+import static android.view.MotionEvent.ACTION_DOWN;
+import static android.view.MotionEvent.ACTION_MOVE;
+import static android.view.MotionEvent.ACTION_UP;
+
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.ArgumentMatchers.floatThat;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+import static org.mockito.Mockito.verifyZeroInteractions;
+
+import android.os.SystemClock;
+import android.testing.AndroidTestingRunner;
+import android.testing.TestableLooper;
+import android.view.MotionEvent;
+import android.view.WindowManager;
+
+import androidx.test.filters.SmallTest;
+
+import com.android.wm.shell.ShellTestCase;
+import com.android.wm.shell.bubbles.BubblesNavBarMotionEventHandler.MotionEventListener;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+/**
+ * Test {@link MotionEvent} handling in {@link BubblesNavBarMotionEventHandler}.
+ * Verifies that swipe events
+ */
+@SmallTest
+@TestableLooper.RunWithLooper(setAsMainLooper = true)
+@RunWith(AndroidTestingRunner.class)
+public class BubblesNavBarMotionEventHandlerTest extends ShellTestCase {
+
+ private BubblesNavBarMotionEventHandler mMotionEventHandler;
+ @Mock
+ private WindowManager mWindowManager;
+ @Mock
+ private Runnable mInterceptTouchRunnable;
+ @Mock
+ private MotionEventListener mMotionEventListener;
+ private long mMotionEventTime;
+
+ @Before
+ public void setUp() {
+ MockitoAnnotations.initMocks(this);
+ TestableBubblePositioner positioner = new TestableBubblePositioner(getContext(),
+ mWindowManager);
+ mMotionEventHandler = new BubblesNavBarMotionEventHandler(getContext(), positioner,
+ mInterceptTouchRunnable, mMotionEventListener);
+ mMotionEventTime = SystemClock.uptimeMillis();
+ }
+
+ @Test
+ public void testMotionEvent_swipeUpInGestureZone_handled() {
+ mMotionEventHandler.onMotionEvent(newEvent(ACTION_DOWN, 0, 990));
+ mMotionEventHandler.onMotionEvent(newEvent(ACTION_MOVE, 0, 690));
+ mMotionEventHandler.onMotionEvent(newEvent(ACTION_MOVE, 0, 490));
+ mMotionEventHandler.onMotionEvent(newEvent(ACTION_MOVE, 0, 390));
+ mMotionEventHandler.onMotionEvent(newEvent(ACTION_UP, 0, 390));
+
+ verify(mMotionEventListener).onDown(0, 990);
+ verify(mMotionEventListener).onMove(0, -300);
+ verify(mMotionEventListener).onMove(0, -500);
+ verify(mMotionEventListener).onMove(0, -600);
+ // Check that velocity up is about 5000
+ verify(mMotionEventListener).onUp(eq(0f), floatThat(f -> Math.round(f) == -5000));
+ verifyZeroInteractions(mMotionEventListener);
+ verify(mInterceptTouchRunnable).run();
+ }
+
+ @Test
+ public void testMotionEvent_swipeUpOutsideGestureZone_ignored() {
+ mMotionEventHandler.onMotionEvent(newEvent(ACTION_DOWN, 0, 500));
+ mMotionEventHandler.onMotionEvent(newEvent(ACTION_MOVE, 0, 100));
+ mMotionEventHandler.onMotionEvent(newEvent(ACTION_UP, 0, 100));
+
+ verifyZeroInteractions(mMotionEventListener);
+ verifyZeroInteractions(mInterceptTouchRunnable);
+ }
+
+ @Test
+ public void testMotionEvent_horizontalMoveMoreThanTouchSlop_handled() {
+ mMotionEventHandler.onMotionEvent(newEvent(ACTION_DOWN, 0, 990));
+ mMotionEventHandler.onMotionEvent(newEvent(ACTION_MOVE, 100, 990));
+ mMotionEventHandler.onMotionEvent(newEvent(ACTION_UP, 100, 990));
+
+ verify(mMotionEventListener).onDown(0, 990);
+ verify(mMotionEventListener).onMove(100, 0);
+ verify(mMotionEventListener).onUp(0, 0);
+ verifyZeroInteractions(mMotionEventListener);
+ verify(mInterceptTouchRunnable).run();
+ }
+
+ @Test
+ public void testMotionEvent_moveLessThanTouchSlop_ignored() {
+ mMotionEventHandler.onMotionEvent(newEvent(ACTION_DOWN, 0, 990));
+ mMotionEventHandler.onMotionEvent(newEvent(ACTION_MOVE, 0, 989));
+ mMotionEventHandler.onMotionEvent(newEvent(ACTION_UP, 0, 989));
+
+ verify(mMotionEventListener).onDown(0, 990);
+ verifyNoMoreInteractions(mMotionEventListener);
+ verifyZeroInteractions(mInterceptTouchRunnable);
+ }
+
+ @Test
+ public void testMotionEvent_actionCancel_listenerNotified() {
+ mMotionEventHandler.onMotionEvent(newEvent(ACTION_DOWN, 0, 990));
+ mMotionEventHandler.onMotionEvent(newEvent(ACTION_CANCEL, 0, 990));
+ verify(mMotionEventListener).onDown(0, 990);
+ verify(mMotionEventListener).onCancel();
+ verifyNoMoreInteractions(mMotionEventListener);
+ verifyZeroInteractions(mInterceptTouchRunnable);
+ }
+
+ private MotionEvent newEvent(int actionDown, float x, float y) {
+ MotionEvent event = MotionEvent.obtain(0L, mMotionEventTime, actionDown, x, y, 0);
+ mMotionEventTime += 10;
+ return event;
+ }
+}
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/bubbles/animation/ExpandedViewAnimationControllerTest.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/bubbles/animation/ExpandedViewAnimationControllerTest.java
new file mode 100644
index 000000000000..21887c03833a
--- /dev/null
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/bubbles/animation/ExpandedViewAnimationControllerTest.java
@@ -0,0 +1,181 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.wm.shell.bubbles.animation;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.junit.Assume.assumeTrue;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.Mockito.atLeastOnce;
+import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.testing.AndroidTestingRunner;
+import android.testing.TestableLooper;
+import android.view.ViewConfiguration;
+import android.view.WindowManager;
+
+import androidx.test.filters.SmallTest;
+
+import com.android.wm.shell.ShellTestCase;
+import com.android.wm.shell.bubbles.BubbleExpandedView;
+import com.android.wm.shell.bubbles.TestableBubblePositioner;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+@SmallTest
+@RunWith(AndroidTestingRunner.class)
+@TestableLooper.RunWithLooper(setAsMainLooper = true)
+public class ExpandedViewAnimationControllerTest extends ShellTestCase {
+
+ private ExpandedViewAnimationController mController;
+
+ @Mock
+ private WindowManager mWindowManager;
+
+ @Mock
+ private BubbleExpandedView mMockExpandedView;
+
+ @Before
+ public void setUp() {
+ MockitoAnnotations.initMocks(this);
+
+ TestableBubblePositioner positioner = new TestableBubblePositioner(getContext(),
+ mWindowManager);
+ mController = new ExpandedViewAnimationControllerImpl(getContext(), positioner);
+
+ mController.setExpandedView(mMockExpandedView);
+ when(mMockExpandedView.getContentHeight()).thenReturn(1000);
+ }
+
+ @Test
+ public void testUpdateDrag_expandedViewMovesUpAndClipped() {
+ // Drag by 50 pixels which corresponds to 10 pixels with overscroll
+ int dragDistance = 50;
+ int dampenedDistance = 10;
+
+ mController.updateDrag(dragDistance);
+
+ verify(mMockExpandedView).setTopClip(dampenedDistance);
+ verify(mMockExpandedView).setContentTranslationY(-dampenedDistance);
+ verify(mMockExpandedView).setManageButtonTranslationY(-dampenedDistance);
+ }
+
+ @Test
+ public void testUpdateDrag_zOrderUpdates() {
+ mController.updateDrag(10);
+ mController.updateDrag(20);
+
+ verify(mMockExpandedView, times(1)).setSurfaceZOrderedOnTop(true);
+ verify(mMockExpandedView, times(1)).setAnimating(true);
+ }
+
+ @Test
+ public void testUpdateDrag_moveBackToZero_zOrderRestored() {
+ mController.updateDrag(50);
+ reset(mMockExpandedView);
+ mController.updateDrag(0);
+ mController.updateDrag(0);
+
+ verify(mMockExpandedView, times(1)).setSurfaceZOrderedOnTop(false);
+ verify(mMockExpandedView, times(1)).setAnimating(false);
+ }
+
+ @Test
+ public void testUpdateDrag_hapticFeedbackOnlyOnce() {
+ // Drag by 10 which is below the collapse threshold - no feedback
+ mController.updateDrag(10);
+ verify(mMockExpandedView, times(0)).performHapticFeedback(anyInt());
+ // 150 takes it over the threshold - perform feedback
+ mController.updateDrag(150);
+ verify(mMockExpandedView, times(1)).performHapticFeedback(anyInt());
+ // Continue dragging, no more feedback
+ mController.updateDrag(200);
+ verify(mMockExpandedView, times(1)).performHapticFeedback(anyInt());
+ // Drag below threshold and over again - no more feedback
+ mController.updateDrag(10);
+ mController.updateDrag(150);
+ verify(mMockExpandedView, times(1)).performHapticFeedback(anyInt());
+ }
+
+ @Test
+ public void testShouldCollapse_doNotCollapseIfNotDragged() {
+ assertThat(mController.shouldCollapse()).isFalse();
+ }
+
+ @Test
+ public void testShouldCollapse_doNotCollapseIfVelocityDown() {
+ assumeTrue("Min fling velocity should be > 1 for this test", getMinFlingVelocity() > 1);
+ mController.setSwipeVelocity(getVelocityAboveMinFling());
+ assertThat(mController.shouldCollapse()).isFalse();
+ }
+
+ @Test
+ public void tesShouldCollapse_doNotCollapseIfVelocityUpIsSmall() {
+ assumeTrue("Min fling velocity should be > 1 for this test", getMinFlingVelocity() > 1);
+ mController.setSwipeVelocity(-getVelocityBelowMinFling());
+ assertThat(mController.shouldCollapse()).isFalse();
+ }
+
+ @Test
+ public void testShouldCollapse_collapseIfVelocityUpIsLarge() {
+ assumeTrue("Min fling velocity should be > 1 for this test", getMinFlingVelocity() > 1);
+ mController.setSwipeVelocity(-getVelocityAboveMinFling());
+ assertThat(mController.shouldCollapse()).isTrue();
+ }
+
+ @Test
+ public void testShouldCollapse_collapseIfPastThreshold() {
+ mController.updateDrag(500);
+ assertThat(mController.shouldCollapse()).isTrue();
+ }
+
+ @Test
+ public void testReset() {
+ mController.updateDrag(100);
+ reset(mMockExpandedView);
+ mController.reset();
+ verify(mMockExpandedView, atLeastOnce()).setAnimating(false);
+ verify(mMockExpandedView).setContentAlpha(1);
+ verify(mMockExpandedView).setAlpha(1);
+ verify(mMockExpandedView).setManageButtonAlpha(1);
+ verify(mMockExpandedView).setManageButtonAlpha(1);
+ verify(mMockExpandedView).setTopClip(0);
+ verify(mMockExpandedView).setContentTranslationY(-0f);
+ verify(mMockExpandedView).setManageButtonTranslationY(-0f);
+ verify(mMockExpandedView).setBottomClip(0);
+ verify(mMockExpandedView).movePointerBy(0, 0);
+ assertThat(mController.shouldCollapse()).isFalse();
+ }
+
+ private int getVelocityBelowMinFling() {
+ return getMinFlingVelocity() - 1;
+ }
+
+ private int getVelocityAboveMinFling() {
+ return getMinFlingVelocity() + 1;
+ }
+
+ private int getMinFlingVelocity() {
+ return ViewConfiguration.get(getContext()).getScaledMinimumFlingVelocity();
+ }
+}
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/onehanded/OneHandedControllerTest.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/onehanded/OneHandedControllerTest.java
index ecf1c5d41864..6a6db8aa3c04 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/onehanded/OneHandedControllerTest.java
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/onehanded/OneHandedControllerTest.java
@@ -345,8 +345,8 @@ public class OneHandedControllerTest extends OneHandedTestCase {
when(mMockSettingsUitl.getSettingsSwipeToNotificationEnabled(any(), anyInt())).thenReturn(
false);
final WindowContainerTransaction handlerWCT = new WindowContainerTransaction();
- mSpiedOneHandedController.onRotateDisplay(mDisplay.getDisplayId(), Surface.ROTATION_0,
- Surface.ROTATION_90, handlerWCT);
+ mSpiedOneHandedController.onDisplayChange(mDisplay.getDisplayId(), Surface.ROTATION_0,
+ Surface.ROTATION_90, null /* newDisplayAreaInfo */, handlerWCT);
verify(mMockDisplayAreaOrganizer, atLeastOnce()).onRotateDisplay(eq(mContext),
eq(Surface.ROTATION_90), any(WindowContainerTransaction.class));
@@ -358,8 +358,8 @@ public class OneHandedControllerTest extends OneHandedTestCase {
when(mMockSettingsUitl.getSettingsSwipeToNotificationEnabled(any(), anyInt())).thenReturn(
false);
final WindowContainerTransaction handlerWCT = new WindowContainerTransaction();
- mSpiedOneHandedController.onRotateDisplay(mDisplay.getDisplayId(), Surface.ROTATION_0,
- Surface.ROTATION_90, handlerWCT);
+ mSpiedOneHandedController.onDisplayChange(mDisplay.getDisplayId(), Surface.ROTATION_0,
+ Surface.ROTATION_90, null /* newDisplayAreaInfo */, handlerWCT);
verify(mMockDisplayAreaOrganizer, never()).onRotateDisplay(eq(mContext),
eq(Surface.ROTATION_90), any(WindowContainerTransaction.class));
@@ -371,8 +371,8 @@ public class OneHandedControllerTest extends OneHandedTestCase {
when(mMockSettingsUitl.getSettingsSwipeToNotificationEnabled(any(), anyInt())).thenReturn(
true);
final WindowContainerTransaction handlerWCT = new WindowContainerTransaction();
- mSpiedOneHandedController.onRotateDisplay(mDisplay.getDisplayId(), Surface.ROTATION_0,
- Surface.ROTATION_90, handlerWCT);
+ mSpiedOneHandedController.onDisplayChange(mDisplay.getDisplayId(), Surface.ROTATION_0,
+ Surface.ROTATION_90, null /* newDisplayAreaInfo */, handlerWCT);
verify(mMockDisplayAreaOrganizer, never()).onRotateDisplay(eq(mContext),
eq(Surface.ROTATION_90), any(WindowContainerTransaction.class));
@@ -384,8 +384,8 @@ public class OneHandedControllerTest extends OneHandedTestCase {
when(mMockSettingsUitl.getSettingsSwipeToNotificationEnabled(any(), anyInt())).thenReturn(
false);
final WindowContainerTransaction handlerWCT = new WindowContainerTransaction();
- mSpiedOneHandedController.onRotateDisplay(mDisplay.getDisplayId(), Surface.ROTATION_0,
- Surface.ROTATION_90, handlerWCT);
+ mSpiedOneHandedController.onDisplayChange(mDisplay.getDisplayId(), Surface.ROTATION_0,
+ Surface.ROTATION_90, null /* newDisplayAreaInfo */, handlerWCT);
verify(mMockDisplayAreaOrganizer, atLeastOnce()).onRotateDisplay(eq(mContext),
eq(Surface.ROTATION_90), any(WindowContainerTransaction.class));
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/tv/TvPipBoundsControllerTest.kt b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/tv/TvPipBoundsControllerTest.kt
new file mode 100644
index 000000000000..05e472245b4a
--- /dev/null
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/tv/TvPipBoundsControllerTest.kt
@@ -0,0 +1,255 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.wm.shell.pip.tv
+
+import android.content.Context
+import android.content.res.Resources
+import android.graphics.Rect
+import android.os.Handler
+import android.os.test.TestLooper
+import android.testing.AndroidTestingRunner
+
+import com.android.wm.shell.R
+import com.android.wm.shell.pip.PipBoundsState.STASH_TYPE_RIGHT
+import com.android.wm.shell.pip.tv.TvPipBoundsController.POSITION_DEBOUNCE_TIMEOUT_MILLIS
+import com.android.wm.shell.pip.tv.TvPipKeepClearAlgorithm.Placement
+
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.mockito.AdditionalAnswers.returnsFirstArg
+import org.mockito.Mock
+import org.mockito.Mockito.`when` as whenever
+import org.mockito.Mockito.any
+import org.mockito.Mockito.anyInt
+import org.mockito.Mockito.eq
+import org.mockito.Mockito.never
+import org.mockito.Mockito.reset
+import org.mockito.Mockito.verify
+import org.mockito.MockitoAnnotations
+
+@RunWith(AndroidTestingRunner::class)
+class TvPipBoundsControllerTest {
+ val ANIMATION_DURATION = 100
+ val STASH_DURATION = 5000
+ val FAR_FUTURE = 60 * 60000L
+ val ANCHOR_BOUNDS = Rect(90, 90, 100, 100)
+ val STASHED_BOUNDS = Rect(99, 90, 109, 100)
+ val MOVED_BOUNDS = Rect(90, 80, 100, 90)
+ val STASHED_MOVED_BOUNDS = Rect(99, 80, 109, 90)
+ val ANCHOR_PLACEMENT = Placement(ANCHOR_BOUNDS, ANCHOR_BOUNDS)
+ val STASHED_PLACEMENT = Placement(STASHED_BOUNDS, ANCHOR_BOUNDS,
+ STASH_TYPE_RIGHT, ANCHOR_BOUNDS, false)
+ val STASHED_PLACEMENT_RESTASH = Placement(STASHED_BOUNDS, ANCHOR_BOUNDS,
+ STASH_TYPE_RIGHT, ANCHOR_BOUNDS, true)
+ val MOVED_PLACEMENT = Placement(MOVED_BOUNDS, ANCHOR_BOUNDS)
+ val STASHED_MOVED_PLACEMENT = Placement(STASHED_MOVED_BOUNDS, ANCHOR_BOUNDS,
+ STASH_TYPE_RIGHT, MOVED_BOUNDS, false)
+ val STASHED_MOVED_PLACEMENT_RESTASH = Placement(STASHED_MOVED_BOUNDS, ANCHOR_BOUNDS,
+ STASH_TYPE_RIGHT, MOVED_BOUNDS, true)
+
+ lateinit var boundsController: TvPipBoundsController
+ var time = 0L
+ lateinit var testLooper: TestLooper
+ lateinit var mainHandler: Handler
+
+ var inMenu = false
+ var inMoveMode = false
+
+ @Mock
+ lateinit var context: Context
+ @Mock
+ lateinit var resources: Resources
+ @Mock
+ lateinit var tvPipBoundsState: TvPipBoundsState
+ @Mock
+ lateinit var tvPipBoundsAlgorithm: TvPipBoundsAlgorithm
+ @Mock
+ lateinit var listener: TvPipBoundsController.PipBoundsListener
+
+ @Before
+ fun setUp() {
+ MockitoAnnotations.initMocks(this)
+ time = 0L
+ inMenu = false
+ inMoveMode = false
+
+ testLooper = TestLooper { time }
+ mainHandler = Handler(testLooper.getLooper())
+
+ whenever(context.resources).thenReturn(resources)
+ whenever(resources.getInteger(R.integer.config_pipStashDuration)).thenReturn(STASH_DURATION)
+ whenever(tvPipBoundsAlgorithm.adjustBoundsForTemporaryDecor(any()))
+ .then(returnsFirstArg<Rect>())
+
+ boundsController = TvPipBoundsController(
+ context,
+ { time },
+ mainHandler,
+ tvPipBoundsState,
+ tvPipBoundsAlgorithm)
+ boundsController.setListener(listener)
+ }
+
+ @Test
+ fun testPlacement_MovedAfterDebounceTimeout() {
+ triggerPlacement(MOVED_PLACEMENT)
+ assertMovementAt(POSITION_DEBOUNCE_TIMEOUT_MILLIS, MOVED_BOUNDS)
+ assertNoMovementUpTo(time + FAR_FUTURE)
+ }
+
+ @Test
+ fun testStashedPlacement_MovedAfterDebounceTimeout_Unstashes() {
+ triggerPlacement(STASHED_PLACEMENT_RESTASH)
+ assertMovementAt(POSITION_DEBOUNCE_TIMEOUT_MILLIS, STASHED_BOUNDS)
+ assertMovementAt(POSITION_DEBOUNCE_TIMEOUT_MILLIS + STASH_DURATION, ANCHOR_BOUNDS)
+ }
+
+ @Test
+ fun testDebounceSamePlacement_MovesDebounceTimeoutAfterFirstPlacement() {
+ triggerPlacement(MOVED_PLACEMENT)
+ advanceTimeTo(POSITION_DEBOUNCE_TIMEOUT_MILLIS / 2)
+ triggerPlacement(MOVED_PLACEMENT)
+
+ assertMovementAt(POSITION_DEBOUNCE_TIMEOUT_MILLIS, MOVED_BOUNDS)
+ }
+
+ @Test
+ fun testNoMovementUntilPlacementStabilizes() {
+ triggerPlacement(ANCHOR_PLACEMENT)
+ advanceTimeTo(time + POSITION_DEBOUNCE_TIMEOUT_MILLIS / 10)
+ triggerPlacement(MOVED_PLACEMENT)
+ advanceTimeTo(time + POSITION_DEBOUNCE_TIMEOUT_MILLIS / 10)
+ triggerPlacement(ANCHOR_PLACEMENT)
+ advanceTimeTo(time + POSITION_DEBOUNCE_TIMEOUT_MILLIS / 10)
+ triggerPlacement(MOVED_PLACEMENT)
+
+ assertMovementAt(time + POSITION_DEBOUNCE_TIMEOUT_MILLIS, MOVED_BOUNDS)
+ }
+
+ @Test
+ fun testUnstashIfStashNoLongerNecessary() {
+ triggerPlacement(STASHED_PLACEMENT_RESTASH)
+ assertMovementAt(POSITION_DEBOUNCE_TIMEOUT_MILLIS, STASHED_BOUNDS)
+
+ triggerPlacement(ANCHOR_PLACEMENT)
+ assertMovementAt(time + POSITION_DEBOUNCE_TIMEOUT_MILLIS, ANCHOR_BOUNDS)
+ }
+
+ @Test
+ fun testRestashingPlacementDelaysUnstash() {
+ triggerPlacement(STASHED_PLACEMENT_RESTASH)
+ assertMovementAt(POSITION_DEBOUNCE_TIMEOUT_MILLIS, STASHED_BOUNDS)
+
+ assertNoMovementUpTo(time + STASH_DURATION / 2)
+ triggerPlacement(STASHED_PLACEMENT_RESTASH)
+ assertNoMovementUpTo(time + POSITION_DEBOUNCE_TIMEOUT_MILLIS)
+ assertMovementAt(time + STASH_DURATION, ANCHOR_BOUNDS)
+ }
+
+ @Test
+ fun testNonRestashingPlacementDoesNotDelayUnstash() {
+ triggerPlacement(STASHED_PLACEMENT_RESTASH)
+ assertMovementAt(POSITION_DEBOUNCE_TIMEOUT_MILLIS, STASHED_BOUNDS)
+
+ assertNoMovementUpTo(time + STASH_DURATION / 2)
+ triggerPlacement(STASHED_PLACEMENT)
+ assertMovementAt(POSITION_DEBOUNCE_TIMEOUT_MILLIS + STASH_DURATION, ANCHOR_BOUNDS)
+ }
+
+ @Test
+ fun testImmediatePlacement() {
+ triggerImmediatePlacement(STASHED_PLACEMENT_RESTASH)
+ assertMovement(STASHED_BOUNDS)
+ assertMovementAt(time + STASH_DURATION, ANCHOR_BOUNDS)
+ }
+
+ @Test
+ fun testInMoveMode_KeepAtAnchor() {
+ startMoveMode()
+ triggerImmediatePlacement(STASHED_MOVED_PLACEMENT_RESTASH)
+ assertMovement(ANCHOR_BOUNDS)
+ assertNoMovementUpTo(time + FAR_FUTURE)
+ }
+
+ @Test
+ fun testInMenu_Unstashed() {
+ openPipMenu()
+ triggerImmediatePlacement(STASHED_MOVED_PLACEMENT_RESTASH)
+ assertMovement(MOVED_BOUNDS)
+ assertNoMovementUpTo(time + FAR_FUTURE)
+ }
+
+ @Test
+ fun testCloseMenu_DoNotRestash() {
+ openPipMenu()
+ triggerImmediatePlacement(STASHED_MOVED_PLACEMENT_RESTASH)
+ assertMovement(MOVED_BOUNDS)
+
+ closePipMenu()
+ triggerPlacement(STASHED_MOVED_PLACEMENT)
+ assertNoMovementUpTo(time + FAR_FUTURE)
+ }
+
+ fun assertMovement(bounds: Rect) {
+ verify(listener).onPipTargetBoundsChange(eq(bounds), anyInt())
+ reset(listener)
+ }
+
+ fun assertMovementAt(timeMs: Long, bounds: Rect) {
+ assertNoMovementUpTo(timeMs - 1)
+ advanceTimeTo(timeMs)
+ assertMovement(bounds)
+ }
+
+ fun assertNoMovementUpTo(timeMs: Long) {
+ advanceTimeTo(timeMs)
+ verify(listener, never()).onPipTargetBoundsChange(any(), anyInt())
+ }
+
+ fun triggerPlacement(placement: Placement, immediate: Boolean = false) {
+ whenever(tvPipBoundsAlgorithm.getTvPipPlacement()).thenReturn(placement)
+ val stayAtAnchorPosition = inMoveMode
+ val disallowStashing = inMenu || stayAtAnchorPosition
+ boundsController.recalculatePipBounds(stayAtAnchorPosition, disallowStashing,
+ ANIMATION_DURATION, immediate)
+ }
+
+ fun triggerImmediatePlacement(placement: Placement) {
+ triggerPlacement(placement, true)
+ }
+
+ fun openPipMenu() {
+ inMenu = true
+ inMoveMode = false
+ }
+
+ fun closePipMenu() {
+ inMenu = false
+ inMoveMode = false
+ }
+
+ fun startMoveMode() {
+ inMenu = true
+ inMoveMode = true
+ }
+
+ fun advanceTimeTo(ms: Long) {
+ time = ms
+ testLooper.dispatchAll()
+ }
+}
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/tv/TvPipKeepClearAlgorithmTest.kt b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/tv/TvPipKeepClearAlgorithmTest.kt
index 46f388d0ce0e..0fcc5cf384c9 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/tv/TvPipKeepClearAlgorithmTest.kt
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/tv/TvPipKeepClearAlgorithmTest.kt
@@ -30,7 +30,9 @@ import com.android.wm.shell.pip.tv.TvPipKeepClearAlgorithm.Placement
import org.junit.Before
import org.junit.Test
import junit.framework.Assert.assertEquals
+import junit.framework.Assert.assertFalse
import junit.framework.Assert.assertNull
+import junit.framework.Assert.assertTrue
@RunWith(AndroidTestingRunner::class)
class TvPipKeepClearAlgorithmTest {
@@ -46,7 +48,6 @@ class TvPipKeepClearAlgorithmTest {
private lateinit var pipSize: Size
private lateinit var movementBounds: Rect
private lateinit var algorithm: TvPipKeepClearAlgorithm
- private var currentTime = 0L
private var restrictedAreas = mutableSetOf<Rect>()
private var unrestrictedAreas = mutableSetOf<Rect>()
private var gravity: Int = 0
@@ -58,16 +59,14 @@ class TvPipKeepClearAlgorithmTest {
restrictedAreas.clear()
unrestrictedAreas.clear()
- currentTime = 0L
pipSize = DEFAULT_PIP_SIZE
gravity = Gravity.BOTTOM or Gravity.RIGHT
- algorithm = TvPipKeepClearAlgorithm({ currentTime })
+ algorithm = TvPipKeepClearAlgorithm()
algorithm.setScreenSize(SCREEN_SIZE)
algorithm.setMovementBounds(movementBounds)
algorithm.pipAreaPadding = PADDING
algorithm.stashOffset = STASH_OFFSET
- algorithm.stashDuration = 5000L
algorithm.setGravity(gravity)
algorithm.maxRestrictedDistanceFraction = 0.3
}
@@ -265,7 +264,7 @@ class TvPipKeepClearAlgorithmTest {
assertEquals(expectedBounds, placement.bounds)
assertEquals(STASH_TYPE_BOTTOM, placement.stashType)
assertEquals(getExpectedAnchorBounds(), placement.unstashDestinationBounds)
- assertEquals(algorithm.stashDuration, placement.unstashTime)
+ assertTrue(placement.triggerStash)
}
@Test
@@ -305,7 +304,7 @@ class TvPipKeepClearAlgorithmTest {
assertEquals(expectedBounds, placement.bounds)
assertEquals(STASH_TYPE_RIGHT, placement.stashType)
assertEquals(expectedUnstashBounds, placement.unstashDestinationBounds)
- assertEquals(algorithm.stashDuration, placement.unstashTime)
+ assertTrue(placement.triggerStash)
}
@Test
@@ -352,9 +351,7 @@ class TvPipKeepClearAlgorithmTest {
assertEquals(expectedBounds, placement.bounds)
assertEquals(STASH_TYPE_RIGHT, placement.stashType)
assertEquals(expectedUnstashBounds, placement.unstashDestinationBounds)
- assertEquals(algorithm.stashDuration, placement.unstashTime)
-
- currentTime += 1000
+ assertTrue(placement.triggerStash)
restrictedAreas.remove(sideBar)
placement = getActualPlacement()
@@ -363,7 +360,7 @@ class TvPipKeepClearAlgorithmTest {
}
@Test
- fun test_Stashed_UnstashBoundsStaysObstructed_UnstashesAfterTimeout() {
+ fun test_Stashed_UnstashBoundsStaysObstructed_DoesNotTriggerStash() {
gravity = Gravity.BOTTOM or Gravity.RIGHT
val bottomBar = makeBottomBar(BOTTOM_SHEET_HEIGHT)
@@ -384,13 +381,13 @@ class TvPipKeepClearAlgorithmTest {
assertEquals(expectedBounds, placement.bounds)
assertEquals(STASH_TYPE_RIGHT, placement.stashType)
assertEquals(expectedUnstashBounds, placement.unstashDestinationBounds)
- assertEquals(algorithm.stashDuration, placement.unstashTime)
-
- currentTime += algorithm.stashDuration
+ assertTrue(placement.triggerStash)
placement = getActualPlacement()
- assertEquals(expectedUnstashBounds, placement.bounds)
- assertNotStashed(placement)
+ assertEquals(expectedBounds, placement.bounds)
+ assertEquals(STASH_TYPE_RIGHT, placement.stashType)
+ assertEquals(expectedUnstashBounds, placement.unstashDestinationBounds)
+ assertFalse(placement.triggerStash)
}
@Test
@@ -415,9 +412,7 @@ class TvPipKeepClearAlgorithmTest {
assertEquals(expectedBounds, placement.bounds)
assertEquals(STASH_TYPE_RIGHT, placement.stashType)
assertEquals(expectedUnstashBounds, placement.unstashDestinationBounds)
- assertEquals(algorithm.stashDuration, placement.unstashTime)
-
- currentTime += 1000
+ assertTrue(placement.triggerStash)
val newObstruction = Rect(
0,
@@ -431,7 +426,7 @@ class TvPipKeepClearAlgorithmTest {
assertEquals(expectedBounds, placement.bounds)
assertEquals(STASH_TYPE_RIGHT, placement.stashType)
assertEquals(expectedUnstashBounds, placement.unstashDestinationBounds)
- assertEquals(currentTime + algorithm.stashDuration, placement.unstashTime)
+ assertTrue(placement.triggerStash)
}
@Test
@@ -458,21 +453,9 @@ class TvPipKeepClearAlgorithmTest {
@Test
fun test_PipInsets() {
- val permInsets = Insets.of(-1, -2, -3, -4)
- algorithm.setPipPermanentDecorInsets(permInsets)
- testInsetsForAllPositions(permInsets)
-
- val tempInsets = Insets.of(-4, -3, -2, -1)
- algorithm.setPipPermanentDecorInsets(Insets.NONE)
- algorithm.setPipTemporaryDecorInsets(tempInsets)
- testInsetsForAllPositions(tempInsets)
-
- algorithm.setPipPermanentDecorInsets(permInsets)
- algorithm.setPipTemporaryDecorInsets(tempInsets)
- testInsetsForAllPositions(Insets.add(permInsets, tempInsets))
- }
+ val insets = Insets.of(-1, -2, -3, -4)
+ algorithm.setPipPermanentDecorInsets(insets)
- private fun testInsetsForAllPositions(insets: Insets) {
gravity = Gravity.BOTTOM or Gravity.RIGHT
testAnchorPositionWithInsets(insets)
@@ -546,6 +529,6 @@ class TvPipKeepClearAlgorithmTest {
private fun assertNotStashed(actual: Placement) {
assertEquals(STASH_TYPE_NONE, actual.stashType)
assertNull(actual.unstashDestinationBounds)
- assertEquals(0L, actual.unstashTime)
+ assertFalse(actual.triggerStash)
}
}
diff --git a/libs/hwui/AnimatorManager.cpp b/libs/hwui/AnimatorManager.cpp
index 4826d5a0c8da..078041411a21 100644
--- a/libs/hwui/AnimatorManager.cpp
+++ b/libs/hwui/AnimatorManager.cpp
@@ -31,7 +31,8 @@ static void detach(sp<BaseRenderNodeAnimator>& animator) {
animator->detach();
}
-AnimatorManager::AnimatorManager(RenderNode& parent) : mParent(parent), mAnimationHandle(nullptr) {}
+AnimatorManager::AnimatorManager(RenderNode& parent)
+ : mParent(parent), mAnimationHandle(nullptr), mCancelAllAnimators(false) {}
AnimatorManager::~AnimatorManager() {
for_each(mNewAnimators.begin(), mNewAnimators.end(), detach);
@@ -82,8 +83,16 @@ void AnimatorManager::pushStaging() {
}
mNewAnimators.clear();
}
- for (auto& animator : mAnimators) {
- animator->pushStaging(mAnimationHandle->context());
+
+ if (mCancelAllAnimators) {
+ for (auto& animator : mAnimators) {
+ animator->forceEndNow(mAnimationHandle->context());
+ }
+ mCancelAllAnimators = false;
+ } else {
+ for (auto& animator : mAnimators) {
+ animator->pushStaging(mAnimationHandle->context());
+ }
}
}
@@ -184,5 +193,9 @@ void AnimatorManager::endAllActiveAnimators() {
mAnimationHandle->release();
}
+void AnimatorManager::forceEndAnimators() {
+ mCancelAllAnimators = true;
+}
+
} /* namespace uirenderer */
} /* namespace android */
diff --git a/libs/hwui/AnimatorManager.h b/libs/hwui/AnimatorManager.h
index a0df01d5962c..6002661dc82a 100644
--- a/libs/hwui/AnimatorManager.h
+++ b/libs/hwui/AnimatorManager.h
@@ -16,11 +16,11 @@
#ifndef ANIMATORMANAGER_H
#define ANIMATORMANAGER_H
-#include <vector>
-
#include <cutils/compiler.h>
#include <utils/StrongPointer.h>
+#include <vector>
+
#include "utils/Macros.h"
namespace android {
@@ -56,6 +56,8 @@ public:
// Hard-ends all animators. May only be called on the UI thread.
void endAllStagingAnimators();
+ void forceEndAnimators();
+
// Hard-ends all animators that have been pushed. Used for cleanup if
// the ActivityContext is being destroyed
void endAllActiveAnimators();
@@ -71,6 +73,8 @@ private:
// To improve the efficiency of resizing & removing from the vector
std::vector<sp<BaseRenderNodeAnimator> > mNewAnimators;
std::vector<sp<BaseRenderNodeAnimator> > mAnimators;
+
+ bool mCancelAllAnimators;
};
} /* namespace uirenderer */
diff --git a/libs/hwui/Properties.cpp b/libs/hwui/Properties.cpp
index 86ae3995eeed..5a67eb9935dd 100644
--- a/libs/hwui/Properties.cpp
+++ b/libs/hwui/Properties.cpp
@@ -134,7 +134,7 @@ bool Properties::load() {
skpCaptureEnabled = debuggingEnabled && base::GetBoolProperty(PROPERTY_CAPTURE_SKP_ENABLED, false);
SkAndroidFrameworkTraceUtil::setEnableTracing(
- base::GetBoolProperty(PROPERTY_SKIA_ATRACE_ENABLED, true));
+ base::GetBoolProperty(PROPERTY_SKIA_ATRACE_ENABLED, false));
runningInEmulator = base::GetBoolProperty(PROPERTY_IS_EMULATOR, false);
diff --git a/libs/hwui/jni/android_graphics_RenderNode.cpp b/libs/hwui/jni/android_graphics_RenderNode.cpp
index 944393c63ad6..db7639029187 100644
--- a/libs/hwui/jni/android_graphics_RenderNode.cpp
+++ b/libs/hwui/jni/android_graphics_RenderNode.cpp
@@ -543,6 +543,12 @@ static void android_view_RenderNode_endAllAnimators(JNIEnv* env, jobject clazz,
renderNode->animators().endAllStagingAnimators();
}
+static void android_view_RenderNode_forceEndAnimators(JNIEnv* env, jobject clazz,
+ jlong renderNodePtr) {
+ RenderNode* renderNode = reinterpret_cast<RenderNode*>(renderNodePtr);
+ renderNode->animators().forceEndAnimators();
+}
+
// ----------------------------------------------------------------------------
// SurfaceView position callback
// ----------------------------------------------------------------------------
@@ -745,6 +751,7 @@ static const JNINativeMethod gMethods[] = {
{"nGetAllocatedSize", "(J)I", (void*)android_view_RenderNode_getAllocatedSize},
{"nAddAnimator", "(JJ)V", (void*)android_view_RenderNode_addAnimator},
{"nEndAllAnimators", "(J)V", (void*)android_view_RenderNode_endAllAnimators},
+ {"nForceEndAnimators", "(J)V", (void*)android_view_RenderNode_forceEndAnimators},
{"nRequestPositionUpdates", "(JLjava/lang/ref/WeakReference;)V",
(void*)android_view_RenderNode_requestPositionUpdates},
diff --git a/media/java/android/media/AudioDeviceVolumeManager.java b/media/java/android/media/AudioDeviceVolumeManager.java
index 11cacd01f53d..fe58cca9395f 100644
--- a/media/java/android/media/AudioDeviceVolumeManager.java
+++ b/media/java/android/media/AudioDeviceVolumeManager.java
@@ -235,13 +235,7 @@ public class AudioDeviceVolumeManager {
mDeviceVolumeDispatcherStub = new DeviceVolumeDispatcherStub();
}
} else {
- for (ListenerInfo info : mDeviceVolumeListeners) {
- if (info.mListener == vclistener) {
- throw new IllegalArgumentException(
- "attempt to call setDeviceAbsoluteMultiVolumeBehavior() "
- + "on a previously registered listener");
- }
- }
+ mDeviceVolumeListeners.removeIf(info -> info.mDevice.equalTypeAddress(device));
}
mDeviceVolumeListeners.add(listenerInfo);
mDeviceVolumeDispatcherStub.register(true, device, volumes, handlesVolumeAdjustment);
@@ -304,6 +298,28 @@ public class AudioDeviceVolumeManager {
"removeOnDeviceVolumeBehaviorChangedListener");
}
+ /**
+ * Return human-readable name for volume behavior
+ * @param behavior one of the volume behaviors defined in AudioManager
+ * @return a string for the given behavior
+ */
+ public static String volumeBehaviorName(@AudioManager.DeviceVolumeBehavior int behavior) {
+ switch (behavior) {
+ case AudioManager.DEVICE_VOLUME_BEHAVIOR_VARIABLE:
+ return "DEVICE_VOLUME_BEHAVIOR_VARIABLE";
+ case AudioManager.DEVICE_VOLUME_BEHAVIOR_FULL:
+ return "DEVICE_VOLUME_BEHAVIOR_FULL";
+ case AudioManager.DEVICE_VOLUME_BEHAVIOR_FIXED:
+ return "DEVICE_VOLUME_BEHAVIOR_FIXED";
+ case AudioManager.DEVICE_VOLUME_BEHAVIOR_ABSOLUTE:
+ return "DEVICE_VOLUME_BEHAVIOR_ABSOLUTE";
+ case AudioManager.DEVICE_VOLUME_BEHAVIOR_ABSOLUTE_MULTI_MODE:
+ return "DEVICE_VOLUME_BEHAVIOR_ABSOLUTE_MULTI_MODE";
+ default:
+ return "invalid volume behavior " + behavior;
+ }
+ }
+
private final class DeviceVolumeBehaviorDispatcherStub
extends IDeviceVolumeBehaviorDispatcher.Stub implements CallbackUtil.DispatcherStub {
public void register(boolean register) {
diff --git a/media/java/android/media/AudioTrack.java b/media/java/android/media/AudioTrack.java
index 55c558f36880..85cd342b5e11 100644
--- a/media/java/android/media/AudioTrack.java
+++ b/media/java/android/media/AudioTrack.java
@@ -2910,6 +2910,10 @@ public class AudioTrack extends PlayerBase
* For portability, an application should prime the data path to the maximum allowed
* by writing data until the write() method returns a short transfer count.
* This allows play() to start immediately, and reduces the chance of underrun.
+ *<p>
+ * As of {@link android.os.Build.VERSION_CODES#S} the minimum level to start playing
+ * can be obtained using {@link #getStartThresholdInFrames()} and set with
+ * {@link #setStartThresholdInFrames(int)}.
*
* @throws IllegalStateException if the track isn't properly initialized
*/
diff --git a/media/java/android/media/tv/interactive/ITvInteractiveAppManagerCallback.aidl b/media/java/android/media/tv/interactive/ITvInteractiveAppManagerCallback.aidl
index fed86dc9e0a8..2e792b394301 100644
--- a/media/java/android/media/tv/interactive/ITvInteractiveAppManagerCallback.aidl
+++ b/media/java/android/media/tv/interactive/ITvInteractiveAppManagerCallback.aidl
@@ -22,10 +22,10 @@ import android.media.tv.interactive.TvInteractiveAppServiceInfo;
* Interface to receive callbacks from ITvInteractiveAppManager regardless of sessions.
* @hide
*/
-interface ITvInteractiveAppManagerCallback {
+oneway interface ITvInteractiveAppManagerCallback {
void onInteractiveAppServiceAdded(in String iAppServiceId);
void onInteractiveAppServiceRemoved(in String iAppServiceId);
void onInteractiveAppServiceUpdated(in String iAppServiceId);
void onTvInteractiveAppServiceInfoUpdated(in TvInteractiveAppServiceInfo tvIAppInfo);
void onStateChanged(in String iAppServiceId, int type, int state, int err);
-} \ No newline at end of file
+}
diff --git a/media/jni/android_media_MediaCodec.cpp b/media/jni/android_media_MediaCodec.cpp
index c8d2d1ee621f..5850a81b8295 100644
--- a/media/jni/android_media_MediaCodec.cpp
+++ b/media/jni/android_media_MediaCodec.cpp
@@ -1294,45 +1294,46 @@ static void throwCryptoException(JNIEnv *env, status_t err, const char *msg,
std::string defaultMsg = "Unknown Error";
/* translate OS errors to Java API CryptoException errorCodes (which are positive) */
+ jint jerr = 0;
switch (err) {
case ERROR_DRM_NO_LICENSE:
- err = gCryptoErrorCodes.cryptoErrorNoKey;
+ jerr = gCryptoErrorCodes.cryptoErrorNoKey;
defaultMsg = "Crypto key not available";
break;
case ERROR_DRM_LICENSE_EXPIRED:
- err = gCryptoErrorCodes.cryptoErrorKeyExpired;
+ jerr = gCryptoErrorCodes.cryptoErrorKeyExpired;
defaultMsg = "License expired";
break;
case ERROR_DRM_RESOURCE_BUSY:
- err = gCryptoErrorCodes.cryptoErrorResourceBusy;
+ jerr = gCryptoErrorCodes.cryptoErrorResourceBusy;
defaultMsg = "Resource busy or unavailable";
break;
case ERROR_DRM_INSUFFICIENT_OUTPUT_PROTECTION:
- err = gCryptoErrorCodes.cryptoErrorInsufficientOutputProtection;
+ jerr = gCryptoErrorCodes.cryptoErrorInsufficientOutputProtection;
defaultMsg = "Required output protections are not active";
break;
case ERROR_DRM_SESSION_NOT_OPENED:
- err = gCryptoErrorCodes.cryptoErrorSessionNotOpened;
+ jerr = gCryptoErrorCodes.cryptoErrorSessionNotOpened;
defaultMsg = "Attempted to use a closed session";
break;
case ERROR_DRM_INSUFFICIENT_SECURITY:
- err = gCryptoErrorCodes.cryptoErrorInsufficientSecurity;
+ jerr = gCryptoErrorCodes.cryptoErrorInsufficientSecurity;
defaultMsg = "Required security level is not met";
break;
case ERROR_DRM_CANNOT_HANDLE:
- err = gCryptoErrorCodes.cryptoErrorUnsupportedOperation;
+ jerr = gCryptoErrorCodes.cryptoErrorUnsupportedOperation;
defaultMsg = "Operation not supported in this configuration";
break;
case ERROR_DRM_FRAME_TOO_LARGE:
- err = gCryptoErrorCodes.cryptoErrorFrameTooLarge;
+ jerr = gCryptoErrorCodes.cryptoErrorFrameTooLarge;
defaultMsg = "Decrytped frame exceeds size of output buffer";
break;
case ERROR_DRM_SESSION_LOST_STATE:
- err = gCryptoErrorCodes.cryptoErrorLostState;
+ jerr = gCryptoErrorCodes.cryptoErrorLostState;
defaultMsg = "Session state was lost, open a new session and retry";
break;
default: /* Other negative DRM error codes go out best-effort. */
- err = MediaErrorToJavaError(err);
+ jerr = MediaErrorToJavaError(err);
defaultMsg = StrCryptoError(err);
break;
}
@@ -1344,7 +1345,7 @@ static void throwCryptoException(JNIEnv *env, status_t err, const char *msg,
jstring msgObj = env->NewStringUTF(msgStr.c_str());
jthrowable exception =
- (jthrowable)env->NewObject(clazz.get(), constructID, err, msgObj);
+ (jthrowable)env->NewObject(clazz.get(), constructID, jerr, msgObj);
env->Throw(exception);
}
diff --git a/media/jni/android_media_Utils.cpp b/media/jni/android_media_Utils.cpp
index f4a39b3469bb..b7ad6dcf9354 100644
--- a/media/jni/android_media_Utils.cpp
+++ b/media/jni/android_media_Utils.cpp
@@ -18,10 +18,10 @@
#define LOG_TAG "AndroidMediaUtils"
#include <aidl/android/hardware/graphics/common/PlaneLayoutComponentType.h>
-#include <hardware/camera3.h>
#include <ui/GraphicBufferMapper.h>
#include <ui/GraphicTypes.h>
#include <utils/Log.h>
+
#include "android_media_Utils.h"
#define ALIGN(x, mask) ( ((x) + (mask) - 1) & ~((mask) - 1) )
@@ -122,8 +122,8 @@ uint32_t Image_getBlobSize(LockedImage* buffer, bool usingRGBAOverride) {
}
// First check for BLOB transport header at the end of the buffer
- uint8_t* header = blobBuffer + (width - sizeof(struct camera3_jpeg_blob));
- struct camera3_jpeg_blob *blob = (struct camera3_jpeg_blob*)(header);
+ uint8_t* header = blobBuffer + (width - sizeof(struct camera3_jpeg_blob_v2));
+ struct camera3_jpeg_blob_v2 *blob = (struct camera3_jpeg_blob_v2*)(header);
if (blob->jpeg_blob_id == CAMERA3_JPEG_BLOB_ID ||
blob->jpeg_blob_id == CAMERA3_HEIC_BLOB_ID) {
size = blob->jpeg_size;
diff --git a/media/jni/android_media_Utils.h b/media/jni/android_media_Utils.h
index 4feb4f516f1e..c12cec129ede 100644
--- a/media/jni/android_media_Utils.h
+++ b/media/jni/android_media_Utils.h
@@ -50,6 +50,20 @@ int getBufferWidth(BufferItem *buffer);
int getBufferHeight(BufferItem *buffer);
+// Must be in sync with AIDL CameraBlob : android.hardware.camera.device.CameraBlob
+// HALs must NOT copy this definition.
+// for details: http://b/229688810
+typedef struct camera3_jpeg_blob_v2 {
+ uint32_t jpeg_blob_id;
+ uint32_t jpeg_size;
+} camera3_jpeg_blobv2_t;
+
+// Must be in sync with AIDL CameraBlob : android.hardware.camera.device.CameraBlobId
+enum {
+ CAMERA3_JPEG_BLOB_ID = 0x00FF,
+ CAMERA3_JPEG_APP_SEGMENTS_BLOB_ID = 0x0100,
+};
+
}; // namespace android
#endif // _ANDROID_MEDIA_UTILS_H_
diff --git a/packages/CompanionDeviceManager/res/values/strings.xml b/packages/CompanionDeviceManager/res/values/strings.xml
index 3d6bf152f93f..a389bfc42725 100644
--- a/packages/CompanionDeviceManager/res/values/strings.xml
+++ b/packages/CompanionDeviceManager/res/values/strings.xml
@@ -20,7 +20,7 @@
<string name="app_label">Companion Device Manager</string>
<!-- Title of the device association confirmation dialog. -->
- <string name="confirmation_title">Allow &lt;strong&gt;<xliff:g id="app_name" example="Android Wear">%1$s</xliff:g>&lt;/strong&gt; to manage your &lt;strong&gt;<xliff:g id="device_name" example="ASUS ZenWatch 2">%2$s</xliff:g>&lt;/strong&gt;</string>
+ <string name="confirmation_title">Allow &lt;strong&gt;<xliff:g id="app_name" example="Android Wear">%1$s</xliff:g>&lt;/strong&gt; to access your &lt;strong&gt;<xliff:g id="device_name" example="ASUS ZenWatch 2">%2$s</xliff:g>&lt;/strong&gt;</string>
<!-- ================= DEVICE_PROFILE_WATCH and null profile ================= -->
@@ -31,10 +31,7 @@
<string name="chooser_title">Choose a <xliff:g id="profile_name" example="watch">%1$s</xliff:g> to be managed by &lt;strong&gt;<xliff:g id="app_name" example="Android Wear">%2$s</xliff:g>&lt;/strong&gt;</string>
<!-- Description of the privileges the application will get if associated with the companion device of WATCH profile (type) [CHAR LIMIT=NONE] -->
- <string name="summary_watch" product="default"><xliff:g id="app_name" example="Wear">%1$s</xliff:g> will be allowed to interact with your notifications and access your Phone, SMS, Contacts and Calendar permissions.</string>
-
- <!-- Description of the privileges the application will get if associated with the companion device of WATCH profile (type) [CHAR LIMIT=NONE] -->
- <string name="summary_watch" product="tablet"><xliff:g id="app_name" example="Wear">%1$s</xliff:g> will be allowed to interact with your notifications and access your Phone, SMS, Contacts and Calendar permissions.</string>
+ <string name="summary_watch">This app is needed to manage your <xliff:g id="device_name" example="My Watch">%1$s</xliff:g>. <xliff:g id="app_name" example="Android Wear">%2$s</xliff:g> will be allowed to interact with your notifications and access your Phone, SMS, Contacts, Calendar, Call logs and Nearby devices permissions.</string>
<!-- ================= DEVICE_PROFILE_APP_STREAMING ================= -->
diff --git a/packages/CompanionDeviceManager/src/com/android/companiondevicemanager/CompanionDeviceActivity.java b/packages/CompanionDeviceManager/src/com/android/companiondevicemanager/CompanionDeviceActivity.java
index 9e9ec04fbd93..a3aa0100870a 100644
--- a/packages/CompanionDeviceManager/src/com/android/companiondevicemanager/CompanionDeviceActivity.java
+++ b/packages/CompanionDeviceManager/src/com/android/companiondevicemanager/CompanionDeviceActivity.java
@@ -497,17 +497,19 @@ public class CompanionDeviceActivity extends FragmentActivity implements
}
final String deviceName = mSelectedDevice.getDisplayName();
- final Spanned title = getHtmlFromResources(
- this, R.string.confirmation_title, appLabel, deviceName);
+ final String profileName = getString(R.string.profile_name_watch);
+ final Spanned title;
final Spanned summary;
final Drawable profileIcon;
if (deviceProfile == null) {
+ title = getHtmlFromResources(this, R.string.confirmation_title, appLabel, deviceName);
summary = getHtmlFromResources(this, R.string.summary_generic);
profileIcon = getIcon(this, R.drawable.ic_device_other);
mSummary.setVisibility(View.GONE);
} else if (deviceProfile.equals(DEVICE_PROFILE_WATCH)) {
- summary = getHtmlFromResources(this, R.string.summary_watch, appLabel, deviceName);
+ title = getHtmlFromResources(this, R.string.confirmation_title, appLabel, profileName);
+ summary = getHtmlFromResources(this, R.string.summary_watch, deviceName, appLabel);
profileIcon = getIcon(this, R.drawable.ic_watch);
} else {
throw new RuntimeException("Unsupported profile " + deviceProfile);
@@ -535,7 +537,7 @@ public class CompanionDeviceActivity extends FragmentActivity implements
mSummary.setVisibility(View.GONE);
} else if (deviceProfile.equals(DEVICE_PROFILE_WATCH)) {
profileName = getString(R.string.profile_name_watch);
- summary = getHtmlFromResources(this, R.string.summary_watch, appLabel);
+ summary = getHtmlFromResources(this, R.string.summary_watch, profileName, appLabel);
profileIcon = getIcon(this, R.drawable.ic_watch);
} else {
throw new RuntimeException("Unsupported profile " + deviceProfile);
diff --git a/packages/CompanionDeviceManager/src/com/android/companiondevicemanager/CompanionDeviceDiscoveryService.java b/packages/CompanionDeviceManager/src/com/android/companiondevicemanager/CompanionDeviceDiscoveryService.java
index f333b86d4d52..fc5ff085139c 100644
--- a/packages/CompanionDeviceManager/src/com/android/companiondevicemanager/CompanionDeviceDiscoveryService.java
+++ b/packages/CompanionDeviceManager/src/com/android/companiondevicemanager/CompanionDeviceDiscoveryService.java
@@ -123,6 +123,7 @@ public class CompanionDeviceDiscoveryService extends Service {
intent.setAction(ACTION_START_DISCOVERY);
intent.putExtra(EXTRA_ASSOCIATION_REQUEST, associationRequest);
sStateLiveData.setValue(DiscoveryState.STARTING);
+ sScanResultsLiveData.setValue(Collections.emptyList());
context.startService(intent);
}
@@ -173,7 +174,6 @@ public class CompanionDeviceDiscoveryService extends Service {
@Override
public void onDestroy() {
- sScanResultsLiveData.setValue(Collections.emptyList());
super.onDestroy();
if (DEBUG) Log.d(TAG, "onDestroy()");
}
@@ -187,7 +187,6 @@ public class CompanionDeviceDiscoveryService extends Service {
mStopAfterFirstMatch = request.isSingleDevice();
mDiscoveryStarted = true;
sStateLiveData.setValue(DiscoveryState.DISCOVERY_IN_PROGRESS);
- sScanResultsLiveData.setValue(Collections.emptyList());
final List<DeviceFilter<?>> allFilters = request.getDeviceFilters();
final List<BluetoothDeviceFilter> btFilters =
diff --git a/packages/CompanionDeviceManager/src/com/android/companiondevicemanager/DeviceFilterPair.java b/packages/CompanionDeviceManager/src/com/android/companiondevicemanager/DeviceFilterPair.java
index faca1ae3f058..1f59d30207d8 100644
--- a/packages/CompanionDeviceManager/src/com/android/companiondevicemanager/DeviceFilterPair.java
+++ b/packages/CompanionDeviceManager/src/com/android/companiondevicemanager/DeviceFilterPair.java
@@ -47,7 +47,7 @@ class DeviceFilterPair<T extends Parcelable> {
}
String getDisplayName() {
- if (mFilter != null) mFilter.getDeviceDisplayName(mDevice);
+ if (mFilter != null) return mFilter.getDeviceDisplayName(mDevice);
if (mDevice instanceof BluetoothDevice) {
return getDeviceDisplayNameInternal((BluetoothDevice) mDevice);
diff --git a/packages/CtsShim/apk/arm/CtsShim.apk b/packages/CtsShim/apk/arm/CtsShim.apk
index 0c3c4bb24208..fb092862b79e 100644
--- a/packages/CtsShim/apk/arm/CtsShim.apk
+++ b/packages/CtsShim/apk/arm/CtsShim.apk
Binary files differ
diff --git a/packages/CtsShim/apk/arm/CtsShimPriv.apk b/packages/CtsShim/apk/arm/CtsShimPriv.apk
index ee42d081f2f2..07915ce76bb5 100644
--- a/packages/CtsShim/apk/arm/CtsShimPriv.apk
+++ b/packages/CtsShim/apk/arm/CtsShimPriv.apk
Binary files differ
diff --git a/packages/CtsShim/apk/x86/CtsShim.apk b/packages/CtsShim/apk/x86/CtsShim.apk
index 0c3c4bb24208..fb092862b79e 100644
--- a/packages/CtsShim/apk/x86/CtsShim.apk
+++ b/packages/CtsShim/apk/x86/CtsShim.apk
Binary files differ
diff --git a/packages/CtsShim/apk/x86/CtsShimPriv.apk b/packages/CtsShim/apk/x86/CtsShimPriv.apk
index 2bb3750b200d..20e94b6f2dac 100644
--- a/packages/CtsShim/apk/x86/CtsShimPriv.apk
+++ b/packages/CtsShim/apk/x86/CtsShimPriv.apk
Binary files differ
diff --git a/packages/CtsShim/build/Android.bp b/packages/CtsShim/build/Android.bp
index 7cf5385bd841..af3e2102e430 100644
--- a/packages/CtsShim/build/Android.bp
+++ b/packages/CtsShim/build/Android.bp
@@ -47,6 +47,7 @@ android_app {
uses_libs: ["android.test.runner"],
apex_available: [
+ "//apex_available:platform",
"com.android.apex.cts.shim.v2_apk_in_apex_upgrades",
],
}
diff --git a/packages/SettingsLib/AndroidManifest.xml b/packages/SettingsLib/AndroidManifest.xml
index 3e67abfe1960..13f8a372c9b5 100644
--- a/packages/SettingsLib/AndroidManifest.xml
+++ b/packages/SettingsLib/AndroidManifest.xml
@@ -22,16 +22,6 @@
<activity
android:name="com.android.settingslib.users.AvatarPickerActivity"
android:theme="@style/SudThemeGlifV2.DayNight"/>
-
- <activity
- android:name="com.android.settingslib.qrcode.QrCodeScanModeActivity"
- android:exported="true">
- <intent-filter>
- <action android:name="android.settings.BLUETOOTH_LE_AUDIO_QR_CODE_SCANNER"/>
- <category android:name="android.intent.category.DEFAULT"/>
- </intent-filter>
- </activity>
-
</application>
</manifest>
diff --git a/packages/SettingsLib/AppPreference/res/layout/preference_app_header.xml b/packages/SettingsLib/AppPreference/res/layout/preference_app_header.xml
new file mode 100644
index 000000000000..e0d01f9bb2c3
--- /dev/null
+++ b/packages/SettingsLib/AppPreference/res/layout/preference_app_header.xml
@@ -0,0 +1,36 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ Copyright (C) 2022 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+ -->
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:orientation="vertical"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:paddingStart="?android:attr/listPreferredItemPaddingStart"
+ android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
+ android:paddingBottom="16dp"
+ android:paddingTop="8dp"
+ android:clickable="false">
+
+ <TextView
+ android:id="@+id/apps_top_intro_text"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:textDirection="locale"
+ android:clickable="false"
+ android:longClickable="false"
+ android:textAppearance="@style/TextAppearance.TopIntroText" />
+
+</LinearLayout>
diff --git a/packages/SettingsLib/SettingsTheme/res/values/styles.xml b/packages/SettingsLib/SettingsTheme/res/values/styles.xml
index aaab0f041fe3..00bd14122251 100644
--- a/packages/SettingsLib/SettingsTheme/res/values/styles.xml
+++ b/packages/SettingsLib/SettingsTheme/res/values/styles.xml
@@ -26,4 +26,11 @@
<style name="TextAppearance.CategoryTitle.SettingsLib"
parent="@android:style/TextAppearance.DeviceDefault.Medium">
</style>
+
+ <style name="TextAppearance.TopIntroText"
+ parent="@android:style/TextAppearance.DeviceDefault">
+ <item name="android:textSize">14sp</item>
+ <item name="android:textColor">?android:attr/textColorSecondary</item>
+ </style>
+
</resources>
diff --git a/packages/SettingsLib/TopIntroPreference/Android.bp b/packages/SettingsLib/TopIntroPreference/Android.bp
index cd0bdea9425f..ecf2a72021ed 100644
--- a/packages/SettingsLib/TopIntroPreference/Android.bp
+++ b/packages/SettingsLib/TopIntroPreference/Android.bp
@@ -16,6 +16,7 @@ android_library {
static_libs: [
"androidx.annotation_annotation",
"androidx.preference_preference",
+ "SettingsLibSettingsTheme",
],
sdk_version: "system_current",
min_sdk_version: "21",
diff --git a/packages/SettingsLib/TopIntroPreference/res/values/styles.xml b/packages/SettingsLib/TopIntroPreference/res/values/styles.xml
deleted file mode 100644
index b6ca41fb6b6d..000000000000
--- a/packages/SettingsLib/TopIntroPreference/res/values/styles.xml
+++ /dev/null
@@ -1,23 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- Copyright (C) 2021 The Android Open Source Project
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- -->
-<resources>
- <style name="TextAppearance.TopIntroText"
- parent="@android:style/TextAppearance.DeviceDefault">
- <item name="android:textSize">14sp</item>
- <item name="android:textColor">?android:attr/textColorSecondary</item>
- </style>
-</resources>
diff --git a/packages/SettingsLib/res/layout/qrcode_scanner_fragment.xml b/packages/SettingsLib/res/layout/qrcode_scanner_fragment.xml
deleted file mode 100644
index 0a7fe0903348..000000000000
--- a/packages/SettingsLib/res/layout/qrcode_scanner_fragment.xml
+++ /dev/null
@@ -1,102 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- Copyright (C) 2022 The Android Open Source Project
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-
-<LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:androidprv="http://schemas.android.com/apk/prv/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical">
-
- <LinearLayout
- android:id="@+id/sud_layout_icon_container"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_weight="3"
- android:layout_marginBottom="35dp">
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_gravity="bottom"
- android:gravity="center"
- android:orientation="vertical">
- <ImageView
- android:id="@+id/sud_layout_icon"
- android:src="@drawable/ic_qr_code_scanner"
- android:tint="?androidprv:attr/colorAccentPrimaryVariant"
- android:layout_width="@dimen/qrcode_icon_size"
- android:layout_height="@dimen/qrcode_icon_size"
- android:contentDescription="@null"/>
-
- <TextView
- android:id="@+id/sud_layout_title"
- style="@style/QrCodeScanner"
- android:textSize="24sp"
- android:text="@string/bt_le_audio_scan_qr_code"
- android:gravity="center"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_marginTop="19dp"/>
-
- <TextView
- android:id="@+id/sud_layout_subtitle"
- style="@style/QrCodeScanner"
- android:text="@string/bt_le_audio_scan_qr_code_scanner"
- android:gravity="center"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_marginTop="8dp"/>
- </LinearLayout>
- </LinearLayout>
-
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_weight="7"
- android:orientation="vertical">
-
- <FrameLayout
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="top"
- android:gravity="center"
- android:clipChildren="true">
- <TextureView
- android:id="@+id/preview_view"
- android:layout_marginStart="@dimen/qrcode_preview_margin"
- android:layout_marginEnd="@dimen/qrcode_preview_margin"
- android:layout_width="match_parent"
- android:layout_height="@dimen/qrcode_preview_size"/>
- </FrameLayout>
-
- <TextView
- android:id="@+id/error_message"
- style="@style/TextAppearance.ErrorText"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_marginTop="16dp"
- android:layout_marginStart="?attr/sudMarginStart"
- android:layout_marginEnd="?attr/sudMarginEnd"
- android:gravity="center"
- android:layout_gravity="center"
- android:visibility="invisible"/>
-
- </LinearLayout>
-
-
-</LinearLayout>
-
diff --git a/packages/SettingsLib/res/values-af/strings.xml b/packages/SettingsLib/res/values-af/strings.xml
index 0533a2ab56a7..9820b3ec9521 100644
--- a/packages/SettingsLib/res/values-af/strings.xml
+++ b/packages/SettingsLib/res/values-af/strings.xml
@@ -279,7 +279,7 @@
<string name="debug_networking_category" msgid="6829757985772659599">"Inligtingruiling"</string>
<string name="wifi_display_certification" msgid="1805579519992520381">"Draadlose skermsertifisering"</string>
<string name="wifi_verbose_logging" msgid="1785910450009679371">"Aktiveer Wi-Fi-woordryke aanmelding"</string>
- <string name="wifi_scan_throttling" msgid="2985624788509913617">"Regulering van Wi-Fi-opsporing"</string>
+ <string name="wifi_scan_throttling" msgid="2985624788509913617">"Regulering van Wi-fi-opsporing"</string>
<string name="wifi_non_persistent_mac_randomization" msgid="7482769677894247316">"Nie-aanhoudende MAC-verewekansiging vir wi-fi"</string>
<string name="mobile_data_always_on" msgid="8275958101875563572">"Mobiele data is altyd aktief"</string>
<string name="tethering_hardware_offload" msgid="4116053719006939161">"Hardewareversnelling vir verbinding"</string>
@@ -667,9 +667,6 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Skakel skerm aan"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Laat toe dat die skerm aangeskakel word"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Laat ’n program toe om die skerm aan te skakel. As jy toestemming gee, kan die program die skerm enige tyd sonder jou uitdruklike bedoeling aanskakel."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"Skandeer QR-kode"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Plaas die QR-kode hieronder in die middel om te begin luister"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"QR-kode is nie ’n geldige formaat nie"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"Hou op om <xliff:g id="APP_NAME">%1$s</xliff:g> uit te saai?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"As jy <xliff:g id="SWITCHAPP">%1$s</xliff:g> uitsaai of die uitvoer verander, sal jou huidige uitsending stop"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"Saai <xliff:g id="SWITCHAPP">%1$s</xliff:g> uit"</string>
diff --git a/packages/SettingsLib/res/values-am/strings.xml b/packages/SettingsLib/res/values-am/strings.xml
index b94cb7e4abd3..7551c3e8df18 100644
--- a/packages/SettingsLib/res/values-am/strings.xml
+++ b/packages/SettingsLib/res/values-am/strings.xml
@@ -667,9 +667,6 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"ማያ ገጽን ያብሩ"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"ማያ ገጹን ማብራት ይፍቀዱ"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"አንድ መተግበሪያ ማያ ገጹን እንዲያበራ ይፍቀዱለት። ከተሰጠ፣ መተግበሪያው ያለእርስዎ ግልጽ ሐሳብ በማንኛውም ጊዜ ማያ ገጹን ሊያበራ ይችላል።"</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"QR ኮድን ይቃኙ"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"ማዳመጥ ለመጀመር ከታች ያለውን QR ኮድ መሃል ላይ ያድርጉት"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"QR ኮድ ልክ ያልኾነ ቅርጸት ነው"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"<xliff:g id="APP_NAME">%1$s</xliff:g>ን ማሰራጨት ይቁም?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"<xliff:g id="SWITCHAPP">%1$s</xliff:g>ን ካሰራጩ ወይም ውፅዓትን ከቀየሩ የአሁኑ ስርጭትዎ ይቆማል"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"<xliff:g id="SWITCHAPP">%1$s</xliff:g> ያሰራጩ"</string>
diff --git a/packages/SettingsLib/res/values-ar/strings.xml b/packages/SettingsLib/res/values-ar/strings.xml
index ad3ea6b992b9..a1342cd3f011 100644
--- a/packages/SettingsLib/res/values-ar/strings.xml
+++ b/packages/SettingsLib/res/values-ar/strings.xml
@@ -117,7 +117,7 @@
<string name="bluetooth_profile_opp" msgid="6692618568149493430">"نقل الملف"</string>
<string name="bluetooth_profile_hid" msgid="2969922922664315866">"جهاز الإرسال"</string>
<string name="bluetooth_profile_pan" msgid="1006235139308318188">"استخدام الإنترنت"</string>
- <string name="bluetooth_profile_pbap" msgid="7064307749579335765">"مشاركة جهة الاتصال"</string>
+ <string name="bluetooth_profile_pbap" msgid="7064307749579335765">"مشاركة جهات الاتصال"</string>
<string name="bluetooth_profile_pbap_summary" msgid="2955819694801952056">"استخدام مع مشاركة جهة الاتصال"</string>
<string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"مشاركة اتصال الإنترنت"</string>
<string name="bluetooth_profile_map" msgid="8907204701162107271">"الرسائل النصية"</string>
@@ -223,8 +223,8 @@
<item msgid="581904787661470707">"الأسرع"</item>
</string-array>
<string name="choose_profile" msgid="343803890897657450">"اختيار ملف شخصي"</string>
- <string name="category_personal" msgid="6236798763159385225">"شخصي"</string>
- <string name="category_work" msgid="4014193632325996115">"للعمل"</string>
+ <string name="category_personal" msgid="6236798763159385225">"التطبيقات الشخصية"</string>
+ <string name="category_work" msgid="4014193632325996115">"تطبيقات العمل"</string>
<string name="development_settings_title" msgid="140296922921597393">"خيارات المطورين"</string>
<string name="development_settings_enable" msgid="4285094651288242183">"تفعيل خيارات المطورين"</string>
<string name="development_settings_summary" msgid="8718917813868735095">"تعيين خيارات تطوير التطبيق"</string>
@@ -569,7 +569,7 @@
<string name="user_add_user_item_title" msgid="2394272381086965029">"المستخدم"</string>
<string name="user_add_profile_item_title" msgid="3111051717414643029">"ملف شخصي محظور"</string>
<string name="user_add_user_title" msgid="5457079143694924885">"هل تريد إضافة مستخدم جديد؟"</string>
- <string name="user_add_user_message_long" msgid="1527434966294733380">"‏يمكنك مشاركة هذا الجهاز مع أشخاص آخرين من خلال إنشاء حسابات لمستخدمين إضافيين. وسيحصل كل مستخدم على مساحته الخاصة التي يمكنه تخصيصها بتطبيقاته وخلفياته التي يريدها وغيرها. كما يمكن للمستخدمين أيضًا ضبط إعدادات الجهاز مثل Wi-Fi والتي تؤثر في جميع المستخدمين.\n\nعند إضافة مستخدم جديد، عليه إعداد مساحته.\n\nيمكن لأي مستخدم تحديث التطبيقات لجميع المستخدمين الآخرين. وقد لا يتم نقل إعدادات وخدمات \"سهولة الاستخدام\" إلى المستخدم الجديد."</string>
+ <string name="user_add_user_message_long" msgid="1527434966294733380">"‏يمكنك مشاركة هذا الجهاز مع أشخاص آخرين من خلال إنشاء حسابات لمستخدمين إضافيين. وسيحصل كل مستخدم على مساحته الخاصة التي يمكنه تخصيصها بتطبيقاته وخلفياته التي يريدها وغير ذلك. ويمكن أيضًا للمستخدمين ضبط إعدادات الجهاز مثل Wi-Fi والتي تؤثر في جميع المستخدمين.\n\nعند إضافة مستخدم جديد، عليه إعداد مساحته.\n\nيمكن لأي مستخدم تحديث التطبيقات لجميع المستخدمين الآخرين. وقد لا يتم نقل إعدادات وخدمات \"سهولة الاستخدام\" إلى المستخدم الجديد."</string>
<string name="user_add_user_message_short" msgid="3295959985795716166">"عند إضافة مستخدم جديد، عليه إعداد مساحته.\n\nويمكن لأي مستخدم تحديث التطبيقات لجميع المستخدمين الآخرين."</string>
<string name="user_setup_dialog_title" msgid="8037342066381939995">"هل تريد إعداد المستخدم الآن؟"</string>
<string name="user_setup_dialog_message" msgid="269931619868102841">"يُرجى التأكّد من أن الشخص يمكنه استخدام الجهاز الآن وإعداد مساحته."</string>
@@ -667,17 +667,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"تشغيل الشاشة"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"السماح بتشغيل الشاشة"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"يمكنك السماح لأحد التطبيقات بتشغيل الشاشة. في حال منحت هذا الإذن، قد يشغِّل التطبيق الشاشة في أي وقت بدون إذن صريح منك."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"إجراء مسح ضوئي لرمز الاستجابة السريعة"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"لبدء الاستماع، امسَح ضوئيًا رمز الاستجابة السريعة التالي."</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"تنسيق رمز الاستجابة السريعة غير صالح."</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"هل تريد إيقاف بث تطبيق <xliff:g id="APP_NAME">%1$s</xliff:g>؟"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"إذا أجريت بث تطبيق <xliff:g id="SWITCHAPP">%1$s</xliff:g> أو غيَّرت جهاز الإخراج، سيتوقَف البث الحالي."</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"بث تطبيق <xliff:g id="SWITCHAPP">%1$s</xliff:g>"</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"تغيير جهاز الإخراج"</string>
- <!-- no translation found for back_navigation_animation (8105467568421689484) -->
- <skip />
- <!-- no translation found for back_navigation_animation_summary (741292224121599456) -->
- <skip />
- <!-- no translation found for back_navigation_animation_dialog (8696966520944625596) -->
- <skip />
+ <string name="back_navigation_animation" msgid="8105467568421689484">"صور متحركة تعرض إيماءة الرجوع إلى الخلف التنبؤية"</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"فعِّل الصور المتحركة في النظام لإيماءة الرجوع إلى الخلف التنبؤية."</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"‏يفعّل هذا الإعداد الصور المتحركة في النظام للصور المتحركة التي تعرض إيماءة الرجوع إلى الخلف التنبؤية. يتطلب الإعداد ضبط enableOnBackInvokedCallback إلى true لكل تطبيق في ملف البيان."</string>
</resources>
diff --git a/packages/SettingsLib/res/values-as/strings.xml b/packages/SettingsLib/res/values-as/strings.xml
index 8583057de9ca..ea0e7a65088a 100644
--- a/packages/SettingsLib/res/values-as/strings.xml
+++ b/packages/SettingsLib/res/values-as/strings.xml
@@ -570,7 +570,7 @@
<string name="user_add_profile_item_title" msgid="3111051717414643029">"সীমিত প্ৰ\'ফাইল"</string>
<string name="user_add_user_title" msgid="5457079143694924885">"নতুন ব্যৱহাৰকাৰী যোগ কৰিবনে?"</string>
<string name="user_add_user_message_long" msgid="1527434966294733380">"আপুনি অতিৰিক্ত ব্যৱহাৰকাৰীক যোগ কৰি এই ডিভাইচটো অন্য় ব্য়ক্তিৰ সৈতে শ্বেয়াৰ কৰিব পাৰে। প্ৰতিজন ব্যৱহাৰকাৰীৰ বাবে নিজাকৈ ঠাই আছে যাক তেওঁলোকে এপ্, ৱালপেপাৰ আৰু অন্য়ান্য় বস্তুৰ বাবে নিজৰ উপযোগিতা অনুযায়ী ব্যৱহাৰ কৰিব পাৰে। ব্যৱহাৰকাৰীসকলে সকলোকে প্ৰভাৱান্বিত কৰা ৱাই-ফাইৰ নিচিনা ডিভাইচৰ ছেটিং সাল-সলনি কৰিবও পাৰে।\n\nআপুনি যেতিয়া কোনো নতুন ব্যৱহাৰকাৰীক যোগ কৰে সেই ব্য়ক্তিজনে নিজেই নিজৰ বাবে ঠাই ছেট আপ কৰিব লাগিব।\n\nসকলো ব্যৱহাৰকাৰীয়ে অন্য় ব্যৱহাৰকাৰীৰ বাবে এপ্‌সমূহ আপডে’ট কৰিব পাৰে। সাধ্য় সুবিধাসমূহৰ ছেটিং আৰু সেৱাসমূহ নতুন ব্যৱহাৰকাৰীলৈ স্থানান্তৰ নহ\'বও পাৰে।"</string>
- <string name="user_add_user_message_short" msgid="3295959985795716166">"আপুনি যেতিয়া এজন নতুন ব্যৱহাৰকাৰী যোগ কৰে, তেওঁ নিজৰ ঠাই ছেট আপ কৰা প্ৰয়োজন।\n\nযিকোনো ব্যৱহাৰকাৰীয়ে সকলো ব্যৱহাৰকাৰীৰ বাবে এপ্ আপডে\'ট কৰিব পাৰে।"</string>
+ <string name="user_add_user_message_short" msgid="3295959985795716166">"আপুনি যেতিয়া এজন নতুন ব্যৱহাৰকাৰী যোগ কৰে, তেওঁ নিজৰ ঠাই ছেট আপ কৰাৰ প্ৰয়োজন।\n\nযিকোনো ব্যৱহাৰকাৰীয়ে অন্য সকলো ব্যৱহাৰকাৰীৰ বাবে এপ্ আপডে\'ট কৰিব পাৰে।"</string>
<string name="user_setup_dialog_title" msgid="8037342066381939995">"ব্যৱহাৰকাৰী এতিয়া ছেট আপ কৰিবনে?"</string>
<string name="user_setup_dialog_message" msgid="269931619868102841">"ডিভাইচটো লৈ নিজৰ ঠাই ছেটআপ কৰিবলৈ নতুন ব্যৱহাৰকাৰী উপলব্ধ থকাটো নিশ্চিত কৰক"</string>
<string name="user_setup_profile_dialog_message" msgid="4788197052296962620">"এতিয়া প্ৰ\'ফাইল ছেট আপ কৰিবনে?"</string>
@@ -667,9 +667,6 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"স্ক্ৰীন অন কৰক"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"স্ক্ৰীনখন অন কৰিবলৈ অনুমতি দিয়ক"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"এপ্‌টোক স্ক্ৰীনখন অন কৰিবলৈ অনুমতি দিয়ক। যদি অনুমতি দিয়া হয়, এপ্‌টোৱে আপোনাৰ স্পষ্ট উদ্দেশ্য অবিহনেও যিকোনো সময়তে স্ক্ৰীনখন অন কৰিব পাৰে।"</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"কিউআৰ ক’ডটো স্কেন কৰক"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"শুনিবলৈ আৰম্ভ কৰিবলৈ, তলৰ মাজৰ অংশত কিউআৰ ক’ডটো ৰাখক"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"কিউআৰ ক’ডটো মান্য ফৰ্মেটৰ নহয়"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"<xliff:g id="APP_NAME">%1$s</xliff:g>ৰ সম্প্ৰচাৰ কৰা বন্ধ কৰিবনে?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"যদি আপুনি <xliff:g id="SWITCHAPP">%1$s</xliff:g>ৰ সম্প্ৰচাৰ কৰে অথবা আউটপুট সলনি কৰে, তেন্তে, আপোনাৰ বৰ্তমানৰ সম্প্ৰচাৰ বন্ধ হৈ যাব"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"<xliff:g id="SWITCHAPP">%1$s</xliff:g> সম্প্ৰচাৰ কৰক"</string>
diff --git a/packages/SettingsLib/res/values-az/strings.xml b/packages/SettingsLib/res/values-az/strings.xml
index e78e11b5f565..8a2a2f77bba5 100644
--- a/packages/SettingsLib/res/values-az/strings.xml
+++ b/packages/SettingsLib/res/values-az/strings.xml
@@ -667,9 +667,6 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Ekranı aktiv etmək"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Ekranı aktiv etməyə icazə verin"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Tətbiqin ekranı aktiv etməsinə icazə verin. İcazə verilərsə, tətbiq istənilən vaxt sizə soruşmadan ekranı aktiv edə bilər."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"QR kodu skanlayın"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Dinləməyə başlamaq üçün aşağıda QR kodu mərkəzə yerləşdirin"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"QR kodu doğru formatda deyil"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"<xliff:g id="APP_NAME">%1$s</xliff:g> tətbiqinin yayımlanması dayandırılsın?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"<xliff:g id="SWITCHAPP">%1$s</xliff:g> tətbiqini yayımlasanız və ya nəticəni dəyişsəniz, cari yayımınız dayandırılacaq"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"<xliff:g id="SWITCHAPP">%1$s</xliff:g> tətbiqini yayımlayın"</string>
diff --git a/packages/SettingsLib/res/values-b+sr+Latn/strings.xml b/packages/SettingsLib/res/values-b+sr+Latn/strings.xml
index 1aaff825e7e9..a91e9f7fb51d 100644
--- a/packages/SettingsLib/res/values-b+sr+Latn/strings.xml
+++ b/packages/SettingsLib/res/values-b+sr+Latn/strings.xml
@@ -667,9 +667,6 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Uključite ekran"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Dozvoli uključivanje ekrana"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Dozvoljava aplikaciji da uključi ekran. Ako se omogući, aplikacija može da uključi ekran u bilo kom trenutku bez vaše eksplicitne namere."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"Skenirajte QR kôd"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Da biste počeli da slušate, centrirajte QR kôd ispod"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"QR kôd nije u važećem formatu"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"Želite da zaustavite emitovanje aplikacije <xliff:g id="APP_NAME">%1$s</xliff:g>?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"Ako emitujete aplikaciju <xliff:g id="SWITCHAPP">%1$s</xliff:g> ili promenite izlaz, aktuelno emitovanje će se zaustaviti"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"Emitujte aplikaciju <xliff:g id="SWITCHAPP">%1$s</xliff:g>"</string>
diff --git a/packages/SettingsLib/res/values-be/strings.xml b/packages/SettingsLib/res/values-be/strings.xml
index 17d31ff302e4..eace050fbb76 100644
--- a/packages/SettingsLib/res/values-be/strings.xml
+++ b/packages/SettingsLib/res/values-be/strings.xml
@@ -667,17 +667,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Уключэнне экрана"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Дазволіць уключэнне экрана"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Дазволіць праграме ўключаць экран. З гэтым дазволам праграма зможа ў любы час уключаць экран без вашага яўнага намеру."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"Сканіраваць QR-код"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Каб пачаць праслухванне, памясціце ў цэнтр QR-код, які знаходзіцца ўнізе"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"QR-код мае несапраўдны фармат"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"Спыніць трансляцыю праграмы \"<xliff:g id="APP_NAME">%1$s</xliff:g>\"?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"Пры пераключэнні на праграму \"<xliff:g id="SWITCHAPP">%1$s</xliff:g>\" ці змяненні вываду бягучая трансляцыя спыняецца"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"Трансляцыя праграмы \"<xliff:g id="SWITCHAPP">%1$s</xliff:g>\""</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"Змяненне вываду"</string>
- <!-- no translation found for back_navigation_animation (8105467568421689484) -->
- <skip />
- <!-- no translation found for back_navigation_animation_summary (741292224121599456) -->
- <skip />
- <!-- no translation found for back_navigation_animation_dialog (8696966520944625596) -->
- <skip />
+ <string name="back_navigation_animation" msgid="8105467568421689484">"Анімацыя падказкі для жэста вяртання"</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"Уключыць сістэмную анімацыю падказкі для жэстаў вяртання."</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"Гэта налада ўключае сістэмную анімацыю падказкі для жэста вяртання. Для гэтага неабходна задаць у файле маніфеста для параметра enableOnBackInvokedCallback значэнне \"True\" для кожнай праграмы."</string>
</resources>
diff --git a/packages/SettingsLib/res/values-bg/strings.xml b/packages/SettingsLib/res/values-bg/strings.xml
index 5cbc02226183..deacb02b834f 100644
--- a/packages/SettingsLib/res/values-bg/strings.xml
+++ b/packages/SettingsLib/res/values-bg/strings.xml
@@ -667,17 +667,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Включване на екрана"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Разрешаване на включването на екрана"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Разрешете на дадено приложение да включва екрана. Ако го направите, то може да включва екрана по всяко време без явното ви намерение."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"Сканиране на QR код"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"За да започнете да слушате, центрирайте QR кода по-долу"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"Невалиден формат на QR кода"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"Да се спре ли предаването на <xliff:g id="APP_NAME">%1$s</xliff:g>?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"Ако предавате <xliff:g id="SWITCHAPP">%1$s</xliff:g> или промените изхода, текущото ви предаване ще бъде прекратено"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"Предаване на <xliff:g id="SWITCHAPP">%1$s</xliff:g>"</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"Промяна на изхода"</string>
- <!-- no translation found for back_navigation_animation (8105467568421689484) -->
- <skip />
- <!-- no translation found for back_navigation_animation_summary (741292224121599456) -->
- <skip />
- <!-- no translation found for back_navigation_animation_dialog (8696966520944625596) -->
- <skip />
+ <string name="back_navigation_animation" msgid="8105467568421689484">"Анимации за предвиждащия жест за връщане назад"</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"Активиране на системните анимации за предвиждащия жест за връщане назад."</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"Тази настройка активира системните анимации за предвиждащите жестове. За целта във файла на манифеста трябва да зададете enableOnBackInvokedCallback на true за отделните приложения."</string>
</resources>
diff --git a/packages/SettingsLib/res/values-bn/strings.xml b/packages/SettingsLib/res/values-bn/strings.xml
index 6585bc14b9d5..c20106fca38e 100644
--- a/packages/SettingsLib/res/values-bn/strings.xml
+++ b/packages/SettingsLib/res/values-bn/strings.xml
@@ -667,9 +667,6 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"স্ক্রিন চালু করুন"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"স্ক্রিন চালু করার অনুমতি দিন"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"অ্যাপকে স্ক্রিন চালু করার অনুমতি দিন। অনুমতি দেওয়া হলে, অ্যাপ আপনার এক্সপ্লিসিট ইনটেন্ট ছাড়াই যেকোনও সময় স্ক্রিন চালু করতে পারবে।"</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"QR কোড স্ক্যান করুন"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"শোনা শুরু করতে, নিচের QR কোডটি মাঝখানে রাখুন"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"QR কোডের ফর্ম্যাট সঠিক নয়"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"<xliff:g id="APP_NAME">%1$s</xliff:g> সম্প্রচার বন্ধ করবেন?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"আপনি <xliff:g id="SWITCHAPP">%1$s</xliff:g> সম্প্রচার করলে বা আউটপুট পরিবর্তন করলে, আপনার বর্তমান সম্প্রচার বন্ধ হয়ে যাবে"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"<xliff:g id="SWITCHAPP">%1$s</xliff:g> সম্প্রচার করুন"</string>
diff --git a/packages/SettingsLib/res/values-bs/strings.xml b/packages/SettingsLib/res/values-bs/strings.xml
index b020a9b9c18e..9b1e0b16feff 100644
--- a/packages/SettingsLib/res/values-bs/strings.xml
+++ b/packages/SettingsLib/res/values-bs/strings.xml
@@ -117,7 +117,7 @@
<string name="bluetooth_profile_opp" msgid="6692618568149493430">"Prenošenje fajla"</string>
<string name="bluetooth_profile_hid" msgid="2969922922664315866">"Ulazni uređaj"</string>
<string name="bluetooth_profile_pan" msgid="1006235139308318188">"Pristup internetu"</string>
- <string name="bluetooth_profile_pbap" msgid="7064307749579335765">"Dijeljenje kontakta"</string>
+ <string name="bluetooth_profile_pbap" msgid="7064307749579335765">"Dijeljenje kontakata"</string>
<string name="bluetooth_profile_pbap_summary" msgid="2955819694801952056">"Koristi za dijeljenje kontakta"</string>
<string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Dijeljenje internet veze"</string>
<string name="bluetooth_profile_map" msgid="8907204701162107271">"SMS-ovi"</string>
@@ -610,7 +610,7 @@
<string name="guest_exit_button" msgid="5774985819191803960">"Napusti način rada za gosta"</string>
<string name="guest_reset_button" msgid="2515069346223503479">"Poništi sesiju gosta"</string>
<string name="guest_exit_quick_settings_button" msgid="1912362095913765471">"Izlazak iz sesije gosta"</string>
- <string name="guest_notification_ephemeral" msgid="7263252466950923871">"Sva aktivnost će biti izbrisana kada napustite sesiju"</string>
+ <string name="guest_notification_ephemeral" msgid="7263252466950923871">"Sva aktivnost će se izbrisati pri napuštanju"</string>
<string name="guest_notification_non_ephemeral" msgid="6843799963012259330">"Možete sačuvati ili izbrisati svoju aktivnost pri izlasku"</string>
<string name="guest_notification_non_ephemeral_non_first_login" msgid="8009307983766934876">"Poništite da odmah izbrišete aktivnost iz sesije ili je možete sačuvati ili izbrisati pri izlasku"</string>
<string name="user_image_take_photo" msgid="467512954561638530">"Snimite fotografiju"</string>
@@ -667,14 +667,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Uključivanje ekrana"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Dozvolite uključivanje ekrana"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Dozvolite aplikaciji da uključi ekran. Ako se odobri, aplikacija može uključiti ekran bilo kada bez vaše izričite namjere."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"Skenirajte QR kôd"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Da pokrenete slušanje, centrirajte QR kôd ispod"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"Format QR koda nije važeći"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"Zaustaviti emitiranje aplikacije <xliff:g id="APP_NAME">%1$s</xliff:g>?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"Ako emitirate aplikaciju <xliff:g id="SWITCHAPP">%1$s</xliff:g> ili promijenite izlaz, trenutno emitiranje će se zaustaviti"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"Emitiraj aplikaciju <xliff:g id="SWITCHAPP">%1$s</xliff:g>"</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"Promijeni izlaz"</string>
- <string name="back_navigation_animation" msgid="8105467568421689484">"Animacije za pokret povratka s predviđanjem"</string>
- <string name="back_navigation_animation_summary" msgid="741292224121599456">"Omogući animacije sustava za pokret povratka s predviđanjem."</string>
- <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"Ova postavka omogućuje animacije sustava za animaciju pokreta s predviđanjem. Zahtijeva postavljanje dopuštenja enableOnBackInvokedCallback po aplikaciji na True u datoteci manifesta."</string>
+ <string name="back_navigation_animation" msgid="8105467568421689484">"Animacije predvidljivog pokreta unazad"</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"Omogućite animacije sistema za predvidljivi pokret unazad."</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"Ova postavka omogućava animacije sistema za animaciju predvidljivih pokreta. Potrebno je po aplikaciji postaviti vrijednost za enableOnBackInvokedCallback na tačno u fajlu deklaracije."</string>
</resources>
diff --git a/packages/SettingsLib/res/values-ca/strings.xml b/packages/SettingsLib/res/values-ca/strings.xml
index 43aa18503dc9..92615007c17a 100644
--- a/packages/SettingsLib/res/values-ca/strings.xml
+++ b/packages/SettingsLib/res/values-ca/strings.xml
@@ -667,17 +667,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Activa la pantalla"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Permet que activi la pantalla"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Permet que una aplicació activi la pantalla. Si concedeixes aquest permís, pot ser que l\'aplicació activi la pantalla en qualsevol moment sense la teva intenció explícita."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"Escaneja un codi QR"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Per començar a escoltar, centra el codi QR més avall"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"El codi QR no té un format vàlid"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"Vols deixar d\'emetre <xliff:g id="APP_NAME">%1$s</xliff:g>?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"Si emets <xliff:g id="SWITCHAPP">%1$s</xliff:g> o canvies la sortida, l\'emissió actual s\'aturarà"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"Emet <xliff:g id="SWITCHAPP">%1$s</xliff:g>"</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"Canvia la sortida"</string>
- <!-- no translation found for back_navigation_animation (8105467568421689484) -->
- <skip />
- <!-- no translation found for back_navigation_animation_summary (741292224121599456) -->
- <skip />
- <!-- no translation found for back_navigation_animation_dialog (8696966520944625596) -->
- <skip />
+ <string name="back_navigation_animation" msgid="8105467568421689484">"Animacions per a les accions de tornada predictives"</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"Activa animacions del sistema per a la tornada predictiva."</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"Aquesta configuració activa animacions del sistema per a accions gestuals predictives. Requereix definir enableOnBackInvokedCallback com a \"true\" en cada aplicació al fitxer de manifest."</string>
</resources>
diff --git a/packages/SettingsLib/res/values-cs/strings.xml b/packages/SettingsLib/res/values-cs/strings.xml
index e49a8a604cae..a51f2ee28b9a 100644
--- a/packages/SettingsLib/res/values-cs/strings.xml
+++ b/packages/SettingsLib/res/values-cs/strings.xml
@@ -667,17 +667,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Zapínat obrazovku"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Povolit zapínání obrazovky"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Povolte aplikaci zapínat obrazovku. Pokud aplikace bude mít toto oprávnění, může kdykoli zapnout obrazovku bez explicitního intentu."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"Skenování QR kódu"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Pokud chcete začít poslouchat, zaměřte QR kód níže"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"QR kód není platný formát"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"Zastavit vysílání v aplikaci <xliff:g id="APP_NAME">%1$s</xliff:g>?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"Pokud budete vysílat v aplikaci <xliff:g id="SWITCHAPP">%1$s</xliff:g> nebo změníte výstup, aktuální vysílání se zastaví"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"Vysílat v aplikaci <xliff:g id="SWITCHAPP">%1$s</xliff:g>"</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"Změna výstupu"</string>
- <!-- no translation found for back_navigation_animation (8105467568421689484) -->
- <skip />
- <!-- no translation found for back_navigation_animation_summary (741292224121599456) -->
- <skip />
- <!-- no translation found for back_navigation_animation_dialog (8696966520944625596) -->
- <skip />
+ <string name="back_navigation_animation" msgid="8105467568421689484">"Prediktivní animace gesta Zpět"</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"Povolit systémové animace prediktivního gesta Zpět"</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"Toto nastavení aktivuje systémové prediktivní animace gest. Vyžaduje, aby v souborech manifestu jednotlivých aplikací byl nastaven atribut enableOnBackInvokedCallback na hodnotu True."</string>
</resources>
diff --git a/packages/SettingsLib/res/values-da/strings.xml b/packages/SettingsLib/res/values-da/strings.xml
index 2a99ac0e6ae1..f3991645993b 100644
--- a/packages/SettingsLib/res/values-da/strings.xml
+++ b/packages/SettingsLib/res/values-da/strings.xml
@@ -607,7 +607,7 @@
<string name="guest_exit_dialog_message_non_ephemeral" msgid="223385323235719442">"Du kan gemme aktivitet fra den aktuelle session eller slette alle apps og data"</string>
<string name="guest_exit_clear_data_button" msgid="3425812652180679014">"Slet"</string>
<string name="guest_exit_save_data_button" msgid="3690974510644963547">"Gem"</string>
- <string name="guest_exit_button" msgid="5774985819191803960">"Afslut gæstetilstanden"</string>
+ <string name="guest_exit_button" msgid="5774985819191803960">"Afslut gæstetilstand"</string>
<string name="guest_reset_button" msgid="2515069346223503479">"Nulstil gæstesession"</string>
<string name="guest_exit_quick_settings_button" msgid="1912362095913765471">"Afslut gæstesession"</string>
<string name="guest_notification_ephemeral" msgid="7263252466950923871">"Al aktivitet slettes ved afslutning"</string>
@@ -667,9 +667,6 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Aktivér skærmen"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Tillad aktivering af skærmen"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Tillad, at en app aktiverer skærmen. Hvis du giver denne tilladelse, kan appen til enhver tid aktiverer skærmen, uden at du eksplicit har bedt om det."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"Scan QR-kode"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Centrer QR-koden nedenfor for at gå i gang med at lytte"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"QR-koden har ikke et gyldigt format"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"Stop udsendelsen <xliff:g id="APP_NAME">%1$s</xliff:g>?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"Hvis du udsender <xliff:g id="SWITCHAPP">%1$s</xliff:g> eller skifter output, stopper din aktuelle udsendelse"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"Udsend <xliff:g id="SWITCHAPP">%1$s</xliff:g>"</string>
diff --git a/packages/SettingsLib/res/values-de/strings.xml b/packages/SettingsLib/res/values-de/strings.xml
index c72fd59b5548..941f8024b7f0 100644
--- a/packages/SettingsLib/res/values-de/strings.xml
+++ b/packages/SettingsLib/res/values-de/strings.xml
@@ -667,17 +667,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Display aktivieren"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Aktivieren des Displays erlauben"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Einer App erlauben, das Display zu aktivieren. Wenn du diese Erlaubnis erteilst, kann die App jederzeit das Display aktivieren – auch ohne deine explizite Absicht."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"QR-Code scannen"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Scanne zum Anhören den QR-Code unten"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"Das Format des QR-Codes ist nicht gültig"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"<xliff:g id="APP_NAME">%1$s</xliff:g> nicht mehr streamen?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"Wenn du <xliff:g id="SWITCHAPP">%1$s</xliff:g> streamst oder die Ausgabe änderst, wird dein aktueller Stream beendet"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"<xliff:g id="SWITCHAPP">%1$s</xliff:g> streamen"</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"Ausgabe ändern"</string>
- <!-- no translation found for back_navigation_animation (8105467568421689484) -->
- <skip />
- <!-- no translation found for back_navigation_animation_summary (741292224121599456) -->
- <skip />
- <!-- no translation found for back_navigation_animation_dialog (8696966520944625596) -->
- <skip />
+ <string name="back_navigation_animation" msgid="8105467568421689484">"Animationen für intelligente „Zurück“-Touch-Geste"</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"Du kannst Systemanimationen für die intelligente „Zurück“-Touch-Geste aktivieren."</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"Diese Einstellung aktiviert Systemanimationen für intelligente Touch-Gesten. Dazu muss in der Manifestdatei enableOnBackInvokedCallback auf App-Ebene auf „true“ gesetzt werden."</string>
</resources>
diff --git a/packages/SettingsLib/res/values-el/strings.xml b/packages/SettingsLib/res/values-el/strings.xml
index d13f533513cc..c15ea1099d03 100644
--- a/packages/SettingsLib/res/values-el/strings.xml
+++ b/packages/SettingsLib/res/values-el/strings.xml
@@ -667,17 +667,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Ενεργοποίηση οθόνης"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Να επιτρέπεται η ενεργοποίηση της οθόνης"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Επιτρέψτε σε μια εφαρμογή να ενεργοποιεί την οθόνη. Αν παραχωρήσετε την άδεια, η εφαρμογή ενδέχεται να ενεργοποιεί την οθόνη ανά πάσα στιγμή, χωρίς να εκφράσετε σαφή πρόθεση."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"Σάρωση κωδικού QR"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Για έναρξη της ακρόασης, κεντράρετε τον παρακάτω κωδικό QR"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"Ο κωδικός QR δεν έχει έγκυρη μορφή"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"Διακοπή μετάδοσης με την εφαρμογή <xliff:g id="APP_NAME">%1$s</xliff:g>;"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"Εάν κάνετε μετάδοση με την εφαρμογή <xliff:g id="SWITCHAPP">%1$s</xliff:g> ή αλλάξετε την έξοδο, η τρέχουσα μετάδοση θα σταματήσει"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"Μετάδοση με την εφαρμογή <xliff:g id="SWITCHAPP">%1$s</xliff:g>"</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"Αλλαγή εξόδου"</string>
- <!-- no translation found for back_navigation_animation (8105467568421689484) -->
- <skip />
- <!-- no translation found for back_navigation_animation_summary (741292224121599456) -->
- <skip />
- <!-- no translation found for back_navigation_animation_dialog (8696966520944625596) -->
- <skip />
+ <string name="back_navigation_animation" msgid="8105467568421689484">"Κινούμ. εικόνες μετάβασης προς τα πίσω με πρόβλεψη"</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"Ενεργοποίηση κινούμενων εικόνων συστήματος για μετάβαση προς τα πίσω με πρόβλεψη."</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"Αυτή η ρύθμιση ενεργοποιεί τις κινούμενες εικόνες συστήματος για τις κινούμενες εικόνες κινήσεων με πρόβλεψη. Απαιτεί τη ρύθμιση της παραμέτρου enableOnBackInvokedCallback ως αληθούς σε κάθε εφαρμογή στο αρχείο μανιφέστου."</string>
</resources>
diff --git a/packages/SettingsLib/res/values-en-rAU/strings.xml b/packages/SettingsLib/res/values-en-rAU/strings.xml
index 9c4b3329a6b8..8a79c6092f89 100644
--- a/packages/SettingsLib/res/values-en-rAU/strings.xml
+++ b/packages/SettingsLib/res/values-en-rAU/strings.xml
@@ -667,9 +667,6 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Turn screen on"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Allow turning the screen on"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Allow an app to turn the screen on. If granted, the app may turn on the screen at any time without your explicit intent."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"Scan QR code"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"To start listening, centre the QR code below"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"QR code isn\'t a valid format"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"Stop broadcasting <xliff:g id="APP_NAME">%1$s</xliff:g>?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"If you broadcast <xliff:g id="SWITCHAPP">%1$s</xliff:g> or change the output, your current broadcast will stop"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"Broadcast <xliff:g id="SWITCHAPP">%1$s</xliff:g>"</string>
diff --git a/packages/SettingsLib/res/values-en-rCA/strings.xml b/packages/SettingsLib/res/values-en-rCA/strings.xml
index ceefae040e86..36a1f7704da4 100644
--- a/packages/SettingsLib/res/values-en-rCA/strings.xml
+++ b/packages/SettingsLib/res/values-en-rCA/strings.xml
@@ -667,9 +667,6 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Turn screen on"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Allow turning the screen on"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Allow an app to turn the screen on. If granted, the app may turn on the screen at any time without your explicit intent."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"Scan QR code"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"To start listening, centre the QR code below"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"QR code isn\'t a valid format"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"Stop broadcasting <xliff:g id="APP_NAME">%1$s</xliff:g>?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"If you broadcast <xliff:g id="SWITCHAPP">%1$s</xliff:g> or change the output, your current broadcast will stop"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"Broadcast <xliff:g id="SWITCHAPP">%1$s</xliff:g>"</string>
diff --git a/packages/SettingsLib/res/values-en-rGB/strings.xml b/packages/SettingsLib/res/values-en-rGB/strings.xml
index 9c4b3329a6b8..8a79c6092f89 100644
--- a/packages/SettingsLib/res/values-en-rGB/strings.xml
+++ b/packages/SettingsLib/res/values-en-rGB/strings.xml
@@ -667,9 +667,6 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Turn screen on"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Allow turning the screen on"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Allow an app to turn the screen on. If granted, the app may turn on the screen at any time without your explicit intent."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"Scan QR code"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"To start listening, centre the QR code below"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"QR code isn\'t a valid format"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"Stop broadcasting <xliff:g id="APP_NAME">%1$s</xliff:g>?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"If you broadcast <xliff:g id="SWITCHAPP">%1$s</xliff:g> or change the output, your current broadcast will stop"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"Broadcast <xliff:g id="SWITCHAPP">%1$s</xliff:g>"</string>
diff --git a/packages/SettingsLib/res/values-en-rIN/strings.xml b/packages/SettingsLib/res/values-en-rIN/strings.xml
index 9c4b3329a6b8..8a79c6092f89 100644
--- a/packages/SettingsLib/res/values-en-rIN/strings.xml
+++ b/packages/SettingsLib/res/values-en-rIN/strings.xml
@@ -667,9 +667,6 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Turn screen on"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Allow turning the screen on"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Allow an app to turn the screen on. If granted, the app may turn on the screen at any time without your explicit intent."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"Scan QR code"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"To start listening, centre the QR code below"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"QR code isn\'t a valid format"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"Stop broadcasting <xliff:g id="APP_NAME">%1$s</xliff:g>?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"If you broadcast <xliff:g id="SWITCHAPP">%1$s</xliff:g> or change the output, your current broadcast will stop"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"Broadcast <xliff:g id="SWITCHAPP">%1$s</xliff:g>"</string>
diff --git a/packages/SettingsLib/res/values-en-rXC/strings.xml b/packages/SettingsLib/res/values-en-rXC/strings.xml
index 18d0d0c1aedd..efdfc4fcc832 100644
--- a/packages/SettingsLib/res/values-en-rXC/strings.xml
+++ b/packages/SettingsLib/res/values-en-rXC/strings.xml
@@ -667,9 +667,6 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‏‎‏‏‏‏‏‎‏‎‏‏‎‏‎‏‎‏‎‏‏‎‎‏‏‏‏‏‏‎‎‎‏‎‏‎‎‏‏‏‏‎‎‏‎‎‏‎‎‏‎‏‎‎‏‎‎‎‏‏‏‎‎‎‏‏‎‎‎‎‎Turn screen on‎‏‎‎‏‎"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‏‎‏‏‏‏‏‏‏‎‏‎‏‎‏‏‏‏‏‏‎‎‎‏‎‎‎‎‎‏‏‎‏‏‎‎‏‏‏‎‎‏‎‎‎‎‎‎‎‏‎‏‏‎‎‎‎‎‎‎‎‏‎‏‏‏‎‏‏‏‏‎Allow turning the screen on‎‏‎‎‏‎"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‏‎‏‏‏‎‎‎‏‎‎‏‏‎‏‏‏‎‏‏‏‎‏‏‎‎‏‎‏‎‎‎‎‏‎‏‎‏‎‏‎‎‏‎‎‎‏‎‏‎‏‏‎‎‏‏‎‏‏‏‏‏‎‎‎Allow an app to turn the screen on. If granted, the app may turn on the screen at any time without your explicit intent.‎‏‎‎‏‎"</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‏‎‏‏‏‏‏‎‏‏‎‎‎‎‏‏‎‏‏‏‏‏‏‏‏‏‏‎‏‏‎‏‏‎‎‏‏‏‎‏‎‏‎‎‎‎‏‎‏‎‎‏‏‏‏‏‎‎‎‏‎‎‏‏‏‎‎‏‏‏‎Scan QR code‎‏‎‎‏‎"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‏‎‏‏‏‏‏‏‏‎‎‎‎‎‎‏‏‏‏‎‎‎‎‏‏‏‎‏‏‎‎‎‏‏‏‏‎‎‏‏‏‎‎‏‎‎‎‎‎‎‏‏‎‏‎‏‏‎‎‎‏‎‏‏‏‏‏‎‎‏‏‎To start listening, center the QR code below‎‏‎‎‏‎"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‏‎‏‏‏‏‏‏‏‎‏‎‏‎‎‏‎‎‎‏‎‏‏‏‏‎‎‏‏‏‏‏‎‎‎‎‎‏‎‏‏‎‏‏‎‎‏‎‏‏‏‎‎‎‎‎‎‏‏‎‎‏‎‎‏‏‎‏‏‏‎‎QR code isn\'t a valid format‎‏‎‎‏‎"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‏‎‏‏‏‏‏‏‏‎‎‏‎‏‎‏‏‎‏‎‏‏‎‏‏‎‏‏‎‏‏‎‎‎‏‎‏‎‏‎‏‏‏‎‎‏‎‏‏‎‎‏‏‏‏‏‏‏‏‏‏‎‎‏‎‏‏‎‎‏‎‎Stop broadcasting ‎‏‎‎‏‏‎<xliff:g id="APP_NAME">%1$s</xliff:g>‎‏‎‎‏‏‏‎?‎‏‎‎‏‎"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‏‎‏‏‏‎‏‎‏‏‏‎‏‏‏‎‎‎‏‏‏‏‎‏‏‎‎‎‏‎‎‎‎‏‏‎‏‎‎‏‎‏‎‏‏‏‎‏‎‏‏‎‏‏‎‏‎‎‏‎‎‏‎‎‎‏‎If you broadcast ‎‏‎‎‏‏‎<xliff:g id="SWITCHAPP">%1$s</xliff:g>‎‏‎‎‏‏‏‎ or change the output, your current broadcast will stop‎‏‎‎‏‎"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‏‎‏‏‏‏‏‏‏‎‎‏‏‏‏‏‏‎‎‏‎‏‏‎‏‏‏‎‎‎‎‏‎‏‏‏‏‏‎‏‎‏‎‎‏‎‎‎‎‏‏‎‎‏‏‏‎‏‎‏‏‏‎‏‏‏‏‎‏‎‎‎Broadcast ‎‏‎‎‏‏‎<xliff:g id="SWITCHAPP">%1$s</xliff:g>‎‏‎‎‏‏‏‎‎‏‎‎‏‎"</string>
diff --git a/packages/SettingsLib/res/values-es-rUS/strings.xml b/packages/SettingsLib/res/values-es-rUS/strings.xml
index 846e6658349c..030b9d7a2360 100644
--- a/packages/SettingsLib/res/values-es-rUS/strings.xml
+++ b/packages/SettingsLib/res/values-es-rUS/strings.xml
@@ -667,17 +667,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Activar pantalla"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Permitir activación de la pantalla"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Permite que una app active la pantalla. Si se otorga permiso, la app podría activar la pantalla en cualquier momento sin que lo pidas de manera explícita."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"Escanear código QR"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Para comenzar a escuchar, centra el código QR que aparece a continuación"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"El código QR no tiene un formato válido"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"¿Quieres dejar de transmitir <xliff:g id="APP_NAME">%1$s</xliff:g>?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"Si transmites <xliff:g id="SWITCHAPP">%1$s</xliff:g> o cambias la salida, tu transmisión actual se detendrá"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"Transmitir <xliff:g id="SWITCHAPP">%1$s</xliff:g>"</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"Cambia la salida"</string>
- <!-- no translation found for back_navigation_animation (8105467568421689484) -->
- <skip />
- <!-- no translation found for back_navigation_animation_summary (741292224121599456) -->
- <skip />
- <!-- no translation found for back_navigation_animation_dialog (8696966520944625596) -->
- <skip />
+ <string name="back_navigation_animation" msgid="8105467568421689484">"Animaciones de retroceso predictivas"</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"Habilitar animaciones del sistema para gestos de retroceso predictivos."</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"Esta configuración habilita las animaciones del sistema para la animación de gestos predictiva. Se requiere la configuración por app de enableOnBackInvokedCallback en verdadero en el archivo de manifiesto."</string>
</resources>
diff --git a/packages/SettingsLib/res/values-es/strings.xml b/packages/SettingsLib/res/values-es/strings.xml
index 9aa6f382b724..71e0b0ef8dc5 100644
--- a/packages/SettingsLib/res/values-es/strings.xml
+++ b/packages/SettingsLib/res/values-es/strings.xml
@@ -667,17 +667,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Encender pantalla"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Permitir encender la pantalla"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Permite que una aplicación encienda la pantalla. Si das este permiso, la aplicación puede encender la pantalla en cualquier momento sin que se lo pidas."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"Escanear código QR"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Para empezar a escuchar, centra el código QR aquí abajo"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"El formato del código QR no es válido"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"¿Dejar de emitir <xliff:g id="APP_NAME">%1$s</xliff:g>?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"Si emites <xliff:g id="SWITCHAPP">%1$s</xliff:g> o cambias la salida, tu emisión actual se detendrá"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"Emitir <xliff:g id="SWITCHAPP">%1$s</xliff:g>"</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"Cambiar salida"</string>
- <!-- no translation found for back_navigation_animation (8105467568421689484) -->
- <skip />
- <!-- no translation found for back_navigation_animation_summary (741292224121599456) -->
- <skip />
- <!-- no translation found for back_navigation_animation_dialog (8696966520944625596) -->
- <skip />
+ <string name="back_navigation_animation" msgid="8105467568421689484">"Animaciones para acciones de retorno predictivas"</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"Habilitar animaciones del sistema para acciones de retorno predictivas."</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"Este ajuste habilita animaciones del sistema para acciones gestuales predictivas. Exige definir el valor de enableOnBackInvokedCallback en \"verdadero\" para cada aplicación en el archivo de manifiesto."</string>
</resources>
diff --git a/packages/SettingsLib/res/values-et/strings.xml b/packages/SettingsLib/res/values-et/strings.xml
index 582fdb37a99d..ad2601a9ea57 100644
--- a/packages/SettingsLib/res/values-et/strings.xml
+++ b/packages/SettingsLib/res/values-et/strings.xml
@@ -667,17 +667,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Ekraani sisselülitamine"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Luba ekraani sisselülitamine"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Rakendusel lubatakse ekraan sisse lülitada. Kui annate loa, võib rakendus ekraani igal ajal sisse lülitada ilma teie sõnaselge kavatsuseta."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"QR-koodi skannimine"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Kuulamise alustamiseks paigutage QR-kood allpool keskele"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"QR-kood ei ole sobilik vorming"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"Kas peatada rakenduse <xliff:g id="APP_NAME">%1$s</xliff:g> ülekandmine?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"Kui kannate rakendust <xliff:g id="SWITCHAPP">%1$s</xliff:g> üle või muudate väljundit, peatatakse teie praegune ülekanne"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"Rakenduse <xliff:g id="SWITCHAPP">%1$s</xliff:g> ülekandmine"</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"Väljundi muutmine"</string>
- <!-- no translation found for back_navigation_animation (8105467568421689484) -->
- <skip />
- <!-- no translation found for back_navigation_animation_summary (741292224121599456) -->
- <skip />
- <!-- no translation found for back_navigation_animation_dialog (8696966520944625596) -->
- <skip />
+ <string name="back_navigation_animation" msgid="8105467568421689484">"Tagasiliigutuse prognoosi animatsioon"</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"Lubage süsteemi animatsioonid, et näha prognoositud tagasiliigutusi."</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"See seade võimaldab süsteemi animatsioonidel prognoosida tagasiliigutusi. See nõuab manifestifailis rakendusepõhise atribuudi enableOnBackInvokedCallback määramist tõeseks."</string>
</resources>
diff --git a/packages/SettingsLib/res/values-eu/strings.xml b/packages/SettingsLib/res/values-eu/strings.xml
index e0b7ad5690fd..e72801386c55 100644
--- a/packages/SettingsLib/res/values-eu/strings.xml
+++ b/packages/SettingsLib/res/values-eu/strings.xml
@@ -667,17 +667,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Piztu pantaila"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Eman pantaila pizteko baimena"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Eman pantaila pizteko baimena aplikazioei. Baimena emanez gero, aplikazioek edonoiz piztu ahal izango dute pantaila, zuk halako asmorik izan ez arren."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"Eskaneatu QR kodea"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Entzuten hasteko, zentratu beheko QR kodea"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"QR kodearen formatuak ez du balio"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"<xliff:g id="APP_NAME">%1$s</xliff:g> aplikazioaren audioa igortzeari utzi nahi diozu?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"<xliff:g id="SWITCHAPP">%1$s</xliff:g> aplikazioaren audioa igortzen baduzu, edo audio-irteera aldatzen baduzu, une hartako igorpena eten egingo da"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"Igorri <xliff:g id="SWITCHAPP">%1$s</xliff:g> aplikazioaren audioa"</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"Aldatu audio-irteera"</string>
- <!-- no translation found for back_navigation_animation (8105467568421689484) -->
- <skip />
- <!-- no translation found for back_navigation_animation_summary (741292224121599456) -->
- <skip />
- <!-- no translation found for back_navigation_animation_dialog (8696966520944625596) -->
- <skip />
+ <string name="back_navigation_animation" msgid="8105467568421689484">"Atzera egiteko keinuaren animazio-igarleak"</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"Gaitu atzera egiteko keinuaren sistemaren animazio-igarleak."</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"Atzera egiteko keinuaren sistemaren animazio-igarleak gaitzen ditu ezarpenak. enableOnBackInvokedCallback-ek egiazko gisa ezarrita egon behar du aplikazio bakoitzaren manifestu-fitxategian."</string>
</resources>
diff --git a/packages/SettingsLib/res/values-fa/strings.xml b/packages/SettingsLib/res/values-fa/strings.xml
index 8e732779da0c..9b2bf3614ba8 100644
--- a/packages/SettingsLib/res/values-fa/strings.xml
+++ b/packages/SettingsLib/res/values-fa/strings.xml
@@ -667,17 +667,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"روشن کردن صفحه‌نمایش"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"اعطای اجازه برای روشن کردن صفحه‌نمایش"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"به برنامه اجازه می‌دهد صفحه‌نمایش را روشن کند. اگر اجازه داده شود، ممکن است این برنامه در هر زمانی بدون هدف صریح شما صفحه‌نمایش را روشن کند."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"اسکن رمزینه پاسخ‌سریع"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"برای گوش دادن، رمزینه پاسخ‌سریع زیر را در مرکز کادر قرار دهید"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"قالب رمزینه پاسخ‌سریع معتبر نیست"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"همه‌فرستی <xliff:g id="APP_NAME">%1$s</xliff:g> متوقف شود؟"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"اگر <xliff:g id="SWITCHAPP">%1$s</xliff:g> را همه‌فرستی کنید یا خروجی را تغییر دهید، همه‌فرستی کنونی متوقف خواهد شد"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"همه‌فرستی <xliff:g id="SWITCHAPP">%1$s</xliff:g>"</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"تغییر خروجی"</string>
- <!-- no translation found for back_navigation_animation (8105467568421689484) -->
- <skip />
- <!-- no translation found for back_navigation_animation_summary (741292224121599456) -->
- <skip />
- <!-- no translation found for back_navigation_animation_dialog (8696966520944625596) -->
- <skip />
+ <string name="back_navigation_animation" msgid="8105467568421689484">"پویانمایی‌های اشاره برگشت پیش‌بینانه"</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"پویانمایی‌های سیستم را برای اشاره برگشت پیش‌بینانه فعال کنید."</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"‏این تنظیم پویانمایی‌های سیستم را برای پویانمایی اشاره برگشت پیش‌بینانه فعال می‌کند. این تنظیم مستلزم تنظیم شدن enableOnBackInvokedCallback مربوط به هر برنامه روی صحیح در فایل مانیفست است."</string>
</resources>
diff --git a/packages/SettingsLib/res/values-fi/strings.xml b/packages/SettingsLib/res/values-fi/strings.xml
index 89c7ed38c6e0..0e697f5ae2e2 100644
--- a/packages/SettingsLib/res/values-fi/strings.xml
+++ b/packages/SettingsLib/res/values-fi/strings.xml
@@ -667,17 +667,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Käynnistä näyttö"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Salli näytön käynnistäminen"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Salli sovelluksen käynnistää näyttö. Jos sovellus saa luvan, se voi käynnistää näytön itsenäisesti milloin tahansa."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"Skannaa QR-koodi"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Aloita kuuntelu keskittämällä alla olevaan QR-koodiin"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"QR-koodin muoto ei kelpaa"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"Lopetetaanko <xliff:g id="APP_NAME">%1$s</xliff:g>-sovelluksen lähettäminen?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"Jos lähetät <xliff:g id="SWITCHAPP">%1$s</xliff:g>-sovellusta tai muutat ulostuloa, nykyinen lähetyksesi loppuu"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"Lähetä <xliff:g id="SWITCHAPP">%1$s</xliff:g>-sovellusta"</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"Muuta ulostuloa"</string>
- <!-- no translation found for back_navigation_animation (8105467568421689484) -->
- <skip />
- <!-- no translation found for back_navigation_animation_summary (741292224121599456) -->
- <skip />
- <!-- no translation found for back_navigation_animation_dialog (8696966520944625596) -->
- <skip />
+ <string name="back_navigation_animation" msgid="8105467568421689484">"Takaisin siirtymisen ennakoivat animaatiot"</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"Ota käyttöön takaisin siirtymisen ennakoivat järjestelmäanimaatiot."</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"Asetus ottaa järjestelmäanimaatiot käyttöön ennakoiville eleanimaatioille. Se edellyttää, että enableOnBackInvokedCallback-arvo on Tosi sovelluksen manifestitiedostossa."</string>
</resources>
diff --git a/packages/SettingsLib/res/values-fr-rCA/strings.xml b/packages/SettingsLib/res/values-fr-rCA/strings.xml
index 6a005dbf7675..318bbb4d3ac5 100644
--- a/packages/SettingsLib/res/values-fr-rCA/strings.xml
+++ b/packages/SettingsLib/res/values-fr-rCA/strings.xml
@@ -667,17 +667,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Activation de l\'écran"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Autoriser l\'activation de l\'écran"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Autorisez une application à activer l\'écran. Lorsque vous accordez cette autorisation, l\'application peut activer l\'écran à tout moment sans votre volonté explicite."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"Numériser le code QR"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Pour commencer à écouter, centrez le code QR ci-dessous"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"Le format du code QR est incorrect"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"Arrêter la diffusion de <xliff:g id="APP_NAME">%1$s</xliff:g>?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"Si vous diffusez <xliff:g id="SWITCHAPP">%1$s</xliff:g> ou changez la sortie, votre diffusion actuelle s\'arrêtera"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"Diffuser <xliff:g id="SWITCHAPP">%1$s</xliff:g>"</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"Changer la sortie"</string>
- <!-- no translation found for back_navigation_animation (8105467568421689484) -->
- <skip />
- <!-- no translation found for back_navigation_animation_summary (741292224121599456) -->
- <skip />
- <!-- no translation found for back_navigation_animation_dialog (8696966520944625596) -->
- <skip />
+ <string name="back_navigation_animation" msgid="8105467568421689484">"Animations pour le retour prédictif"</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"Activer les animations système pour le retour prédictif."</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"Ce paramètre permet d\'activer les animations du système pour l\'animation des gestes prédictifs. Cela exige de définir le paramètre enableOnBackInvokedCallback à Vrai pour chaque application dans le fichier de configuration."</string>
</resources>
diff --git a/packages/SettingsLib/res/values-fr/strings.xml b/packages/SettingsLib/res/values-fr/strings.xml
index 47eafc32352f..0b4303715165 100644
--- a/packages/SettingsLib/res/values-fr/strings.xml
+++ b/packages/SettingsLib/res/values-fr/strings.xml
@@ -610,7 +610,7 @@
<string name="guest_exit_button" msgid="5774985819191803960">"Quitter le mode Invité"</string>
<string name="guest_reset_button" msgid="2515069346223503479">"Réinitialiser la session Invité"</string>
<string name="guest_exit_quick_settings_button" msgid="1912362095913765471">"Quitter le mode Invité"</string>
- <string name="guest_notification_ephemeral" msgid="7263252466950923871">"Toute l\'activité sera supprimée une fois la session quittée"</string>
+ <string name="guest_notification_ephemeral" msgid="7263252466950923871">"Toute l\'activité sera supprimée à la fin de la session"</string>
<string name="guest_notification_non_ephemeral" msgid="6843799963012259330">"Vous pouvez enregistrer ou supprimer l\'activité en quittant"</string>
<string name="guest_notification_non_ephemeral_non_first_login" msgid="8009307983766934876">"Réinitialisez la session pour supprimer immédiatement l\'activité. Vous pourrez aussi l\'enregistrer ou la supprimer en quittant la session."</string>
<string name="user_image_take_photo" msgid="467512954561638530">"Prendre une photo"</string>
@@ -667,17 +667,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Activer l\'écran"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Autoriser l\'activation de l\'écran"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Autoriser une appli à activer l\'écran. Si l\'autorisation est accordée, l\'appli peut activer l\'écran à tout moment sans votre intention explicite."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"Scanner un code QR"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Pour commencer à écouter, centrez le code QR ci-dessous"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"Le format de code QR n\'est pas valide"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"Arrêter la diffusion de <xliff:g id="APP_NAME">%1$s</xliff:g> ?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"Si vous diffusez <xliff:g id="SWITCHAPP">%1$s</xliff:g> ou que vous modifiez le résultat, votre annonce actuelle s\'arrêtera"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"Diffuser <xliff:g id="SWITCHAPP">%1$s</xliff:g>"</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"Modifier le résultat"</string>
- <!-- no translation found for back_navigation_animation (8105467568421689484) -->
- <skip />
- <!-- no translation found for back_navigation_animation_summary (741292224121599456) -->
- <skip />
- <!-- no translation found for back_navigation_animation_dialog (8696966520944625596) -->
- <skip />
+ <string name="back_navigation_animation" msgid="8105467568421689484">"Animations pour prévisualiser le geste de retour"</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"Activer les animations système pour la prévisualisation du geste de retour."</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"Ce paramètre active les animations système pour la prévisualisation du geste de retour. Pour cela, enableOnBackInvokedCallback doit être défini sur \"True\" dans le fichier manifeste de chaque appli."</string>
</resources>
diff --git a/packages/SettingsLib/res/values-gl/strings.xml b/packages/SettingsLib/res/values-gl/strings.xml
index 78c9b53fb8fa..f0e7172e3c9e 100644
--- a/packages/SettingsLib/res/values-gl/strings.xml
+++ b/packages/SettingsLib/res/values-gl/strings.xml
@@ -601,7 +601,7 @@
<string name="guest_reset_and_restart_dialog_title" msgid="3396657008451616041">"Queres restablecer a sesión de convidado?"</string>
<string name="guest_reset_and_restart_dialog_message" msgid="2764425635305200790">"Iniciarase unha nova sesión de convidado e eliminaranse todas as aplicacións e datos desta sesión"</string>
<string name="guest_exit_dialog_title" msgid="1846494656849381804">"Saír do modo de convidado?"</string>
- <string name="guest_exit_dialog_message" msgid="1743218864242719783">"Eliminaranse as aplicacións e os datos da sesión de convidado"</string>
+ <string name="guest_exit_dialog_message" msgid="1743218864242719783">"Eliminaranse as aplicacións e os datos da sesión de convidado actual"</string>
<string name="guest_exit_dialog_button" msgid="1736401897067442044">"Saír"</string>
<string name="guest_exit_dialog_title_non_ephemeral" msgid="7675327443743162986">"Gardar actividade do convidado?"</string>
<string name="guest_exit_dialog_message_non_ephemeral" msgid="223385323235719442">"Podes gardar a actividade da sesión ou eliminar todas as aplicacións e datos"</string>
@@ -667,17 +667,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Activar a pantalla"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Permitir activación da pantalla"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Permite que unha aplicación active a pantalla. Se lle dás permiso, a aplicación poderá activar a pantalla en calquera momento sen que llo pidas."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"Escanear código QR"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Para comezar a escoitar audio, encadra o seguinte código QR"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"O formato do código QR non é válido"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"Queres deixar de emitir contido a través de <xliff:g id="APP_NAME">%1$s</xliff:g>?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"Se emites contido a través de <xliff:g id="SWITCHAPP">%1$s</xliff:g> ou cambias de saída, a emisión en curso deterase"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"Emitir contido a través de <xliff:g id="SWITCHAPP">%1$s</xliff:g>"</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"Cambiar de saída"</string>
- <!-- no translation found for back_navigation_animation (8105467568421689484) -->
- <skip />
- <!-- no translation found for back_navigation_animation_summary (741292224121599456) -->
- <skip />
- <!-- no translation found for back_navigation_animation_dialog (8696966520944625596) -->
- <skip />
+ <string name="back_navigation_animation" msgid="8105467568421689484">"Animacións para o xesto preditivo de volver atrás"</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"Activa as animacións do sistema para o xesto preditivo de volver atrás."</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"Esta opción de configuración activa as animacións do sistema para o xesto preditivo de volver atrás. É preciso definir enableOnBackInvokedCallback como True (verdadeiro) para cada aplicación no ficheiro de manifesto."</string>
</resources>
diff --git a/packages/SettingsLib/res/values-gu/strings.xml b/packages/SettingsLib/res/values-gu/strings.xml
index 1cc4bfa255e9..374c7d8c4473 100644
--- a/packages/SettingsLib/res/values-gu/strings.xml
+++ b/packages/SettingsLib/res/values-gu/strings.xml
@@ -667,9 +667,6 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"સ્ક્રીન ચાલુ કરો"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"સ્ક્રીન ચાલુ કરવાની મંજૂરી આપો"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"ઍપને સ્ક્રીન ચાલુ કરવાની મંજૂરી આપો. જો મંજૂરી આપી હોય, તો ઍપ તમારા સ્પષ્ટ હેતુ વિના કોઈપણ સમયે સ્ક્રીન ચાલુ કરી શકે છે."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"QR કોડ સ્કૅન કરો"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"સાંભળવાનું શરૂ કરવા માટે, QR કોડને નીચે ફ્રેમની મધ્યમાં લાવો"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"આ QR કોડ માન્ય ફૉર્મેટમાં નથી"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"<xliff:g id="APP_NAME">%1$s</xliff:g> બ્રોડકાસ્ટ કરવાનું રોકીએ?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"જો તમે <xliff:g id="SWITCHAPP">%1$s</xliff:g> બ્રોડકાસ્ટ કરો અથવા આઉટપુટ બદલો, તો તમારું હાલનું બ્રોડકાસ્ટ બંધ થઈ જશે"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"<xliff:g id="SWITCHAPP">%1$s</xliff:g> બ્રોડકાસ્ટ કરો"</string>
diff --git a/packages/SettingsLib/res/values-hi/strings.xml b/packages/SettingsLib/res/values-hi/strings.xml
index 5de0d420177a..47b01f3159ed 100644
--- a/packages/SettingsLib/res/values-hi/strings.xml
+++ b/packages/SettingsLib/res/values-hi/strings.xml
@@ -569,7 +569,7 @@
<string name="user_add_user_item_title" msgid="2394272381086965029">"उपयोगकर्ता"</string>
<string name="user_add_profile_item_title" msgid="3111051717414643029">"प्रतिबंधित प्रोफ़ाइल"</string>
<string name="user_add_user_title" msgid="5457079143694924885">"नया उपयोगकर्ता जोड़ें?"</string>
- <string name="user_add_user_message_long" msgid="1527434966294733380">"आप और ज़्यादा उपयोगकर्ता बनाकर इस डिवाइस को दूसरे लोगों के साथ शेयर कर सकते हैं. हर उपयोगकर्ता के पास अपनी जगह होती है, जिसमें वह मनपसंद तरीके से ऐप्लिकेशन, वॉलपेपर और दूसरी चीज़ों में बदलाव कर सकते हैं. उपयोगकर्ता वाई-फ़ाई जैसी डिवाइस सेटिंग में भी बदलाव कर सकते हैं, जिसका असर हर किसी पर पड़ेगा.\n\nजब आप कोई नया उपयोगकर्ता जोड़ते हैं तो उन्हें अपनी जगह सेट करनी होगी.\n\nकोई भी उपयोगकर्ता दूसरे सभी उपयोगकर्ताओं के लिए ऐप्लिकेशन अपडेट कर सकता है. ऐसा भी हो सकता है कि सुलभता सेटिंग और सेवाएं नए उपयोगकर्ता को ट्रांसफ़र न हो पाएं."</string>
+ <string name="user_add_user_message_long" msgid="1527434966294733380">"नए उपयोगकर्ता जोड़कर इस डिवाइस को दूसरे लोगों के साथ शेयर किया जा सकता है. हर उपयोगकर्ता के पास अपनी जगह होती है, जिसमें वे ऐप्लिकेशन, वॉलपेपर, और दूसरी चीज़ों में मनमुताबिक बदलाव कर सकते हैं. उपयोगकर्ता वाई-फ़ाई जैसी डिवाइस सेटिंग में भी बदलाव कर सकते हैं, जिसका असर हर किसी पर पड़ता है.\n\nजब किसी नए उपयोगकर्ता को जोड़ा जाता है, तो उसे अपनी जगह सेट करनी होती है.\n\nकोई भी उपयोगकर्ता, दूसरे सभी उपयोगकर्ताओं के लिए ऐप्लिकेशन अपडेट कर सकता है. ऐसा भी हो सकता है कि सुलभता सेटिंग और सेवाएं नए उपयोगकर्ता को ट्रांसफ़र न हो पाएं."</string>
<string name="user_add_user_message_short" msgid="3295959985795716166">"कोई नया उपयोगकर्ता जोड़ने पर, उसे अपनी जगह सेट करनी होती है.\n\nकोई भी उपयोगकर्ता बाकी सभी उपयोगकर्ताओं के लिए ऐप्लिकेशन अपडेट कर सकता है."</string>
<string name="user_setup_dialog_title" msgid="8037342066381939995">"उपयोगकर्ता को अभी सेट करें?"</string>
<string name="user_setup_dialog_message" msgid="269931619868102841">"पक्का करें कि व्यक्ति डिवाइस का इस्तेमाल करने और अपनी जगह सेट करने के लिए मौजूद है"</string>
@@ -607,7 +607,7 @@
<string name="guest_exit_dialog_message_non_ephemeral" msgid="223385323235719442">"मौजूदा सेशन की गतिविधि को सेव किया जा सकता है या सभी ऐप और डेटा को मिटाया जा सकता है"</string>
<string name="guest_exit_clear_data_button" msgid="3425812652180679014">"मिटाएं"</string>
<string name="guest_exit_save_data_button" msgid="3690974510644963547">"सेव करें"</string>
- <string name="guest_exit_button" msgid="5774985819191803960">"मेहमान मोड से बाहर निकलें?"</string>
+ <string name="guest_exit_button" msgid="5774985819191803960">"मेहमान मोड से बाहर निकलें"</string>
<string name="guest_reset_button" msgid="2515069346223503479">"मेहमान मोड के सेशन को रीसेट करें?"</string>
<string name="guest_exit_quick_settings_button" msgid="1912362095913765471">"मेहमान मोड से बाहर निकलें"</string>
<string name="guest_notification_ephemeral" msgid="7263252466950923871">"बाहर निकलने पर, सारी गतिविधि मिट जाएगी"</string>
@@ -667,9 +667,6 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"स्क्रीन चालू करें"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"स्क्रीन चालू करने की अनुमति दें"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"ऐप्लिकेशन को स्क्रीन चालू करने की अनुमति दें. ऐसा करने पर, ऐप्लिकेशन आपकी अनुमति लिए बिना भी, जब चाहे स्क्रीन चालू कर सकता है."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"क्यूआर कोड को स्कैन करें"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"सुनने के लिए, दिए गए क्यूआर कोड को बीच में लाएं"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"क्यूआर कोड का फ़ॉर्मैट गलत है"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"<xliff:g id="APP_NAME">%1$s</xliff:g> पर ब्रॉडकास्ट करना रोकें?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"<xliff:g id="SWITCHAPP">%1$s</xliff:g> पर ब्रॉडकास्ट शुरू करने पर या आउटपुट बदलने पर, आपका मौजूदा ब्रॉडकास्ट बंद हो जाएगा"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"<xliff:g id="SWITCHAPP">%1$s</xliff:g> पर ब्रॉडकास्ट करें"</string>
diff --git a/packages/SettingsLib/res/values-hr/strings.xml b/packages/SettingsLib/res/values-hr/strings.xml
index fcf832864602..ad6f75d3b010 100644
--- a/packages/SettingsLib/res/values-hr/strings.xml
+++ b/packages/SettingsLib/res/values-hr/strings.xml
@@ -667,9 +667,6 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Uključivanje zaslona"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Dopusti uključivanje zaslona"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Dopustite aplikaciji da uključuje zaslon. Ako date to dopuštenje, aplikacija može uključiti zaslon u bilo kojem trenutku bez vaše izričite namjere."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"Skeniraj QR kôd"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Da biste počeli slušati, centrirajte QR kôd u nastavku"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"QR kôd nije u važećem formatu"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"Zaustaviti emitiranje aplikacije <xliff:g id="APP_NAME">%1$s</xliff:g>?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"Ako emitirate aplikaciju <xliff:g id="SWITCHAPP">%1$s</xliff:g> ili promijenite izlaz, vaše će se trenutačno emitiranje zaustaviti"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"Emitiranje aplikacije <xliff:g id="SWITCHAPP">%1$s</xliff:g>"</string>
diff --git a/packages/SettingsLib/res/values-hu/strings.xml b/packages/SettingsLib/res/values-hu/strings.xml
index 63d075335ab7..1b906f8ebe14 100644
--- a/packages/SettingsLib/res/values-hu/strings.xml
+++ b/packages/SettingsLib/res/values-hu/strings.xml
@@ -667,17 +667,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Képernyő bekapcsolása"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"A képernyő bekapcsolásának engedélyezése"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"A képernyő bekapcsolásának engedélyezése az adott alkalmazás számára. Ha megadja az engedélyt, az alkalmazás az Ön kifejezett szándéka nélkül, bármikor bekapcsolhatja a képernyőt."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"QR-kód beolvasása"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"A hallgatás megkezdéséhez igazítsa a QR-kódot az alábbi panel közepére"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"A QR-kód formátuma nem érvényes"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"Leállítja a(z) <xliff:g id="APP_NAME">%1$s</xliff:g> közvetítését?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"A(z) <xliff:g id="SWITCHAPP">%1$s</xliff:g> közvetítése vagy a kimenet módosítása esetén a jelenlegi közvetítés leáll"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"<xliff:g id="SWITCHAPP">%1$s</xliff:g> közvetítése"</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"Kimenet módosítása"</string>
- <!-- no translation found for back_navigation_animation (8105467568421689484) -->
- <skip />
- <!-- no translation found for back_navigation_animation_summary (741292224121599456) -->
- <skip />
- <!-- no translation found for back_navigation_animation_dialog (8696966520944625596) -->
- <skip />
+ <string name="back_navigation_animation" msgid="8105467568421689484">"Prediktív „vissza” kézmozdulat-animációk"</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"Rendszeranimációk engedélyezése prediktív „vissza” kézmozdulatok esetén."</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"A beállítás engedélyezi a rendszeranimációkat a prediktív kézmozdulat-animációk esetén. A használatukhoz az enableOnBackInvokedCallback beállítást true értékre kell állítani az egyes alkalmazások manifestfájljaiban."</string>
</resources>
diff --git a/packages/SettingsLib/res/values-hy/strings.xml b/packages/SettingsLib/res/values-hy/strings.xml
index a364cf182e05..2b6ea25e8d34 100644
--- a/packages/SettingsLib/res/values-hy/strings.xml
+++ b/packages/SettingsLib/res/values-hy/strings.xml
@@ -570,7 +570,7 @@
<string name="user_add_profile_item_title" msgid="3111051717414643029">"Սահմանափակված պրոֆիլ"</string>
<string name="user_add_user_title" msgid="5457079143694924885">"Ավելացնե՞լ նոր օգտատեր"</string>
<string name="user_add_user_message_long" msgid="1527434966294733380">"Այս սարքից կարող եք օգտվել մի քանի հոգով: Դրա համար անհրաժեշտ է ստեղծել լրացուցիչ պրոֆիլներ: Յուրաքանչյուր օգտատեր կարող է կարգավորել իր պրոֆիլը ըստ իր հայեցողության և ճաշակի (օր.՝ ընտրել իր ուզած պաստառը, տեղադրել անհրաժեշտ հավելվածները և այլն): Բացի այդ, օգտատերերը կարող են կարգավորել սարքի որոշ պարամետրեր (օր.՝ Wi-Fi-ը), որոնք կգործեն նաև մյուս պրոֆիլների համար:\n\nԵրբ նոր պրոֆիլ ավելացնեք, տվյալ օգտատերը պետք է կարգավորի այն:\n\nՅուրաքանչյուր օգտատեր կարող է թարմացնել մյուս օգտատերերի հավելվածները: Հատուկ գործառույթների և ծառայությունների կարգավորումները կարող են չփոխանցվել նոր օգտատերերին:"</string>
- <string name="user_add_user_message_short" msgid="3295959985795716166">"Երբ նոր օգտատեր եք ավելացնում, նա պետք է կարգավորի իր պրոֆիլը:\n\nՑանկացած օգտատեր կարող է թարմացնել հավելվածները մյուս բոլոր հաշիվների համար:"</string>
+ <string name="user_add_user_message_short" msgid="3295959985795716166">"Երբ նոր օգտատեր եք ավելացնում, նա պետք է կարգավորի իր պրոֆիլը:\n\nՑանկացած օգտատեր կարող է թարմացնել հավելվածները բոլոր օգտատերերի համար:"</string>
<string name="user_setup_dialog_title" msgid="8037342066381939995">"Կարգավորե՞լ պրոֆիլը"</string>
<string name="user_setup_dialog_message" msgid="269931619868102841">"Համոզվեք, որ անձը կարող է վերցնել սարքը և կարգավորել իր տարածքը"</string>
<string name="user_setup_profile_dialog_message" msgid="4788197052296962620">"Կարգավորե՞լ պրոֆիլը հիմա:"</string>
@@ -592,7 +592,7 @@
<string name="user_add_user" msgid="7876449291500212468">"Ավելացնել օգտատեր"</string>
<string name="guest_new_guest" msgid="3482026122932643557">"Ավելացնել հյուր"</string>
<string name="guest_exit_guest" msgid="5908239569510734136">"Հեռացնել հյուրին"</string>
- <string name="guest_reset_guest" msgid="6110013010356013758">"Վերակայել հյուրի աշխատաշրջանը"</string>
+ <string name="guest_reset_guest" msgid="6110013010356013758">"Զրոյացնել հյուրի աշխատաշրջանը"</string>
<string name="guest_reset_guest_dialog_title" msgid="8047270010895437534">"Զրոյացնե՞լ հյուրի աշխատաշրջանը"</string>
<string name="guest_remove_guest_dialog_title" msgid="4548511006624088072">"Հեռացնե՞լ հյուրին"</string>
<string name="guest_reset_guest_confirm_button" msgid="2989915693215617237">"Զրոյացնել"</string>
@@ -608,9 +608,9 @@
<string name="guest_exit_clear_data_button" msgid="3425812652180679014">"Ջնջել"</string>
<string name="guest_exit_save_data_button" msgid="3690974510644963547">"Պահել"</string>
<string name="guest_exit_button" msgid="5774985819191803960">"Դուրս գալ հյուրի ռեժիմից"</string>
- <string name="guest_reset_button" msgid="2515069346223503479">"Վերակայել հյուրի աշխատաշրջանը"</string>
+ <string name="guest_reset_button" msgid="2515069346223503479">"Զրոյացնել հյուրի աշխատաշրջանը"</string>
<string name="guest_exit_quick_settings_button" msgid="1912362095913765471">"Դուրս գալ հյուրի ռեժիմից"</string>
- <string name="guest_notification_ephemeral" msgid="7263252466950923871">"Դուրս գալու դեպքում ամբողջ պատմությունը կջնջվի"</string>
+ <string name="guest_notification_ephemeral" msgid="7263252466950923871">"Եթե դուրս գաք, ամբողջ պատմությունը կջնջվի"</string>
<string name="guest_notification_non_ephemeral" msgid="6843799963012259330">"Դուրս գալիս կարող եք պահել կամ ջնջել ձեր պատմությունը"</string>
<string name="guest_notification_non_ephemeral_non_first_login" msgid="8009307983766934876">"Վերակայեք աշխատաշրջանի պատմությունը հիմա կամ պահեք/ջնջեք այն դուրս գալիս"</string>
<string name="user_image_take_photo" msgid="467512954561638530">"Լուսանկարել"</string>
@@ -667,17 +667,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Էկրանի միացում"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Թույլատրել հավելվածին միացնել էկրանը"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Եթե թույլ տաք, հավելվածը ցանկացած ժամանակ կկարողանա միացնել էկրանը՝ առանց ձեր բացահայտ համաձայնության։"</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"QR կոդի սկանավորում"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Լսելու համար տեսախցիկը պահեք QR կոդի վրա"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"QR կոդի ձևաչափն անվավեր է"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"Կանգնեցնել <xliff:g id="APP_NAME">%1$s</xliff:g> հավելվածի հեռարձակումը"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"Եթե հեռարձակեք <xliff:g id="SWITCHAPP">%1$s</xliff:g> հավելվածը կամ փոխեք աուդիո ելքը, ձեր ընթացիկ հեռարձակումը կկանգնեցվի։"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"Հեռարձակել <xliff:g id="SWITCHAPP">%1$s</xliff:g> հավելվածը"</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"Փոխել աուդիո ելքը"</string>
- <!-- no translation found for back_navigation_animation (8105467568421689484) -->
- <skip />
- <!-- no translation found for back_navigation_animation_summary (741292224121599456) -->
- <skip />
- <!-- no translation found for back_navigation_animation_dialog (8696966520944625596) -->
- <skip />
+ <string name="back_navigation_animation" msgid="8105467568421689484">"«Հետ» ժեստի հուշման շարժանկարներ"</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"Միացնել համակարգի անիմացիաները «Հետ» ժեստի հուշման համար"</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"Այս կարգավորման միջոցով կարելի է միացնել համակարգային շարժանկարները ժեստի հուշման համար։ Կարգավորումը պահանջում է մանիֆեստի ֆայլում սահմանել true արժեքը per-app enableOnBackInvokedCallback հատկության համար։"</string>
</resources>
diff --git a/packages/SettingsLib/res/values-in/strings.xml b/packages/SettingsLib/res/values-in/strings.xml
index 01bd7fe29b85..d4e642eea4f6 100644
--- a/packages/SettingsLib/res/values-in/strings.xml
+++ b/packages/SettingsLib/res/values-in/strings.xml
@@ -667,17 +667,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Aktifkan layar"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Izinkan pengaktifan layar"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Mengizinkan aplikasi mengaktifkan layar. Jika diizinkan, aplikasi dapat mengaktifkan layar kapan saja tanpa izin Anda."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"Pindai kode QR"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Untuk mulai mendengarkan, pusatkan kode QR"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"Format kode QR tidak valid"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"Hentikan siaran <xliff:g id="APP_NAME">%1$s</xliff:g>?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"Jika Anda menyiarkan <xliff:g id="SWITCHAPP">%1$s</xliff:g> atau mengubah output, siaran saat ini akan dihentikan"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"Siarkan <xliff:g id="SWITCHAPP">%1$s</xliff:g>"</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"Ubah output"</string>
- <!-- no translation found for back_navigation_animation (8105467568421689484) -->
- <skip />
- <!-- no translation found for back_navigation_animation_summary (741292224121599456) -->
- <skip />
- <!-- no translation found for back_navigation_animation_dialog (8696966520944625596) -->
- <skip />
+ <string name="back_navigation_animation" msgid="8105467568421689484">"Animasi kembali prediktif"</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"Aktifkan animasi sistem untuk kembali prediktif."</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"Setelan ini mengaktifkan animasi sistem untuk animasi gestur prediktif. Setelan ini mewajibkan enableOnBackInvokedCallback per-aplikasi disetel ke benar (true) dalam file manifes."</string>
</resources>
diff --git a/packages/SettingsLib/res/values-is/strings.xml b/packages/SettingsLib/res/values-is/strings.xml
index 5dc4d04dfc01..d9e5a3964e31 100644
--- a/packages/SettingsLib/res/values-is/strings.xml
+++ b/packages/SettingsLib/res/values-is/strings.xml
@@ -667,17 +667,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Kveikja á skjánum"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Leyfa að kveikt sé á skjánum"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Leyfa forriti að kveikja á skjánum. Ef þetta er leyft getur forritið kveikt á skjánum hvenær sem er án þess að þú samþykkir það sérstaklega."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"Skanna QR-kóða"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Byrjaðu að hlusta með því að skanna QR-kóðann hér að neðan"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"QR-kóði er ekki gilt snið"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"Hætta að senda út <xliff:g id="APP_NAME">%1$s</xliff:g>?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"Ef þú sendir út <xliff:g id="SWITCHAPP">%1$s</xliff:g> eða skiptir um úttak lýkur yfirstandandi útsendingu"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"Senda út <xliff:g id="SWITCHAPP">%1$s</xliff:g>"</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"Skipta um úttak"</string>
- <!-- no translation found for back_navigation_animation (8105467568421689484) -->
- <skip />
- <!-- no translation found for back_navigation_animation_summary (741292224121599456) -->
- <skip />
- <!-- no translation found for back_navigation_animation_dialog (8696966520944625596) -->
- <skip />
+ <string name="back_navigation_animation" msgid="8105467568421689484">"Hreyfimyndir flýtiritunar við bendinguna „til baka“"</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"Kveikja á hreyfimyndum í kerfinu til að sýna hreyfimyndir þegar bendingin „til baka“ er gerð."</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"Þessi stilling kveikir á hreyfimyndum í kerfinu til að sýna hreyfimyndir flýtiritunar með bendingum. Stillingin krefst þess að kveikt sé á enableOnBackInvokedCallback í upplýsingaskránni fyrir hvert forrit."</string>
</resources>
diff --git a/packages/SettingsLib/res/values-it/strings.xml b/packages/SettingsLib/res/values-it/strings.xml
index 57c75d9788ea..fa84ed5cfe47 100644
--- a/packages/SettingsLib/res/values-it/strings.xml
+++ b/packages/SettingsLib/res/values-it/strings.xml
@@ -667,17 +667,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Attiva lo schermo"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Consenti l\'attivazione dello schermo"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Consenti a un\'app di attivare lo schermo. Se la autorizzi, l\'app può attivare lo schermo in qualsiasi momento senza la tua autorizzazione esplicita."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"Scansiona codice QR"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Per iniziare ad ascoltare, centra il codice QR qui sotto"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"Il formato del codice QR non è valido"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"Vuoi interrompere la trasmissione dell\'app <xliff:g id="APP_NAME">%1$s</xliff:g>?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"Se trasmetti l\'app <xliff:g id="SWITCHAPP">%1$s</xliff:g> o cambi l\'uscita, la trasmissione attuale viene interrotta"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"Trasmetti l\'app <xliff:g id="SWITCHAPP">%1$s</xliff:g>"</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"Cambia uscita"</string>
- <!-- no translation found for back_navigation_animation (8105467568421689484) -->
- <skip />
- <!-- no translation found for back_navigation_animation_summary (741292224121599456) -->
- <skip />
- <!-- no translation found for back_navigation_animation_dialog (8696966520944625596) -->
- <skip />
+ <string name="back_navigation_animation" msgid="8105467568421689484">"Animazioni predittive con Indietro"</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"Attiva le animazioni di sistema per il gesto Indietro predittivo."</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"Questa impostazione attiva le animazioni di sistema per il gesto Indietro predittivo. Richiede di impostare il metodo enableOnBackInvokedCallback su true nel file manifest di tutte le app."</string>
</resources>
diff --git a/packages/SettingsLib/res/values-iw/strings.xml b/packages/SettingsLib/res/values-iw/strings.xml
index 72ba41b0df72..90be29d57647 100644
--- a/packages/SettingsLib/res/values-iw/strings.xml
+++ b/packages/SettingsLib/res/values-iw/strings.xml
@@ -667,17 +667,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"הפעלת המסך"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"הרשאה להפעלת המסך"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"הרשאה לאפליקציה להפעיל את המסך. אם מעניקים את ההרשאה, האפליקציה יכולה להפעיל את המסך בכל זמן, גם בלי שמתכוונים לכך במפורש."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"‏סריקת קוד QR"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"‏כדי להתחיל בהאזנה, צריך להציב את קוד ה‑QR במרכז החלון שבהמשך"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"‏הפורמט של קוד ה‑QR לא תקין"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"האם להפסיק לשדר את התוכן מאפליקציית <xliff:g id="APP_NAME">%1$s</xliff:g>?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"אם משדרים את התוכן מאפליקציית <xliff:g id="SWITCHAPP">%1$s</xliff:g> או משנים את הפלט, השידור הנוכחי יפסיק לפעול"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"שידור תוכן מאפליקציית <xliff:g id="SWITCHAPP">%1$s</xliff:g>"</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"שינוי הפלט"</string>
- <!-- no translation found for back_navigation_animation (8105467568421689484) -->
- <skip />
- <!-- no translation found for back_navigation_animation_summary (741292224121599456) -->
- <skip />
- <!-- no translation found for back_navigation_animation_dialog (8696966520944625596) -->
- <skip />
+ <string name="back_navigation_animation" msgid="8105467568421689484">"חיזוי אנימציה של תנועת החזרה"</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"הפעלת אנימציות מערכת עבור חיזוי של תנועת החזרה."</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"‏ההגדרה הזו מפעילה אנימציות מערכת עבור חיזוי אנימציה של תנועת החזרה. היא מחייבת הגדרה בכל אפליקציה של ערך true בשדה enableOnBackInvokedCallback בקובץ המניפסט."</string>
</resources>
diff --git a/packages/SettingsLib/res/values-ja/strings.xml b/packages/SettingsLib/res/values-ja/strings.xml
index 6622d2b6c87a..54abcd47e568 100644
--- a/packages/SettingsLib/res/values-ja/strings.xml
+++ b/packages/SettingsLib/res/values-ja/strings.xml
@@ -667,17 +667,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"画面をオンにする"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"画面をオンにすることを許可する"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"画面をオンにすることをアプリに許可します。許可すると、ユーザーからの明示的インテントを必要とせずに、アプリがいつでも画面をオンにできるようになります。"</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"QR コードをスキャン"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"再生を開始するには、下の枠に QR コードを合わせてください"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"QR コードの形式が無効です"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"<xliff:g id="APP_NAME">%1$s</xliff:g> のブロードキャストを停止しますか?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"<xliff:g id="SWITCHAPP">%1$s</xliff:g> をブロードキャストしたり、出力を変更したりすると、現在のブロードキャストが停止します。"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"<xliff:g id="SWITCHAPP">%1$s</xliff:g> をブロードキャスト"</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"出力を変更"</string>
- <!-- no translation found for back_navigation_animation (8105467568421689484) -->
- <skip />
- <!-- no translation found for back_navigation_animation_summary (741292224121599456) -->
- <skip />
- <!-- no translation found for back_navigation_animation_dialog (8696966520944625596) -->
- <skip />
+ <string name="back_navigation_animation" msgid="8105467568421689484">"予測型「戻る」アニメーション"</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"予測型「戻る」のシステム アニメーションを有効にする。"</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"この設定は、予測型操作のシステム アニメーションを有効にします。アプリごとにマニフェスト ファイルで enableOnBackInvokedCallback を true に設定する必要があります。"</string>
</resources>
diff --git a/packages/SettingsLib/res/values-ka/strings.xml b/packages/SettingsLib/res/values-ka/strings.xml
index 736a05935798..27d3a99ec0c9 100644
--- a/packages/SettingsLib/res/values-ka/strings.xml
+++ b/packages/SettingsLib/res/values-ka/strings.xml
@@ -667,9 +667,6 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"ჩართეთ ეკრანი"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"ეკრანის ჩართვის დაშვება"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"დართეთ ნება აპს, ჩართოს ეკრანი. თუ ამ ნებართვას მიანიჭებთ, აპმა შეიძლება ნებისმიერ დროს ჩართოს ეკრანი თქვენი ცალსახა განზრახვის გარეშე."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"QR კოდის სკანირება"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"მოსმენის დასაწყებად ცენტრში მოაქციეთ ქვემოთ მოცემული QR კოდი"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"QR კოდის ფორმატი არასწორია"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"გსურთ <xliff:g id="APP_NAME">%1$s</xliff:g>-ის ტრანსლაციის შეჩერება?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"<xliff:g id="SWITCHAPP">%1$s</xliff:g>-ის ტრანსლაციის შემთხვევაში ან აუდიოს გამოსასვლელის შეცვლისას, მიმდინარე ტრანსლაცია შეჩერდება"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"<xliff:g id="SWITCHAPP">%1$s</xliff:g>-ის ტრანსლაცია"</string>
diff --git a/packages/SettingsLib/res/values-kk/strings.xml b/packages/SettingsLib/res/values-kk/strings.xml
index 93497f4049ef..19e3a49fba5a 100644
--- a/packages/SettingsLib/res/values-kk/strings.xml
+++ b/packages/SettingsLib/res/values-kk/strings.xml
@@ -608,7 +608,7 @@
<string name="guest_exit_clear_data_button" msgid="3425812652180679014">"Жою"</string>
<string name="guest_exit_save_data_button" msgid="3690974510644963547">"Сақтау"</string>
<string name="guest_exit_button" msgid="5774985819191803960">"Қонақ режимінен шығу"</string>
- <string name="guest_reset_button" msgid="2515069346223503479">"Иә"</string>
+ <string name="guest_reset_button" msgid="2515069346223503479">"Қонақ режимін қалпына келтіру"</string>
<string name="guest_exit_quick_settings_button" msgid="1912362095913765471">"Қонақ режимінен шығу"</string>
<string name="guest_notification_ephemeral" msgid="7263252466950923871">"Шыққанда барлық әрекет жойылады."</string>
<string name="guest_notification_non_ephemeral" msgid="6843799963012259330">"Шыққанда барлық әрекетті сақтай немесе жоя аласыз."</string>
@@ -667,17 +667,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Экранды қосу"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Экранды қосуға рұқсат беру"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Қолданбаның экранды қосуына рұқсат береді. Рұқсат берілсе, қолданба кез келген уақытта экранды өздігінен қосуы мүмкін."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"QR кодын сканерлеу"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Тыңдай бастау үшін төмендегі QR кодын ортаға орналастырыңыз."</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"QR кодының форматы жарамсыз."</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"<xliff:g id="APP_NAME">%1$s</xliff:g> қолданбасын таратуды тоқтатасыз ба?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"<xliff:g id="SWITCHAPP">%1$s</xliff:g> қолданбасын таратсаңыз немесе аудио шығысын өзгертсеңіз, қазіргі тарату сеансы тоқтайды."</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"<xliff:g id="SWITCHAPP">%1$s</xliff:g> қолданбасын тарату"</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"Аудио шығысын өзгерту"</string>
- <!-- no translation found for back_navigation_animation (8105467568421689484) -->
- <skip />
- <!-- no translation found for back_navigation_animation_summary (741292224121599456) -->
- <skip />
- <!-- no translation found for back_navigation_animation_dialog (8696966520944625596) -->
- <skip />
+ <string name="back_navigation_animation" msgid="8105467568421689484">"\"Артқа\" қимылына арналған тұспал анимациясы"</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"\"Артқа\" қимылына арналған жүйелік тұспал анимацияларын іске қосу."</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"Бұл параметр қимылға арналған жүйелік тұспал анимацияларын іске қосады. Ол үшін әр қолданбаның манифест файлында enableOnBackInvokedCallback үшін \"True\" мәні қойылуы керек."</string>
</resources>
diff --git a/packages/SettingsLib/res/values-km/strings.xml b/packages/SettingsLib/res/values-km/strings.xml
index 2995c21b76b7..49f9ed38f37e 100644
--- a/packages/SettingsLib/res/values-km/strings.xml
+++ b/packages/SettingsLib/res/values-km/strings.xml
@@ -667,17 +667,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"បើក​អេក្រង់"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"អនុញ្ញាតឱ្យ​បើកអេក្រង់"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"អនុញ្ញាតឱ្យ​កម្មវិធី​បើកអេក្រង់។ ប្រសិនបើ​អនុញ្ញាត កម្មវិធី​អាចបើកអេក្រង់​បានគ្រប់ពេល ទោះបីជា​អ្នកគ្មានបំណង​ធ្វើអន្តរកម្មក៏ដោយ។"</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"ស្កេន​កូដ QR"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"ដើម្បីចាប់ផ្ដើមស្ដាប់ សូមដាក់កូដ QR ខាងក្រោមឱ្យ​នៅចំកណ្ដាល"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"កូដ QR មិនមែនជា​ទម្រង់​ដែលត្រឹមត្រូវ​ទេ"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"បញ្ឈប់ការផ្សាយ <xliff:g id="APP_NAME">%1$s</xliff:g> ឬ?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"ប្រសិនបើអ្នក​ផ្សាយ <xliff:g id="SWITCHAPP">%1$s</xliff:g> ឬប្ដូរឧបករណ៍បញ្ចេញសំឡេង ការផ្សាយបច្ចុប្បន្នរបស់អ្នកនឹង​បញ្ឈប់"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"ការផ្សាយ <xliff:g id="SWITCHAPP">%1$s</xliff:g>"</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"ប្ដូរឧបករណ៍បញ្ចេញសំឡេង"</string>
- <!-- no translation found for back_navigation_animation (8105467568421689484) -->
- <skip />
- <!-- no translation found for back_navigation_animation_summary (741292224121599456) -->
- <skip />
- <!-- no translation found for back_navigation_animation_dialog (8696966520944625596) -->
- <skip />
+ <string name="back_navigation_animation" msgid="8105467568421689484">"ចលនា​ថយក្រោយ​ដែល​ព្យាករ"</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"បើក​ចលនា​ប្រព័ន្ធ​សម្រាប់​ការ​ថយក្រោយ​ព្យាករ។"</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"ការ​កំណត់នេះ​បើក​ចលនា​ប្រព័ន្ធ​សម្រាប់​ចលនាព្យាករ។ ចលនា​នេះ​ទាមទារ​ការ​កំណត់ enableOnBackInvokedCallback នៅ​ក្នុងកម្មវិធី​ទៅពិត​នៅ​ក្នុង​ឯកសារ​មេនីហ្វេសថ៍។"</string>
</resources>
diff --git a/packages/SettingsLib/res/values-kn/strings.xml b/packages/SettingsLib/res/values-kn/strings.xml
index 2be4960b1847..bdc67cebc142 100644
--- a/packages/SettingsLib/res/values-kn/strings.xml
+++ b/packages/SettingsLib/res/values-kn/strings.xml
@@ -667,9 +667,6 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"ಸ್ಕ್ರೀನ್ ಅನ್ನು ಆನ್ ಮಾಡಿ"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"ಸ್ಕ್ರೀನ್ ಅನ್ನು ಆನ್ ಮಾಡಲು ಅನುಮತಿಸಿ"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"ಸ್ಕ್ರೀನ್ ಅನ್ನು ಆನ್ ಮಾಡಲು ಆ್ಯಪ್‌ಗೆ ಅನುಮತಿಸಿ. ಅನುಮತಿಸಿದರೆ, ನಿಮಗೆ ಅಗತ್ಯವಿಲ್ಲದಿದ್ದಾಗಲೂ ಆ್ಯಪ್ ಯಾವುದೇ ಸಮಯದಲ್ಲಿ ಸ್ಕ್ರೀನ್ ಅನ್ನು ಆನ್ ಮಾಡಬಹುದು."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"QR ಕೋಡ್ ಸ್ಕ್ಯಾನ್ ಮಾಡಿ"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"ಆಲಿಸುವುದಕ್ಕೆ ಪ್ರಾರಂಭಿಸಲು, ಕ್ಯಾಮರಾವನ್ನು ಕೆಳಗಿನ QR ಕೋಡ್ ಮೇಲೆ ಕೇಂದ್ರೀಕರಿಸಿ"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"QR ಕೋಡ್ ಮಾನ್ಯ ಫಾರ್ಮ್ಯಾಟ್‌ನಲ್ಲಿಲ್ಲ"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"<xliff:g id="APP_NAME">%1$s</xliff:g> ನ ಪ್ರಸಾರವನ್ನು ನಿಲ್ಲಿಸಬೇಕೆ?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"ನೀವು <xliff:g id="SWITCHAPP">%1$s</xliff:g> ಅನ್ನು ಪ್ರಸಾರ ಮಾಡಿದರೆ ಅಥವಾ ಔಟ್‌ಪುಟ್ ಅನ್ನು ಬದಲಾಯಿಸಿದರೆ, ನಿಮ್ಮ ಪ್ರಸ್ತುತ ಪ್ರಸಾರವು ಸ್ಥಗಿತಗೊಳ್ಳುತ್ತದೆ"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"<xliff:g id="SWITCHAPP">%1$s</xliff:g> ಅನ್ನು ಪ್ರಸಾರ ಮಾಡಿ"</string>
diff --git a/packages/SettingsLib/res/values-ko/strings.xml b/packages/SettingsLib/res/values-ko/strings.xml
index 7f0ee76b48c9..cb8b932807b7 100644
--- a/packages/SettingsLib/res/values-ko/strings.xml
+++ b/packages/SettingsLib/res/values-ko/strings.xml
@@ -667,17 +667,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"화면 켜기"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"화면 켜기 허용"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"앱에서 화면을 켜도록 허용합니다. 권한이 부여된 경우 앱에서 명시적 인텐트 없이 언제든지 화면을 켤 수 있습니다."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"QR 코드 스캔"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"아래의 QR 코드가 스캐너 가운데에 오도록 맞춘 다음 듣기를 시작하세요"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"QR 코드의 형식이 유효하지 않습니다."</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"<xliff:g id="APP_NAME">%1$s</xliff:g> 방송을 중지하시겠습니까?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"<xliff:g id="SWITCHAPP">%1$s</xliff:g> 앱을 방송하거나 출력을 변경하면 기존 방송이 중단됩니다"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"<xliff:g id="SWITCHAPP">%1$s</xliff:g> 방송"</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"출력 변경"</string>
- <!-- no translation found for back_navigation_animation (8105467568421689484) -->
- <skip />
- <!-- no translation found for back_navigation_animation_summary (741292224121599456) -->
- <skip />
- <!-- no translation found for back_navigation_animation_dialog (8696966520944625596) -->
- <skip />
+ <string name="back_navigation_animation" msgid="8105467568421689484">"예측된 뒤로 동작 애니메이션"</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"예측된 뒤로 동작에 시스템 애니메이션을 사용하도록 설정합니다."</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"이 설정은 예측된 동작 애니메이션에 시스템 애니메이션을 사용하도록 합니다. 매니페스트 파일에서 앱별 enableOnBackInvokedCallback을 True로 설정해야 합니다."</string>
</resources>
diff --git a/packages/SettingsLib/res/values-ky/strings.xml b/packages/SettingsLib/res/values-ky/strings.xml
index fbf4b6d086c8..e99d55674aa9 100644
--- a/packages/SettingsLib/res/values-ky/strings.xml
+++ b/packages/SettingsLib/res/values-ky/strings.xml
@@ -667,17 +667,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Экранды күйгүзүү"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Экранды күйгүзүүгө уруксат берүү"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Колдонмого экранды күйгүзүүгө уруксат бериңиз. Уруксат берилсе, колдонмо экранды каалаган убакта сизден уруксат сурабастан күйгүзүшү мүмкүн."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"QR кодун скандоо"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Угуп баштоо үчүн QR кодун борборго жайгаштырыңыз"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"QR кодунун форматы жараксыз"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"<xliff:g id="APP_NAME">%1$s</xliff:g> колдонмосунда кабарлоо токтотулсунбу?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"Эгер <xliff:g id="SWITCHAPP">%1$s</xliff:g> колдонмосунда кабарласаңыз же аудионун чыгуусун өзгөртсөңүз, учурдагы кабарлоо токтотулат"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"<xliff:g id="SWITCHAPP">%1$s</xliff:g> колдонмосунда кабарлоо"</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"Аудионун чыгуусун өзгөртүү"</string>
- <!-- no translation found for back_navigation_animation (8105467568421689484) -->
- <skip />
- <!-- no translation found for back_navigation_animation_summary (741292224121599456) -->
- <skip />
- <!-- no translation found for back_navigation_animation_dialog (8696966520944625596) -->
- <skip />
+ <string name="back_navigation_animation" msgid="8105467568421689484">"Божомолдонгон анимациялар"</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"Божомолдоп билүү үчүн тутумдун анимацияларын иштетиңиз."</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"Бул параметр жаңсоо анимациясын божомолдоп билүү үчүн тутумдун анимацияларын иштетет. Ал үчүн манифест файлындагы enableOnBackInvokedCallback параметри ар бир колдонмо үчүн \"true\" деп коюлушу керек."</string>
</resources>
diff --git a/packages/SettingsLib/res/values-lo/strings.xml b/packages/SettingsLib/res/values-lo/strings.xml
index fd6ba22ef372..15579a733b46 100644
--- a/packages/SettingsLib/res/values-lo/strings.xml
+++ b/packages/SettingsLib/res/values-lo/strings.xml
@@ -225,7 +225,7 @@
<string name="choose_profile" msgid="343803890897657450">"ເລືອກໂປຣໄຟລ໌"</string>
<string name="category_personal" msgid="6236798763159385225">"​ສ່ວນ​ໂຕ"</string>
<string name="category_work" msgid="4014193632325996115">"​ບ່ອນ​ເຮັດ​ວຽກ"</string>
- <string name="development_settings_title" msgid="140296922921597393">"ໂຕເລືອກນັກພັດທະນາ"</string>
+ <string name="development_settings_title" msgid="140296922921597393">"ຕົວເລືອກນັກພັດທະນາ"</string>
<string name="development_settings_enable" msgid="4285094651288242183">"ເປີດໃຊ້ຕົວເລືອກນັກພັດທະນາ"</string>
<string name="development_settings_summary" msgid="8718917813868735095">"ຕັ້ງຄ່າໂຕເລືອກສຳລັບການພັດທະນາແອັບຯ"</string>
<string name="development_settings_not_available" msgid="355070198089140951">"ໂຕເລືອກສຳລັບນັກພັດທະນາບໍ່ສາມາດໃຊ້ໄດ້ກັບຜູ່ໃຊ້ນີ້"</string>
@@ -601,7 +601,7 @@
<string name="guest_reset_and_restart_dialog_title" msgid="3396657008451616041">"ຣີເຊັດເຊດຊັນຂອງແຂກບໍ?"</string>
<string name="guest_reset_and_restart_dialog_message" msgid="2764425635305200790">"ນີ້ຈະເລີ່ມໄລຍະເວລາຂອງແຂກໃໝ່ ແລະ ລຶບແອັບ ແລະ ຂໍ້ມູນທັງໝົດອອກຈາກເຊດຊັນປັດຈຸບັນ"</string>
<string name="guest_exit_dialog_title" msgid="1846494656849381804">"ອອກຈາກໂໝດແຂກບໍ?"</string>
- <string name="guest_exit_dialog_message" msgid="1743218864242719783">"ນີ້ຈະລຶບແອັບ ແລະ ຂໍ້ມູນອອກຈາກໄລຍະເວລາຂອງແຂກປັດຈຸບັນ"</string>
+ <string name="guest_exit_dialog_message" msgid="1743218864242719783">"ນີ້ຈະລຶບແອັບ ແລະ ຂໍ້ມູນອອກຈາກເຊດຊັນແຂກປັດຈຸບັນ"</string>
<string name="guest_exit_dialog_button" msgid="1736401897067442044">"ອອກ"</string>
<string name="guest_exit_dialog_title_non_ephemeral" msgid="7675327443743162986">"ບັນທຶກການເຄື່ອນໄຫວແຂກບໍ?"</string>
<string name="guest_exit_dialog_message_non_ephemeral" msgid="223385323235719442">"ທ່ານສາມາດບັນທຶກການເຄື່ອນໄຫວຈາກເຊດຊັນປັດຈຸບັນ ຫຼື ລຶບແອັບ ແລະ ຂໍ້ມູນທັງໝົດໄດ້"</string>
@@ -667,9 +667,6 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"ເປີດໜ້າຈໍ"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"ອະນຸຍາດໃຫ້ເປີດໜ້າຈໍ"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"ອະນຸຍາດໃຫ້ແອັບເປີດໜ້າຈໍໄດ້. ຫາກອະນຸມັດ, ແອັບຈະສາມາດເປີດໜ້າຈໍຕອນໃດກໍໄດ້ໂດຍທີ່ທ່ານບໍ່ຕ້ອງມີເຈດຕະນາຢ່າງຈະແຈ້ງ."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"ສະແກນລະຫັດ QR"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"ເພື່ອເລີ່ມການຟັງ, ໃຫ້ວາງລະຫັດ QR ທາງລຸ່ມນີ້ໄວ້ທາງກາງ"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"ຮູບແບບລະຫັດ QR ບໍ່ຖືກຕ້ອງ"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"ຢຸດການອອກອາກາດ <xliff:g id="APP_NAME">%1$s</xliff:g> ບໍ?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"ຫາກທ່ານອອກອາກາດ <xliff:g id="SWITCHAPP">%1$s</xliff:g> ຫຼື ປ່ຽນເອົ້າພຸດ, ການອອກອາກາດປັດຈຸບັນຂອງທ່ານຈະຢຸດ"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"ອອກອາກາດ <xliff:g id="SWITCHAPP">%1$s</xliff:g>"</string>
diff --git a/packages/SettingsLib/res/values-lt/strings.xml b/packages/SettingsLib/res/values-lt/strings.xml
index f8475e1dfc07..8a85a2135c66 100644
--- a/packages/SettingsLib/res/values-lt/strings.xml
+++ b/packages/SettingsLib/res/values-lt/strings.xml
@@ -667,17 +667,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Ekrano įjungimas"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Leisti įjungti ekraną"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Leiskite programai įjungti ekraną. Jei suteiksite leidimą, programa galės įjungti ekraną bet kuriuo metu be nurodyto tikslo."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"QR kodo nuskaitymas"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Jei norite pradėti klausyti, nustatykite toliau pateiktą QR kodą per vidurį"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"QR kodas netinkamo formato"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"Sustabdyti „<xliff:g id="APP_NAME">%1$s</xliff:g>“ transliaciją?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"Jei transliuosite „<xliff:g id="SWITCHAPP">%1$s</xliff:g>“ arba pakeisite išvestį, dabartinė transliacija bus sustabdyta"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"Transliuoti „<xliff:g id="SWITCHAPP">%1$s</xliff:g>“"</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"Keisti išvestį"</string>
- <!-- no translation found for back_navigation_animation (8105467568421689484) -->
- <skip />
- <!-- no translation found for back_navigation_animation_summary (741292224121599456) -->
- <skip />
- <!-- no translation found for back_navigation_animation_dialog (8696966520944625596) -->
- <skip />
+ <string name="back_navigation_animation" msgid="8105467568421689484">"Numatomos grįžimo atgal gestų animacijos"</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"Įgalinkite sistemos animacijas, kad būtų galima naudoti numatomus grįžimo atgal gestus."</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"Šis nustatymas įgalina numatomų grįžimo atgal gestų sistemos animacijas. Aprašo faile programos lauką „enableOnBackInvokedCallback“ reikia nustatyti į vertę „true“."</string>
</resources>
diff --git a/packages/SettingsLib/res/values-lv/strings.xml b/packages/SettingsLib/res/values-lv/strings.xml
index e024d30ded99..1b7ccf995488 100644
--- a/packages/SettingsLib/res/values-lv/strings.xml
+++ b/packages/SettingsLib/res/values-lv/strings.xml
@@ -667,17 +667,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Ekrāna ieslēgšana"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Atļaut ieslēgt ekrānu"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Atļaujiet lietotnei ieslēgt ekrānu. Ja to atļausiet, lietotne varēs jebkurā laikā ieslēgt ekrānu bez tiešas jūsu piekrišanas."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"Kvadrātkoda skenēšana"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Lai sāktu klausīties, centrējiet tālāk norādīto kvadrātkodu."</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"Kvadrātkoda formāts nav derīgs."</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"Vai apturēt lietotnes <xliff:g id="APP_NAME">%1$s</xliff:g> apraidīšanu?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"Ja sāksiet lietotnes <xliff:g id="SWITCHAPP">%1$s</xliff:g> apraidīšanu vai mainīsiet izvadi, pašreizējā apraide tiks apturēta"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"Lietotnes <xliff:g id="SWITCHAPP">%1$s</xliff:g> apraide"</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"Izvades maiņa"</string>
- <!-- no translation found for back_navigation_animation (8105467568421689484) -->
- <skip />
- <!-- no translation found for back_navigation_animation_summary (741292224121599456) -->
- <skip />
- <!-- no translation found for back_navigation_animation_dialog (8696966520944625596) -->
- <skip />
+ <string name="back_navigation_animation" msgid="8105467568421689484">"Animāciju prognozēšana pāriešanai atpakaļ"</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"Iespējot sistēmas animācijas prognozētam žestam pāriešanai atpakaļ."</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"Šis iestatījums iespējo sistēmas animācijas prognozēto žestu animācijām. Lai to varētu izmantot, parametram “enableOnBackInvokedCallback” lietotnes manifesta failā jāiestata vērtība “true”."</string>
</resources>
diff --git a/packages/SettingsLib/res/values-mk/strings.xml b/packages/SettingsLib/res/values-mk/strings.xml
index d91792a56de8..6e2b7ca20e52 100644
--- a/packages/SettingsLib/res/values-mk/strings.xml
+++ b/packages/SettingsLib/res/values-mk/strings.xml
@@ -667,9 +667,6 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Вклучување на екранот"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Дозволи вклучување на екранот"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Дозволете апликација да го вклучи екранот. Ако дозволите, апликацијата може да го вклучи екранот во секое време без ваша намера."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"Скенирајте QR-код"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"За да започне слушањето, центрирајте го QR-кодот долу"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"QR-кодот не е во важечки формат"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"Да се прекине емитувањето на <xliff:g id="APP_NAME">%1$s</xliff:g>?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"Ако емитувате на <xliff:g id="SWITCHAPP">%1$s</xliff:g> или го промените излезот, тековното емитување ќе запре"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"Емитување на <xliff:g id="SWITCHAPP">%1$s</xliff:g>"</string>
diff --git a/packages/SettingsLib/res/values-ml/strings.xml b/packages/SettingsLib/res/values-ml/strings.xml
index f07b0669fd91..828fe45f62c4 100644
--- a/packages/SettingsLib/res/values-ml/strings.xml
+++ b/packages/SettingsLib/res/values-ml/strings.xml
@@ -570,7 +570,7 @@
<string name="user_add_profile_item_title" msgid="3111051717414643029">"നിയന്ത്രിത പ്രൊഫൈൽ"</string>
<string name="user_add_user_title" msgid="5457079143694924885">"പുതിയ ഉപയോക്താവിനെ ചേർക്കണോ?"</string>
<string name="user_add_user_message_long" msgid="1527434966294733380">"കൂടുതൽ ഉപയോക്താക്കളെ സൃഷ്‌ടിച്ചുകൊണ്ട് ഈ ഉപകരണം മറ്റുള്ളവരുമായി നിങ്ങൾക്ക് പങ്കിടാം. ആപ്പുകളും വാൾപേപ്പറുകളും മറ്റും ഉപയോഗിച്ച് ഇഷ്‌ടാനുസൃതമാക്കാൻ ഓരോ ഉപയോക്താവിനും സാധിക്കും. വൈഫൈ പോലെ എല്ലാവരെയും ബാധിക്കുന്ന ഉപകരണ ക്രമീകരണവും ഉപയോക്താക്കൾക്ക് അഡ്ജസ്റ്റ് ചെയ്യാം.\n\nനിങ്ങളൊരു പുതിയ ഉപയോക്താവിനെ ചേർക്കുമ്പോൾ, ആ വ്യക്തി സ്വന്തമായ ഇടം സജ്ജീകരിക്കേണ്ടതുണ്ട്.\n\n ഏതെങ്കിലും ഉപയോക്താവിന് എല്ലാ ഉപയോക്താക്കൾക്കുമായി ആപ്പുകൾ അപ്‌ഡേറ്റ് ചെയ്യാനാകും. ഉപയോഗസഹായി ക്രമീകരണവും സേവനങ്ങളും പുതിയ ഉപയോക്താവിന് കൈമാറുകയില്ല."</string>
- <string name="user_add_user_message_short" msgid="3295959985795716166">"നിങ്ങൾ ഒരു പുതിയ ഉപയോക്താവിനെ ചേർക്കുമ്പോൾ, ആ വ്യക്തിയ്‌ക്ക് അവരുടെ ഇടം സജ്ജീകരിക്കേണ്ടതുണ്ട്.\n\nമറ്റ് എല്ലാ ഉപയോക്താക്കൾക്കുമായി ഏതൊരു ഉപയോക്താവിനും ആപ്പുകൾ അപ്‌ഡേറ്റ് ചെയ്യാനാവും."</string>
+ <string name="user_add_user_message_short" msgid="3295959985795716166">"നിങ്ങൾ ഒരു പുതിയ ഉപയോക്താവിനെ ചേർക്കുമ്പോൾ, ആ വ്യക്തി സ്വന്തമായ ഇടം സജ്ജീകരിക്കേണ്ടതുണ്ട്.\n\nമറ്റെല്ലാ ഉപയോക്താക്കൾക്കുമായി ഏതെങ്കിലും ഉപയോക്താവിന് ആപ്പുകൾ അപ്‌ഡേറ്റ് ചെയ്യാം."</string>
<string name="user_setup_dialog_title" msgid="8037342066381939995">"ഉപയോക്താവിനെ ഇപ്പോൾ സജ്ജീകരിക്കണോ?"</string>
<string name="user_setup_dialog_message" msgid="269931619868102841">"ഉപകരണം എടുത്ത് ഇടം സജ്ജീകരിക്കുന്നതിന് വ്യക്തി ലഭ്യമാണെന്ന് ഉറപ്പാക്കുക"</string>
<string name="user_setup_profile_dialog_message" msgid="4788197052296962620">"ഇപ്പോൾ പ്രൊഫൈൽ സജ്ജീകരിക്കണോ?"</string>
@@ -667,17 +667,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"സ്ക്രീൻ ഓണാക്കുക"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"സ്ക്രീൻ ഓണാക്കാൻ അനുവദിക്കുക"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"സ്ക്രീൻ ഓണാക്കാൻ ആപ്പിനെ അനുവദിക്കുക. അനുവദിക്കുകയാണെങ്കിൽ, നിങ്ങളുടെ താൽപ്പര്യം കൂടാതെ ഏതുസമയത്തും സ്ക്രീൻ ഓണാക്കാൻ ആപ്പിന് കഴിയും."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"QR കോഡ് സ്‌കാൻ ചെയ്യുക"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"കേട്ട് തുടങ്ങാൻ ചുവടെയുള്ള QR കോഡിലേക്ക് കേന്ദ്രീകരിക്കുക"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"QR കോഡ് ഫോർമാറ്റ് അസാധുവാണ്"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"<xliff:g id="APP_NAME">%1$s</xliff:g> ബ്രോഡ്‌കാസ്റ്റ് ചെയ്യുന്നത് അവസാനിപ്പിക്കണോ?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"നിങ്ങൾ <xliff:g id="SWITCHAPP">%1$s</xliff:g> ബ്രോഡ്‌കാസ്റ്റ് ചെയ്യുകയോ ഔട്ട്പുട്ട് മാറ്റുകയോ ചെയ്താൽ നിങ്ങളുടെ നിലവിലുള്ള ബ്രോഡ്‌കാസ്റ്റ് അവസാനിക്കും"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"<xliff:g id="SWITCHAPP">%1$s</xliff:g> ബ്രോഡ്‌കാസ്റ്റ് ചെയ്യുക"</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"ഔട്ട്പുട്ട് മാറ്റുക"</string>
- <!-- no translation found for back_navigation_animation (8105467568421689484) -->
- <skip />
- <!-- no translation found for back_navigation_animation_summary (741292224121599456) -->
- <skip />
- <!-- no translation found for back_navigation_animation_dialog (8696966520944625596) -->
- <skip />
+ <string name="back_navigation_animation" msgid="8105467568421689484">"പ്രെഡിക്റ്റീവ് ബാക്ക് ആനിമേഷനുകൾ"</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"പ്രെഡിക്റ്റീവ് ബാക്കിനായി സിസ്റ്റം ആനിമേഷനുകൾ പ്രവർത്തനക്ഷമമാക്കുക."</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"ഈ ക്രമീകരണം പ്രെഡിക്റ്റീവ് ജെസ്ച്ചർ ആനിമേഷന് വേണ്ടി സിസ്റ്റം ആനിമേഷനുകളെ പ്രവർത്തനക്ഷമമാക്കുന്നു. ഇതിന് ഓരോ ആപ്പിലും enableOnBackInvokedCallback എന്നത് മാനിഫെസ്റ്റ് ഫയലിൽ ശരി എന്ന് സജ്ജീകരിക്കേണ്ടതുണ്ട്."</string>
</resources>
diff --git a/packages/SettingsLib/res/values-mn/strings.xml b/packages/SettingsLib/res/values-mn/strings.xml
index 35a29a4556b3..b25a57c2ca67 100644
--- a/packages/SettingsLib/res/values-mn/strings.xml
+++ b/packages/SettingsLib/res/values-mn/strings.xml
@@ -667,9 +667,6 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Дэлгэцийг асаах"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Дэлгэцийг асаахыг зөвшөөрнө үү"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Аппад дэлгэцийг асаахыг зөвшөөрнө үү. Зөвшөөрсөн тохиолдолд тухайн апп таны тодорхой оролцоогүйгээр ямар ч үед дэлгэцийг асааж болно."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"QR код скан хийх"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Сонсож эхлэхийн тулд доорх QR кодыг голлуулаарай"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"QR код буруу форматтай байна"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"<xliff:g id="APP_NAME">%1$s</xliff:g>-г нэвтрүүлэхээ зогсоох уу?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"Хэрэв та <xliff:g id="SWITCHAPP">%1$s</xliff:g>-г нэвтрүүлсэн эсвэл гаралтыг өөрчилсөн бол таны одоогийн нэвтрүүлэлтийг зогсооно"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"<xliff:g id="SWITCHAPP">%1$s</xliff:g>-г нэвтрүүлэх"</string>
diff --git a/packages/SettingsLib/res/values-mr/strings.xml b/packages/SettingsLib/res/values-mr/strings.xml
index 44b90d544543..12bbcee38b48 100644
--- a/packages/SettingsLib/res/values-mr/strings.xml
+++ b/packages/SettingsLib/res/values-mr/strings.xml
@@ -667,9 +667,6 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"स्क्रीन सुरू करा"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"स्क्रीन सुरू करण्यासाठी अनुमती द्या"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"स्क्रीन सुरू करण्यासाठी ॲपला अनुमती द्या. अनुमती दिल्यास, ॲप तुमच्या स्पष्ट हेतूशिवाय कधीही स्क्रीन सुरू करू शकते."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"QR कोड स्कॅन करा"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"ऐकणे सुरू करण्यासाठी, खालील QR कोड मध्यभागी ठेवा"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"QR कोडचा फॉरमॅट चुकीचा आहे"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"<xliff:g id="APP_NAME">%1$s</xliff:g> चे प्रसारण थांबवायचे आहे का?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"तुम्ही <xliff:g id="SWITCHAPP">%1$s</xliff:g> चे प्रसारण केल्यास किंवा आउटपुट बदलल्यास, तुमचे सध्याचे प्रसारण बंद होईल"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"<xliff:g id="SWITCHAPP">%1$s</xliff:g> चे प्रसारण करा"</string>
diff --git a/packages/SettingsLib/res/values-ms/strings.xml b/packages/SettingsLib/res/values-ms/strings.xml
index 126c5ef5fa35..2b6f62d16cfe 100644
--- a/packages/SettingsLib/res/values-ms/strings.xml
+++ b/packages/SettingsLib/res/values-ms/strings.xml
@@ -448,7 +448,7 @@
<string name="daltonizer_mode_protanomaly" msgid="7805583306666608440">"Protanomali (merah-hijau)"</string>
<string name="daltonizer_mode_tritanomaly" msgid="7135266249220732267">"Tritanomali (biru-kuning)"</string>
<string name="accessibility_display_daltonizer_preference_title" msgid="1810693571332381974">"Pembetulan warna"</string>
- <string name="accessibility_display_daltonizer_preference_subtitle" msgid="1522101114585266455">"Pembetulan warna dapat membantu apabila anda mahu:&lt;br/&gt; &lt;ol&gt; &lt;li&gt;&amp;nbsp;Melihat warna dengan lebih tepat&lt;/li&gt; &lt;li&gt;&amp;nbsp;Mengalih keluar warna untuk membantu anda menumpukan perhatian&lt;/li&gt; &lt;/ol&gt;"</string>
+ <string name="accessibility_display_daltonizer_preference_subtitle" msgid="1522101114585266455">"Pembetulan warna dapat membantu apabila anda mahu:&lt;br/&gt; &lt;ol&gt; &lt;li&gt;&amp;nbsp;Melihat warna dengan lebih tepat&lt;/li&gt; &lt;li&gt;&amp;nbsp;Mengalih keluar warna agar anda dapat menumpukan perhatian&lt;/li&gt; &lt;/ol&gt;"</string>
<string name="daltonizer_type_overridden" msgid="4509604753672535721">"Diatasi oleh <xliff:g id="TITLE">%1$s</xliff:g>"</string>
<string name="power_remaining_settings_home_page" msgid="4885165789445462557">"<xliff:g id="PERCENTAGE">%1$s</xliff:g> - <xliff:g id="TIME_STRING">%2$s</xliff:g>"</string>
<string name="power_remaining_duration_only" msgid="8264199158671531431">"Kira-kira <xliff:g id="TIME_REMAINING">%1$s</xliff:g> lagi"</string>
@@ -474,8 +474,8 @@
<string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7703677921000858479">"Tablet mungkin ditutup tidak lama lagi (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
<string name="power_remaining_duration_shutdown_imminent" product="device" msgid="4374784375644214578">"Peranti mungkin ditutup tidak lama lagi (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
<string name="power_charging" msgid="6727132649743436802">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
- <string name="power_remaining_charging_duration_only" msgid="8085099012811384899">"<xliff:g id="TIME">%1$s</xliff:g> lagi hingga penuh"</string>
- <string name="power_charging_duration" msgid="6127154952524919719">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> lagi hingga penuh"</string>
+ <string name="power_remaining_charging_duration_only" msgid="8085099012811384899">"<xliff:g id="TIME">%1$s</xliff:g> lagi sebelum penuh"</string>
+ <string name="power_charging_duration" msgid="6127154952524919719">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> lagi sebelum penuh"</string>
<string name="power_charging_limited" msgid="7956120998372505295">"<xliff:g id="LEVEL">%1$s</xliff:g> - Pengecasan terhad sementara"</string>
<string name="battery_info_status_unknown" msgid="268625384868401114">"Tidak diketahui"</string>
<string name="battery_info_status_charging" msgid="4279958015430387405">"Mengecas"</string>
@@ -667,9 +667,6 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Hidupkan skrin"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Benarkan menghidupkan skrin"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Benarkan apl menghidupkan skrin. Jika dibenarkan, apl boleh menghidupkan skrin pada bila-bila masa tanpa niat eksplisit anda."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"Imbas kod QR"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Untuk mula mendengar, pusatkan kod QR di bawah"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"Kod QR bukan dalam format yang sah"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"Hentikan siaran <xliff:g id="APP_NAME">%1$s</xliff:g>?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"Jika anda siarkan <xliff:g id="SWITCHAPP">%1$s</xliff:g> atau tukarkan output, siaran semasa anda akan berhenti"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"Siarkan <xliff:g id="SWITCHAPP">%1$s</xliff:g>"</string>
diff --git a/packages/SettingsLib/res/values-my/strings.xml b/packages/SettingsLib/res/values-my/strings.xml
index b0f9f340e928..5aab523529e4 100644
--- a/packages/SettingsLib/res/values-my/strings.xml
+++ b/packages/SettingsLib/res/values-my/strings.xml
@@ -668,17 +668,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"ဖန်သားပြင် ဖွင့်ခြင်း"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"ဖန်သားပြင် ဖွင့်ခွင့်ပြုရန်"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"အက်ပ်ကို ဖန်သားပြင် ဖွင့်ခွင့်ပြုနိုင်သည်။ ခွင့်ပြုထားပါက အက်ပ်သည် သင့်ထံမှ တိကျသောရည်ရွယ်ချက်မလိုဘဲ ဖန်သားပြင်ကို အချိန်မရွေး ဖွင့်နိုင်မည်။"</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"QR ကုဒ်ကို စကင်ဖတ်ရန်"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"စတင်နားဆင်ရန် အောက်ရှိ QR ကုဒ်ကို အလယ်တွင်ထားပါ"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"QR ကုဒ်သည် မှန်ကန်သောဖော်မက် မဟုတ်ပါ"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"<xliff:g id="APP_NAME">%1$s</xliff:g> ထုတ်လွှင့်ခြင်းကို ရပ်မလား။"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"<xliff:g id="SWITCHAPP">%1$s</xliff:g> ကို ထုတ်လွှင့်သောအခါ (သို့) အထွက်ကို ပြောင်းသောအခါ သင့်လက်ရှိထုတ်လွှင့်ခြင်း ရပ်သွားမည်"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"<xliff:g id="SWITCHAPP">%1$s</xliff:g> ထုတ်လွှင့်ခြင်း"</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"အထွက်ကို ပြောင်းခြင်း"</string>
- <!-- no translation found for back_navigation_animation (8105467568421689484) -->
- <skip />
- <!-- no translation found for back_navigation_animation_summary (741292224121599456) -->
- <skip />
- <!-- no translation found for back_navigation_animation_dialog (8696966520944625596) -->
- <skip />
+ <string name="back_navigation_animation" msgid="8105467568421689484">"နောက်ခလုတ်၏ ရှေ့ပြေးလှုပ်ရှားသက်ဝင်ပုံ"</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"နောက်ခလုတ်ရှေ့ပြေးအတွက် စနစ်လှုပ်ရှားသက်ဝင်ပုံများကို ဖွင့်ပါသည်။"</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"ဤဆက်တင်သည် လက်ဟန် ရှေ့ပြေးလှုပ်ရှားသက်ဝင်ပုံအတွက် စနစ်လှုပ်ရှားသက်ဝင်ပုံများကို ဖွင့်ပါသည်။ အက်ပ်တစ်ခုစီ၏ ဆက်တင်အတွက် enableOnBackInvokedCallback ကို မန်နီးဖက်စ် (manifest) ဖိုင်၌ ဖွင့်ထားရန်လိုအပ်သည်။"</string>
</resources>
diff --git a/packages/SettingsLib/res/values-nb/strings.xml b/packages/SettingsLib/res/values-nb/strings.xml
index 229730e3b057..8899644963d0 100644
--- a/packages/SettingsLib/res/values-nb/strings.xml
+++ b/packages/SettingsLib/res/values-nb/strings.xml
@@ -667,17 +667,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Slå på skjermen"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Tillat å slå på skjermen"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Tillat at en app slår på skjermen. Hvis tillatelsen gis, kan appen slå på skjermen når som helst uten din eksplisitte intensjon."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"Skann QR-koden"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"For å begynne å lytte, midtstill QR-koden nedenfor"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"QR-koden er ikke i et gyldig format"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"Vil du stoppe kringkastingen av <xliff:g id="APP_NAME">%1$s</xliff:g>?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"Hvis du kringkaster <xliff:g id="SWITCHAPP">%1$s</xliff:g> eller endrer utgangen, stopper den nåværende kringkastingen din"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"Kringkast <xliff:g id="SWITCHAPP">%1$s</xliff:g>"</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"Endre utgang"</string>
- <!-- no translation found for back_navigation_animation (8105467568421689484) -->
- <skip />
- <!-- no translation found for back_navigation_animation_summary (741292224121599456) -->
- <skip />
- <!-- no translation found for back_navigation_animation_dialog (8696966520944625596) -->
- <skip />
+ <string name="back_navigation_animation" msgid="8105467568421689484">"Tilbake-animasjoner med forslag"</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"Slå på systemanimasjoner for tilbakebevegelser med forslag."</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"Denne innstillingen slår på systemanimasjoner for bevegelsesanimasjoner med forslag. Den krever at enableOnBackInvokedCallback settes til sann i manifestfilen for hver app."</string>
</resources>
diff --git a/packages/SettingsLib/res/values-ne/strings.xml b/packages/SettingsLib/res/values-ne/strings.xml
index 3473b816cc3c..d59ceebcc774 100644
--- a/packages/SettingsLib/res/values-ne/strings.xml
+++ b/packages/SettingsLib/res/values-ne/strings.xml
@@ -667,9 +667,6 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"स्क्रिन अन गर्नुहोस्"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"स्क्रिन अन गर्ने अनुमति दिइयोस्"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"कुनै एपलाई स्क्रिन अन गर्ने अनुमति दिइयोस्। यो अनुमति दिइएका खण्डमा तपाईंले अन गर्न नखोजेका बेलामा पनि एपले जुनसुकै बेला स्क्रिन अन गर्न सक्छ।"</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"QR कोड स्क्यान गर्नुहोस्"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"अडियो सुन्न तलको QR कोडलाई केन्द्र भागमा पार्नुहोस्"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"QR कोडको फर्म्याट वैध छैन"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"<xliff:g id="APP_NAME">%1$s</xliff:g> ब्रोडकास्ट गर्न छाड्ने हो?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"तपाईंले <xliff:g id="SWITCHAPP">%1$s</xliff:g> ब्रोडकास्ट गर्नुभयो वा आउटपुट परिवर्तन गर्नुभयो भने तपाईंको हालको ब्रोडकास्ट रोकिने छ"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"<xliff:g id="SWITCHAPP">%1$s</xliff:g> ब्रोडकास्ट गर्नुहोस्"</string>
diff --git a/packages/SettingsLib/res/values-nl/strings.xml b/packages/SettingsLib/res/values-nl/strings.xml
index 0b52e9ea6070..8a487619ab82 100644
--- a/packages/SettingsLib/res/values-nl/strings.xml
+++ b/packages/SettingsLib/res/values-nl/strings.xml
@@ -667,9 +667,6 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Scherm aanzetten"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Scherm aanzetten toestaan"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Toestaan dat een app het scherm aanzet. Indien toegestaan, kan de app het scherm op elk moment aanzetten zonder jouw expliciete intentie."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"QR-code scannen"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Centreer de onderstaande QR-code om te beginnen met luisteren"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"QR-code heeft geen geldige indeling"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"Uitzending van <xliff:g id="APP_NAME">%1$s</xliff:g> stopzetten?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"Als je <xliff:g id="SWITCHAPP">%1$s</xliff:g> uitzendt of de uitvoer wijzigt, wordt je huidige uitzending gestopt"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"<xliff:g id="SWITCHAPP">%1$s</xliff:g> uitzenden"</string>
diff --git a/packages/SettingsLib/res/values-or/strings.xml b/packages/SettingsLib/res/values-or/strings.xml
index 1649550cc4ca..3ae906d47d0a 100644
--- a/packages/SettingsLib/res/values-or/strings.xml
+++ b/packages/SettingsLib/res/values-or/strings.xml
@@ -667,17 +667,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"ସ୍କ୍ରିନକୁ ଚାଲୁ କରନ୍ତୁ"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"ସ୍କ୍ରିନକୁ ଚାଲୁ କରିବା ପାଇଁ ଅନୁମତି ଦିଅନ୍ତୁ"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"ସ୍କ୍ରିନକୁ ଚାଲୁ କରିବା ପାଇଁ ଏକ ଆପକୁ ଅନୁମତି ଦିଅନ୍ତୁ। ଯଦି ଅନୁମତି ଦିଆଯାଏ, ତେବେ ଆପଟି ଆପଣଙ୍କ ସ୍ପଷ୍ଟ ଇଣ୍ଟେଣ୍ଟ ବିନା ଯେ କୌଣସି ସମୟରେ ସ୍କ୍ରିନକୁ ଚାଲୁ କରିପାରେ।"</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"QR କୋଡ ସ୍କାନ କରନ୍ତୁ"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"ଶୁଣିବା ଆରମ୍ଭ କରିବା ପାଇଁ, ନିମ୍ନରେ ଥିବା QR କୋଡକୁ କେନ୍ଦ୍ରରେ ରଖନ୍ତୁ"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"QR କୋଡ ଏକ ବୈଧ ଫର୍ମାଟ ନୁହେଁ"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"<xliff:g id="APP_NAME">%1$s</xliff:g> ବ୍ରଡକାଷ୍ଟ କରିବା ବନ୍ଦ କରିବେ?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"ଯଦି ଆପଣ <xliff:g id="SWITCHAPP">%1$s</xliff:g> ବ୍ରଡକାଷ୍ଟ କରନ୍ତି କିମ୍ବା ଆଉଟପୁଟ ବଦଳାନ୍ତି, ତେବେ ଆପଣଙ୍କ ବର୍ତ୍ତମାନର ବ୍ରଡକାଷ୍ଟ ବନ୍ଦ ହୋଇଯିବ"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"<xliff:g id="SWITCHAPP">%1$s</xliff:g> ବ୍ରଡକାଷ୍ଟ କରନ୍ତୁ"</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"ଆଉଟପୁଟ ବଦଳାନ୍ତୁ"</string>
- <!-- no translation found for back_navigation_animation (8105467568421689484) -->
- <skip />
- <!-- no translation found for back_navigation_animation_summary (741292224121599456) -->
- <skip />
- <!-- no translation found for back_navigation_animation_dialog (8696966520944625596) -->
- <skip />
+ <string name="back_navigation_animation" msgid="8105467568421689484">"ପ୍ରେଡିକ୍ଟିଭ ବ୍ୟାକ ଆନିମେସନ"</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"ପ୍ରେଡିକ୍ଟିଭ ବ୍ୟାକ ପାଇଁ ସିଷ୍ଟମ ଆନିମେସନଗୁଡ଼ିକୁ ସକ୍ଷମ କରନ୍ତୁ।"</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"ଏହି ସେଟିଂ ପ୍ରେଡିକ୍ଟିଭ ଜେଶ୍ଚର ଆନିମେସନ ପାଇଁ ସିଷ୍ଟମ ଆନିମେସନଗୁଡ଼ିକୁ ସକ୍ଷମ କରେ। ଏଥିପାଇଁ ମାନିଫେଷ୍ଟ ଫାଇଲରେ ପ୍ରତି-ଆପ enableOnBackInvokedCallbackକୁ \"ଠିକ\"ରେ ସେଟ କରିବା ଆବଶ୍ୟକ।"</string>
</resources>
diff --git a/packages/SettingsLib/res/values-pa/strings.xml b/packages/SettingsLib/res/values-pa/strings.xml
index 8cda50050b63..84b0f8bdfaf6 100644
--- a/packages/SettingsLib/res/values-pa/strings.xml
+++ b/packages/SettingsLib/res/values-pa/strings.xml
@@ -667,17 +667,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"ਸਕ੍ਰੀਨ ਚਾਲੂ ਕਰੋ"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"ਸਕ੍ਰੀਨ ਚਾਲੂ ਕਰਨ ਦਿਓ"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"ਐਪ ਨੂੰ ਸਕ੍ਰੀਨ ਚਾਲੂ ਕਰਨ ਦਿਓ। ਜੇ ਇਜਾਜ਼ਤ ਦਿੱਤੀ ਜਾਂਦੀ ਹੈ, ਤਾਂ ਐਪ ਕਿਸੇ ਵੀ ਸਮੇਂ ਸਕ੍ਰੀਨ ਨੂੰ ਚਾਲੂ ਕਰ ਸਕਦੀ ਹੈ, ਭਾਵੇਂ ਤੁਹਾਨੂੰ ਇਸਦੀ ਲੋੜ ਨਾ ਹੋਵੇ।"</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"QR ਕੋਡ ਸਕੈਨ ਕਰੋ"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"ਸੁਣਨਾ ਸ਼ੁਰੂ ਕਰਨ ਲਈ, ਹੇਠਾਂ ਦਿੱਤੇ QR ਕੋਡ ਨੂੰ ਕੇਂਦਰ ਵਿੱਚ ਰੱਖੋ"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"QR ਕੋਡ ਦਾ ਫਾਰਮੈਟ ਵੈਧ ਨਹੀਂ ਹੈ"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"ਕੀ <xliff:g id="APP_NAME">%1$s</xliff:g> ਦੇ ਪ੍ਰਸਾਰਨ ਨੂੰ ਰੋਕਣਾ ਹੈ?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"ਜੇ ਤੁਸੀਂ <xliff:g id="SWITCHAPP">%1$s</xliff:g> ਦਾ ਪ੍ਰਸਾਰਨ ਕਰਦੇ ਹੋ ਜਾਂ ਆਊਟਪੁੱਟ ਬਦਲਦੇ ਹੋ, ਤਾਂ ਤੁਹਾਡਾ ਮੌਜੂਦਾ ਪ੍ਰਸਾਰਨ ਰੁਕ ਜਾਵੇਗਾ"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"<xliff:g id="SWITCHAPP">%1$s</xliff:g> ਦਾ ਪ੍ਰਸਾਰਨ ਕਰੋ"</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"ਆਊਟਪੁੱਟ ਬਦਲੋ"</string>
- <!-- no translation found for back_navigation_animation (8105467568421689484) -->
- <skip />
- <!-- no translation found for back_navigation_animation_summary (741292224121599456) -->
- <skip />
- <!-- no translation found for back_navigation_animation_dialog (8696966520944625596) -->
- <skip />
+ <string name="back_navigation_animation" msgid="8105467568421689484">"ਪਿਛਲੇ ਐਨੀਮੇਸ਼ਨਾਂ ਦਾ ਪੂਰਵ-ਅਨੁਮਾਨ"</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"ਪੂਰਵ-ਅਨੁਮਾਨ ਵਾਪਸੀ ਲਈ ਸਿਸਟਮ ਐਨੀਮੇਸ਼ਨਾਂ ਨੂੰ ਚਾਲੂ ਕਰੋ।"</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"ਇਹ ਸੈਟਿੰਗ ਪੂਰਵ-ਅਨੁਮਾਨ ਇਸ਼ਾਰਾ ਐਨੀਮੇਸ਼ਨ ਲਈ ਸਿਸਟਮ ਐਨੀਮੇਸ਼ਨਾਂ ਨੂੰ ਚਾਲੂ ਕਰਦੀ ਹੈ। ਮੈਨੀਫ਼ੈਸਟ ਫ਼ਾਈਲ ਵਿੱਚ enableOnBackInvokedCallback ਸੈਟਿੰਗ ਨੂੰ ਪ੍ਰਤੀ-ਐਪ \'ਸਹੀ\' \'ਤੇ ਕਰਨ ਦੀ ਲੋੜ ਹੈ।"</string>
</resources>
diff --git a/packages/SettingsLib/res/values-pl/strings.xml b/packages/SettingsLib/res/values-pl/strings.xml
index 3488532f3506..523ec7c878b8 100644
--- a/packages/SettingsLib/res/values-pl/strings.xml
+++ b/packages/SettingsLib/res/values-pl/strings.xml
@@ -667,17 +667,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Włączanie ekranu"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Zezwalaj na włączanie ekranu"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Zezwalaj na włączanie ekranu przez aplikację. Gdy przyznasz te uprawnienia, aplikacja będzie mogła w dowolnym momencie włączyć ekran bez Twojego wyraźnego pozwolenia."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"Skaner kodów QR"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Aby odsłuchać, wyśrodkuj kod QR poniżej"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"Nieprawidłowy format kodu QR"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"Zatrzymaj transmisję aplikacji <xliff:g id="APP_NAME">%1$s</xliff:g>?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"Jeśli transmitujesz aplikację <xliff:g id="SWITCHAPP">%1$s</xliff:g> lub zmieniasz dane wyjściowe, Twoja obecna transmisja zostanie zakończona"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"Transmisja aplikacji <xliff:g id="SWITCHAPP">%1$s</xliff:g>"</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"Zmień dane wyjściowe"</string>
- <!-- no translation found for back_navigation_animation (8105467568421689484) -->
- <skip />
- <!-- no translation found for back_navigation_animation_summary (741292224121599456) -->
- <skip />
- <!-- no translation found for back_navigation_animation_dialog (8696966520944625596) -->
- <skip />
+ <string name="back_navigation_animation" msgid="8105467568421689484">"Animacje przewidywanego przejścia wstecz"</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"Włącz animacje systemowe dla przewidywanego przejścia wstecz."</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"To ustawienie uruchamia animacje systemowe dla przewidywanych gestów. Wymaga ustawienia w pliku manifestu wartości true w polu enableOnBackInvokedCallback dla każdej aplikacji."</string>
</resources>
diff --git a/packages/SettingsLib/res/values-pt-rBR/strings.xml b/packages/SettingsLib/res/values-pt-rBR/strings.xml
index c8f57d5b6feb..d7d723ceed44 100644
--- a/packages/SettingsLib/res/values-pt-rBR/strings.xml
+++ b/packages/SettingsLib/res/values-pt-rBR/strings.xml
@@ -594,7 +594,7 @@
<string name="guest_exit_guest" msgid="5908239569510734136">"Remover convidado"</string>
<string name="guest_reset_guest" msgid="6110013010356013758">"Redefinir sessão de visitante"</string>
<string name="guest_reset_guest_dialog_title" msgid="8047270010895437534">"Redefinir visitante?"</string>
- <string name="guest_remove_guest_dialog_title" msgid="4548511006624088072">"Remover convidado?"</string>
+ <string name="guest_remove_guest_dialog_title" msgid="4548511006624088072">"Remover visitante?"</string>
<string name="guest_reset_guest_confirm_button" msgid="2989915693215617237">"Redefinir"</string>
<string name="guest_remove_guest_confirm_button" msgid="7858123434954143879">"Remover"</string>
<string name="guest_resetting" msgid="7822120170191509566">"Redefinindo visitante…"</string>
@@ -667,17 +667,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Ligar tela"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Permitir que a tela seja ligada"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Permitir que um app ligue a tela. Se permitido, o app vai poder ligar a tela a qualquer momento sem uma intent explícita."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"Ler o código QR"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Para começar a ouvir, centralize o código QR abaixo"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"O código QR não está em um formato válido"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"Interromper a transmissão do app <xliff:g id="APP_NAME">%1$s</xliff:g>?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"Se você transmitir o app <xliff:g id="SWITCHAPP">%1$s</xliff:g> ou mudar a saída, a transmissão atual será interrompida"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"Transmitir <xliff:g id="SWITCHAPP">%1$s</xliff:g>"</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"Mudar saída"</string>
- <!-- no translation found for back_navigation_animation (8105467568421689484) -->
- <skip />
- <!-- no translation found for back_navigation_animation_summary (741292224121599456) -->
- <skip />
- <!-- no translation found for back_navigation_animation_dialog (8696966520944625596) -->
- <skip />
+ <string name="back_navigation_animation" msgid="8105467568421689484">"Animações de gestos \"Voltar\" preditivos"</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"Ativar animações do sistema para gestos \"Voltar\" preditivos."</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"Esta configuração ativa animações do sistema para gestos preditivos. Ela requer que a política enableOnBackInvokedCallback por app seja definida como verdadeira no arquivo de manifesto."</string>
</resources>
diff --git a/packages/SettingsLib/res/values-pt-rPT/strings.xml b/packages/SettingsLib/res/values-pt-rPT/strings.xml
index dbda70ddd73f..1a8bd8993a94 100644
--- a/packages/SettingsLib/res/values-pt-rPT/strings.xml
+++ b/packages/SettingsLib/res/values-pt-rPT/strings.xml
@@ -600,7 +600,7 @@
<string name="guest_resetting" msgid="7822120170191509566">"A repor o convidado…"</string>
<string name="guest_reset_and_restart_dialog_title" msgid="3396657008451616041">"Repor sessão de convidado?"</string>
<string name="guest_reset_and_restart_dialog_message" msgid="2764425635305200790">"Esta ação inicia uma nova sessão de convidado e elimina todas as apps e dados da sessão atual"</string>
- <string name="guest_exit_dialog_title" msgid="1846494656849381804">"Sair do modo de convidado?"</string>
+ <string name="guest_exit_dialog_title" msgid="1846494656849381804">"Sair do modo convidado?"</string>
<string name="guest_exit_dialog_message" msgid="1743218864242719783">"Esta ação elimina as apps e os dados da sessão de convidado atual"</string>
<string name="guest_exit_dialog_button" msgid="1736401897067442044">"Sair"</string>
<string name="guest_exit_dialog_title_non_ephemeral" msgid="7675327443743162986">"Guardar atividade de convidado?"</string>
@@ -667,9 +667,6 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Ative o ecrã"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Permitir a ativação do ecrã"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Permita que uma app ative o ecrã. Se a autorização for concedida, a app pode ativar o ecrã em qualquer altura sem a sua intenção explícita."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"Leia o código QR"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Para começar a ouvir, centre o código QR abaixo"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"O código QR não é um formato válido"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"Interromper a transmissão da app <xliff:g id="APP_NAME">%1$s</xliff:g>?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"Se transmitir a app <xliff:g id="SWITCHAPP">%1$s</xliff:g> ou alterar a saída, a sua transmissão atual é interrompida"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"Transmita a app <xliff:g id="SWITCHAPP">%1$s</xliff:g>"</string>
diff --git a/packages/SettingsLib/res/values-pt/strings.xml b/packages/SettingsLib/res/values-pt/strings.xml
index c8f57d5b6feb..d7d723ceed44 100644
--- a/packages/SettingsLib/res/values-pt/strings.xml
+++ b/packages/SettingsLib/res/values-pt/strings.xml
@@ -594,7 +594,7 @@
<string name="guest_exit_guest" msgid="5908239569510734136">"Remover convidado"</string>
<string name="guest_reset_guest" msgid="6110013010356013758">"Redefinir sessão de visitante"</string>
<string name="guest_reset_guest_dialog_title" msgid="8047270010895437534">"Redefinir visitante?"</string>
- <string name="guest_remove_guest_dialog_title" msgid="4548511006624088072">"Remover convidado?"</string>
+ <string name="guest_remove_guest_dialog_title" msgid="4548511006624088072">"Remover visitante?"</string>
<string name="guest_reset_guest_confirm_button" msgid="2989915693215617237">"Redefinir"</string>
<string name="guest_remove_guest_confirm_button" msgid="7858123434954143879">"Remover"</string>
<string name="guest_resetting" msgid="7822120170191509566">"Redefinindo visitante…"</string>
@@ -667,17 +667,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Ligar tela"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Permitir que a tela seja ligada"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Permitir que um app ligue a tela. Se permitido, o app vai poder ligar a tela a qualquer momento sem uma intent explícita."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"Ler o código QR"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Para começar a ouvir, centralize o código QR abaixo"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"O código QR não está em um formato válido"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"Interromper a transmissão do app <xliff:g id="APP_NAME">%1$s</xliff:g>?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"Se você transmitir o app <xliff:g id="SWITCHAPP">%1$s</xliff:g> ou mudar a saída, a transmissão atual será interrompida"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"Transmitir <xliff:g id="SWITCHAPP">%1$s</xliff:g>"</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"Mudar saída"</string>
- <!-- no translation found for back_navigation_animation (8105467568421689484) -->
- <skip />
- <!-- no translation found for back_navigation_animation_summary (741292224121599456) -->
- <skip />
- <!-- no translation found for back_navigation_animation_dialog (8696966520944625596) -->
- <skip />
+ <string name="back_navigation_animation" msgid="8105467568421689484">"Animações de gestos \"Voltar\" preditivos"</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"Ativar animações do sistema para gestos \"Voltar\" preditivos."</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"Esta configuração ativa animações do sistema para gestos preditivos. Ela requer que a política enableOnBackInvokedCallback por app seja definida como verdadeira no arquivo de manifesto."</string>
</resources>
diff --git a/packages/SettingsLib/res/values-ro/strings.xml b/packages/SettingsLib/res/values-ro/strings.xml
index 085226eea1ce..9ef302c806a9 100644
--- a/packages/SettingsLib/res/values-ro/strings.xml
+++ b/packages/SettingsLib/res/values-ro/strings.xml
@@ -667,17 +667,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Activați ecranul"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Permiteți activarea ecranului"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Permiteți unei aplicații să activeze ecranul. Dacă acordați permisiunea, aplicația poate să activeze oricând ecranul, fără intenția dvs. explicită."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"Scanați codul QR"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Pentru a începe să ascultați, centrați codul QR de mai jos"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"Codul QR nu are un format valid"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"Opriți difuzarea <xliff:g id="APP_NAME">%1$s</xliff:g>?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"Dacă difuzați <xliff:g id="SWITCHAPP">%1$s</xliff:g> sau schimbați rezultatul, difuzarea actuală se va opri"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"Difuzați <xliff:g id="SWITCHAPP">%1$s</xliff:g>"</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"Schimbați rezultatul"</string>
- <!-- no translation found for back_navigation_animation (8105467568421689484) -->
- <skip />
- <!-- no translation found for back_navigation_animation_summary (741292224121599456) -->
- <skip />
- <!-- no translation found for back_navigation_animation_dialog (8696966520944625596) -->
- <skip />
+ <string name="back_navigation_animation" msgid="8105467568421689484">"Animații pentru gestul înapoi predictiv"</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"Activați animațiile de sistem pentru gestul înapoi predictiv."</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"Această setare activează animațiile de sistem pentru animația gesturilor predictive. Necesită setarea valorii true în cazul atributului enableOnBackInvokedCallback pentru fiecare aplicație în fișierul manifest."</string>
</resources>
diff --git a/packages/SettingsLib/res/values-ru/strings.xml b/packages/SettingsLib/res/values-ru/strings.xml
index dfd052b37682..fd061549d752 100644
--- a/packages/SettingsLib/res/values-ru/strings.xml
+++ b/packages/SettingsLib/res/values-ru/strings.xml
@@ -667,9 +667,6 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Включение экрана"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Разрешить приложению включать экран"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Приложение сможет в любое время включать экран без явного согласия с вашей стороны"</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"Сканирование QR-кода"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Чтобы прослушать, поместите QR-код в центр"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"Недопустимый формат QR-кода"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"Остановить трансляцию \"<xliff:g id="APP_NAME">%1$s</xliff:g>\"?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"Если вы начнете транслировать \"<xliff:g id="SWITCHAPP">%1$s</xliff:g>\" или смените целевое устройство, текущая трансляция прервется."</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"Транслировать \"<xliff:g id="SWITCHAPP">%1$s</xliff:g>\""</string>
diff --git a/packages/SettingsLib/res/values-si/strings.xml b/packages/SettingsLib/res/values-si/strings.xml
index 3da503455451..347c5c8f934d 100644
--- a/packages/SettingsLib/res/values-si/strings.xml
+++ b/packages/SettingsLib/res/values-si/strings.xml
@@ -284,7 +284,7 @@
<string name="mobile_data_always_on" msgid="8275958101875563572">"ජංගම දත්ත සැමවිට ක්‍රියාකාරීය"</string>
<string name="tethering_hardware_offload" msgid="4116053719006939161">"ටෙදරින් දෘඪාංග ත්වරණය"</string>
<string name="bluetooth_show_devices_without_names" msgid="923584526471885819">"නම් නොමැති බ්ලූටූත් උපාංග පෙන්වන්න"</string>
- <string name="bluetooth_disable_absolute_volume" msgid="1452342324349203434">"නිරපේක්ෂ හඩ පරිමාව අබල කරන්න"</string>
+ <string name="bluetooth_disable_absolute_volume" msgid="1452342324349203434">"නිරපේක්ෂ හඩ අබල කරන්න"</string>
<string name="bluetooth_enable_gabeldorsche" msgid="9131730396242883416">"Gabeldorsche සබල කරන්න"</string>
<string name="bluetooth_select_avrcp_version_string" msgid="1710571610177659127">"බ්ලූටූත් AVRCP අනුවාදය"</string>
<string name="bluetooth_select_avrcp_version_dialog_title" msgid="7846922290083709633">"බ්ලූටූත් AVRCP අනුවාදය තෝරන්න"</string>
@@ -338,7 +338,7 @@
<string name="verify_apps_over_usb_title" msgid="6031809675604442636">"USB ඔස්සේ යෙදුම් සත්‍යාපනය කරගන්න"</string>
<string name="verify_apps_over_usb_summary" msgid="1317933737581167839">"ADB/ADT හරහා ස්ථාපනය වූ යෙදුම්, විනාශකාරී ක්‍රියාවන් ඇත්දැයි පරික්ෂාකර බලන්න."</string>
<string name="bluetooth_show_devices_without_names_summary" msgid="780964354377854507">"නම් නොමැති බ්ලූටූත් උපාංග (MAC ලිපින පමණි) සංදර්ශනය කරනු ඇත"</string>
- <string name="bluetooth_disable_absolute_volume_summary" msgid="2006309932135547681">"පිළිගත නොහැකි ලෙස වැඩි හඩ පරිමාව හෝ පාලනය නොමැති වීම යනාදී දුරස්ථ උපාංග සමගින් වන හඬ පරිමා ගැටලුවලදී බ්ලූටූත් නිරපේක්ෂ හඬ පරිමා විශේෂාංගය අබල කරයි."</string>
+ <string name="bluetooth_disable_absolute_volume_summary" msgid="2006309932135547681">"පිළිගත නොහැකි ලෙස වැඩි හඩ හෝ පාලනය නොමැති වීම යනාදී දුරස්ථ උපාංග සමගින් වන හඬ පරිමා ගැටලුවලදී බ්ලූටූත් නිරපේක්ෂ හඬ පරිමා විශේෂාංගය අබල කරයි."</string>
<string name="bluetooth_enable_gabeldorsche_summary" msgid="2054730331770712629">"Bluetooth Gabeldorsche විශේෂාංග අට්ටිය සබල කරයි."</string>
<string name="enhanced_connectivity_summary" msgid="1576414159820676330">"වැඩිදියුණු කළ සබැඳුම් හැකියා විශේෂාංගය සබල කරයි."</string>
<string name="enable_terminal_title" msgid="3834790541986303654">"අභ්‍යන්තර අන්තය"</string>
@@ -667,17 +667,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"තිරය ක්‍රියාත්මක කරන්න"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"තිරය ක්‍රියාත්මක කිරීමට ඉඩ දෙන්න"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"යෙදුමකට තිරය ක්‍රියාත්මක කිරීමට ඉඩ දෙන්න. ඉඩ දුනහොත්, යෙදුම ඔබගේ පැහැදිලි අභිප්‍රායෙන් තොරව ඕනෑම වේලාවක තිරය ක්‍රියාත්මක කළ හැකිය."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"QR කේතය ස්කෑන් කරන්න"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"සවන් දීම ආරම්භ කිරීමට, පහත QR කේතය මධ්‍යගත කරන්න"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"QR කේතය වලංගු ආකෘතියක් නොවේ"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"<xliff:g id="APP_NAME">%1$s</xliff:g> විකාශනය කිරීම නවත්වන්නද?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"ඔබ <xliff:g id="SWITCHAPP">%1$s</xliff:g> විකාශනය කළහොත් හෝ ප්‍රතිදානය වෙනස් කළහොත්, ඔබගේ වත්මන් විකාශනය නවතිනු ඇත."</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"<xliff:g id="SWITCHAPP">%1$s</xliff:g> විකාශනය"</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"ප්‍රතිදානය වෙනස් කරන්න"</string>
- <!-- no translation found for back_navigation_animation (8105467568421689484) -->
- <skip />
- <!-- no translation found for back_navigation_animation_summary (741292224121599456) -->
- <skip />
- <!-- no translation found for back_navigation_animation_dialog (8696966520944625596) -->
- <skip />
+ <string name="back_navigation_animation" msgid="8105467568421689484">"පුරෝකථනමය පසු සජීවිකරණ"</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"පුරෝකථනමය ආපසු සඳහා පද්ධති සජීවිකරණ සබල කරන්න."</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"මෙම සැකසීම පුරෝකථනමය ඉංගිත සජීවිකරණය සඳහා පද්ධති සජීවිකරණ සබල කරයි. එයට මැනිෆෙස්ට් ගොනුව තුළ එක් යෙදුමකට enableOnBackInvokedCallback සත්‍ය ලෙස සැකසීම අවශ්‍ය වේ."</string>
</resources>
diff --git a/packages/SettingsLib/res/values-sk/strings.xml b/packages/SettingsLib/res/values-sk/strings.xml
index c398f661e43a..7394985be2ff 100644
--- a/packages/SettingsLib/res/values-sk/strings.xml
+++ b/packages/SettingsLib/res/values-sk/strings.xml
@@ -405,7 +405,7 @@
<string name="force_allow_on_external" msgid="9187902444231637880">"Vynútiť povolenie aplikácií na externom úložisku"</string>
<string name="force_allow_on_external_summary" msgid="8525425782530728238">"Umožniť zapísať akúkoľvek aplikáciu do externého úložiska bez ohľadu na hodnoty v manifeste"</string>
<string name="force_resizable_activities" msgid="7143612144399959606">"Vynútiť možnosť zmeny veľkosti aktivít"</string>
- <string name="force_resizable_activities_summary" msgid="2490382056981583062">"Umožniť veľkosť všetkých aktivít na niekoľko okien (bez ohľadu na hodnoty manifestu)"</string>
+ <string name="force_resizable_activities_summary" msgid="2490382056981583062">"Umožniť zmeniť veľkosť všetkých aktivít na niekoľko okien (bez ohľadu na hodnoty manifestu)"</string>
<string name="enable_freeform_support" msgid="7599125687603914253">"Povoliť okná s voľným tvarom"</string>
<string name="enable_freeform_support_summary" msgid="1822862728719276331">"Povoliť podporu pre experimentálne okná s voľným tvarom"</string>
<string name="local_backup_password_title" msgid="4631017948933578709">"Heslo pre zálohy v počítači"</string>
@@ -667,9 +667,6 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Zapínanie obrazovky"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Povolenie zapínania obrazovky"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Povoľte aplikácii zapínať obrazovku. Ak to urobíte, aplikácia bude môcť kedykoľvek zapínať obrazovku, a to aj vtedy, keď to nebudete mať v úmysle."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"Naskenovanie QR kódu"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Ak chcete začať počúvať, umiestnite QR kód do stredu nižšie"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"QR kód nie je platný formát"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"Chcete zastaviť vysielanie aplikácie <xliff:g id="APP_NAME">%1$s</xliff:g>?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"Ak vysielate aplikáciu <xliff:g id="SWITCHAPP">%1$s</xliff:g> alebo zmeníte výstup, aktuálne vysielanie bude zastavené"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"Vysielanie aplikácie <xliff:g id="SWITCHAPP">%1$s</xliff:g>"</string>
diff --git a/packages/SettingsLib/res/values-sl/strings.xml b/packages/SettingsLib/res/values-sl/strings.xml
index 0d0a0de97cce..28824a3504d3 100644
--- a/packages/SettingsLib/res/values-sl/strings.xml
+++ b/packages/SettingsLib/res/values-sl/strings.xml
@@ -667,9 +667,6 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Vklop zaslona"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Dovoli vklop zaslona"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Dovolite aplikaciji, da vklopi zaslon. Če ji to odobrite, lahko aplikacija kadar koli brez vašega eksplicitnega namena vklopi zaslon."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"Optično branje kode QR"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Če želite začeti poslušati, postavite spodnjo kodo QR na sredino."</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"Koda QR nima pravilne oblike zapisa."</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"Želite ustaviti oddajanje aplikacije <xliff:g id="APP_NAME">%1$s</xliff:g>?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"Če oddajate aplikacijo <xliff:g id="SWITCHAPP">%1$s</xliff:g> ali spremenite izhod, bo trenutno oddajanje ustavljeno."</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"Oddajaj aplikacijo <xliff:g id="SWITCHAPP">%1$s</xliff:g>"</string>
diff --git a/packages/SettingsLib/res/values-sq/strings.xml b/packages/SettingsLib/res/values-sq/strings.xml
index ec64a925c0f0..27fe4549e8e3 100644
--- a/packages/SettingsLib/res/values-sq/strings.xml
+++ b/packages/SettingsLib/res/values-sq/strings.xml
@@ -667,17 +667,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Ndiz ekranin"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Lejo ndezjen e ekranit"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Lejo një aplikacion që të ndezë ekranin. Nëse lejohet, aplikacioni mund ta ndezë ekranin në çdo kohë pa synimin tënd të shprehur."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"Skano kodin QR"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Që të fillosh të dëgjosh, vendos në qendër kodin QR më poshtë"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"Kodi QR nuk është në format të vlefshëm"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"Të ndalohet transmetimi i <xliff:g id="APP_NAME">%1$s</xliff:g>?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"Nëse transmeton <xliff:g id="SWITCHAPP">%1$s</xliff:g> ose ndryshon daljen, transmetimi yt aktual do të ndalojë"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"Transmeto <xliff:g id="SWITCHAPP">%1$s</xliff:g>"</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"Ndrysho daljen"</string>
- <!-- no translation found for back_navigation_animation (8105467568421689484) -->
- <skip />
- <!-- no translation found for back_navigation_animation_summary (741292224121599456) -->
- <skip />
- <!-- no translation found for back_navigation_animation_dialog (8696966520944625596) -->
- <skip />
+ <string name="back_navigation_animation" msgid="8105467568421689484">"Animacionet për gjestin e parashikuar të kthimit prapa"</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"Aktivizo animacionet e sistemit për gjestin e parashikuar të kthimit prapa."</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"Ky cilësim aktivizon animacionet e sistemit për animacionin e gjestit të parashikuar. Ai kërkon që enableOnBackInvokedCallback për aplikacionin të jetë caktuar si i vërtetë në skedarin e manifestit."</string>
</resources>
diff --git a/packages/SettingsLib/res/values-sr/strings.xml b/packages/SettingsLib/res/values-sr/strings.xml
index ff73639f0460..768cb1e6fde1 100644
--- a/packages/SettingsLib/res/values-sr/strings.xml
+++ b/packages/SettingsLib/res/values-sr/strings.xml
@@ -667,9 +667,6 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Укључите екран"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Дозволи укључивање екрана"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Дозвољава апликацији да укључи екран. Ако се омогући, апликација може да укључи екран у било ком тренутку без ваше експлицитне намере."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"Скенирајте QR кôд"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Да бисте почели да слушате, центрирајте QR кôд испод"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"QR кôд није у важећем формату"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"Желите да зауставите емитовање апликације <xliff:g id="APP_NAME">%1$s</xliff:g>?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"Ако емитујете апликацију <xliff:g id="SWITCHAPP">%1$s</xliff:g> или промените излаз, актуелно емитовање ће се зауставити"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"Емитујте апликацију <xliff:g id="SWITCHAPP">%1$s</xliff:g>"</string>
diff --git a/packages/SettingsLib/res/values-sv/strings.xml b/packages/SettingsLib/res/values-sv/strings.xml
index e3960b2e4a78..2be1898e447d 100644
--- a/packages/SettingsLib/res/values-sv/strings.xml
+++ b/packages/SettingsLib/res/values-sv/strings.xml
@@ -667,17 +667,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Aktivera skärmen"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Tillåt att skärmen aktiveras"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Tillåt att en app aktiverar skärmen. Om du ger tillåtelse kan appen aktivera skärmen när som helst utan din uttryckliga avsikt."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"Skanna QR-kod"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Centrera QR-koden nedan om du vill börja lyssna"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"QR-kodens format är ogiltigt"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"Vill du sluta sända från <xliff:g id="APP_NAME">%1$s</xliff:g>?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"Om en utsändning från <xliff:g id="SWITCHAPP">%1$s</xliff:g> pågår eller om du byter ljudutgång avbryts den nuvarande utsändningen"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"Sänd från <xliff:g id="SWITCHAPP">%1$s</xliff:g>"</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"Byt ljudutgång"</string>
- <!-- no translation found for back_navigation_animation (8105467568421689484) -->
- <skip />
- <!-- no translation found for back_navigation_animation_summary (741292224121599456) -->
- <skip />
- <!-- no translation found for back_navigation_animation_dialog (8696966520944625596) -->
- <skip />
+ <string name="back_navigation_animation" msgid="8105467568421689484">"Förhandsanimationer för bakåtrörelser"</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"Aktivera systemanimationer som förhandsvisar bakåtrörelser."</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"Den här inställningen aktiverar systemanimationer som förhandsvisar vart rörelserna leder. Du måste ställa in enableOnBackInvokedCallback som sant per app i manifestfilen."</string>
</resources>
diff --git a/packages/SettingsLib/res/values-sw/strings.xml b/packages/SettingsLib/res/values-sw/strings.xml
index c2b75cd3f175..b4bd3cb27e08 100644
--- a/packages/SettingsLib/res/values-sw/strings.xml
+++ b/packages/SettingsLib/res/values-sw/strings.xml
@@ -570,9 +570,9 @@
<string name="user_add_profile_item_title" msgid="3111051717414643029">"Wasifu uliozuiwa"</string>
<string name="user_add_user_title" msgid="5457079143694924885">"Ungependa kuongeza mtumiaji?"</string>
<string name="user_add_user_message_long" msgid="1527434966294733380">"Unaweza kutumia kifaa hiki pamoja na watu wengine kwa kuongeza watumiaji wa ziada. Kila mtumiaji ana nafasi yake mwenyewe, ambayo anaweza kuweka programu, mandhari na vipengee vingine anavyopenda. Watumiaji pia wanaweza kurekebisha mipangilio ya kifaa inayoathiri kila mtu kama vile Wi-Fi.\n\nUnapomwongeza mtumiaji mpya, mtu huyo anahitaji kujitayarishia nafasi yake.\n\nMtumiaji yeyote anaweza kuwasasishia watumiaji wengine wote programu. Huenda mipangilio na huduma za ufikivu zisihamishiwe mtumiaji mgeni."</string>
- <string name="user_add_user_message_short" msgid="3295959985795716166">"Mtumiaji mpya utakayemwongeza atahitaji kuongeza akaunti yake.\n\nMtumiaji yoyote anaweza kusasisha programu kwa niaba ya wengine wote."</string>
+ <string name="user_add_user_message_short" msgid="3295959985795716166">"Mtumiaji mpya utakayemwongeza atahitaji kujitayarishia nafasi yake.\n\nMtumiaji yoyote anaweza kusasisha programu kwa niaba ya wengine wote."</string>
<string name="user_setup_dialog_title" msgid="8037342066381939995">"Mtumiaji aongezwe sasa?"</string>
- <string name="user_setup_dialog_message" msgid="269931619868102841">"Hakikisha kuwa mtu huyu anaweza kuchukua kifaa na kuweka mapendeleo yake"</string>
+ <string name="user_setup_dialog_message" msgid="269931619868102841">"Hakikisha kuwa mtu huyu anaweza kuchukua kifaa na kujitayarishia nafasi yake"</string>
<string name="user_setup_profile_dialog_message" msgid="4788197052296962620">"Ungependa kuweka wasifu sasa?"</string>
<string name="user_setup_button_setup_now" msgid="1708269547187760639">"Mwongeze sasa"</string>
<string name="user_setup_button_setup_later" msgid="8712980133555493516">"Si sasa"</string>
@@ -667,17 +667,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Washa skrini"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Ruhusu kuwasha skrini"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Ruhusu programu iwashe skrini. Ikiwa imepewa idhini, programu inaweza kuwasha skrini wakati wowote bila utaratibu wako dhahiri wa kuratibu."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"Changanua msimbo wa QR"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Ili uanze kusikiliza, weka katikati msimbo wa QR ulio hapa chini"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"Msimbo wa QR si muundo sahihi"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"Ungependa kusimamisha utangazaji kwenye <xliff:g id="APP_NAME">%1$s</xliff:g>?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"Ikiwa unatangaza kwenye <xliff:g id="SWITCHAPP">%1$s</xliff:g> au unabadilisha maudhui, tangazo lako la sasa litasimamishwa"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"Tangaza kwenye <xliff:g id="SWITCHAPP">%1$s</xliff:g>"</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"Badilisha maudhui"</string>
- <!-- no translation found for back_navigation_animation (8105467568421689484) -->
- <skip />
- <!-- no translation found for back_navigation_animation_summary (741292224121599456) -->
- <skip />
- <!-- no translation found for back_navigation_animation_dialog (8696966520944625596) -->
- <skip />
+ <string name="back_navigation_animation" msgid="8105467568421689484">"Uhuishaji wa utabiri wa kurudi nyuma"</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"Ruhusu uhuishaji wa mfumo wa utabiri wa kurudi nyuma."</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"Mipangilio hii inaruhusu uhuishaji wa mfumo wa uhuishaji wa utabiri wa ishara. Inahitaji kuweka mipangilio kwa kila programu enableOnBackInvokedCallback kuwa true katika faili ya maelezo."</string>
</resources>
diff --git a/packages/SettingsLib/res/values-ta/strings.xml b/packages/SettingsLib/res/values-ta/strings.xml
index 70e2c6283611..c79a2ede9d7f 100644
--- a/packages/SettingsLib/res/values-ta/strings.xml
+++ b/packages/SettingsLib/res/values-ta/strings.xml
@@ -117,7 +117,7 @@
<string name="bluetooth_profile_opp" msgid="6692618568149493430">"ஃபைல் இடமாற்றம்"</string>
<string name="bluetooth_profile_hid" msgid="2969922922664315866">"உள்ளீட்டுச் சாதனம்"</string>
<string name="bluetooth_profile_pan" msgid="1006235139308318188">"இணைய அணுகல்"</string>
- <string name="bluetooth_profile_pbap" msgid="7064307749579335765">"தொடர்புப் பகிர்தல்"</string>
+ <string name="bluetooth_profile_pbap" msgid="7064307749579335765">"தொடர்பைப் பகிர்தல்"</string>
<string name="bluetooth_profile_pbap_summary" msgid="2955819694801952056">"தொடர்புப் பகிர்தலுக்குப் பயன்படுத்து"</string>
<string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"இணைய இணைப்பு பகிர்தல்"</string>
<string name="bluetooth_profile_map" msgid="8907204701162107271">"உரைச் செய்திகள்"</string>
@@ -667,9 +667,6 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"திரையை ஆன் செய்தல்"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"திரையை ஆன் செய்வதை அனுமதி"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"திரையை ஆன் செய்ய ஓர் ஆப்ஸை அனுமதிக்கவும். அனுமதித்தால், உங்கள் தலையீடு இல்லாமலே ஆப்ஸ் எப்போது வேண்டுமானாலும் திரையை ஆன் செய்யக்கூடும்."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"QR குறியீட்டை ஸ்கேன் செய்யுங்கள்"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"ஆடியோவைக் கேட்க, கீழுள்ள QR குறியீட்டை மையப்படுத்திக் காட்டுங்கள்"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"QR குறியீடு சரியான வடிவமைப்பில் இல்லை"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"<xliff:g id="APP_NAME">%1$s</xliff:g> ஆப்ஸ் ஒலிபரப்பப்படுவதை நிறுத்தவா?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"நீங்கள் <xliff:g id="SWITCHAPP">%1$s</xliff:g> ஆப்ஸை ஒலிபரப்பினாலோ அவுட்புட்டை மாற்றினாலோ உங்களின் தற்போதைய ஒலிபரப்பு நிறுத்தப்படும்"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"<xliff:g id="SWITCHAPP">%1$s</xliff:g> ஆப்ஸை ஒலிபரப்பு"</string>
diff --git a/packages/SettingsLib/res/values-te/strings.xml b/packages/SettingsLib/res/values-te/strings.xml
index c711dc433df9..d0855a4e1c1d 100644
--- a/packages/SettingsLib/res/values-te/strings.xml
+++ b/packages/SettingsLib/res/values-te/strings.xml
@@ -148,7 +148,7 @@
<string name="bluetooth_le_audio_profile_summary_use_for" msgid="2778318636027348572">"LE_AUDIO కోసం ఉపయోగించండి"</string>
<string name="bluetooth_pairing_accept" msgid="2054232610815498004">"జత చేయి"</string>
<string name="bluetooth_pairing_accept_all_caps" msgid="2734383073450506220">"జత చేయి"</string>
- <string name="bluetooth_pairing_decline" msgid="6483118841204885890">"రద్దు చేయి"</string>
+ <string name="bluetooth_pairing_decline" msgid="6483118841204885890">"రద్దు చేయండి"</string>
<string name="bluetooth_pairing_will_share_phonebook" msgid="3064334458659165176">"పెయిర్ చేయడం వలన కనెక్ట్ చేయబడినప్పుడు మీ కాంటాక్ట్‌లకు అలాగే కాల్ హిస్టరీకి యాక్సెస్‌ను మంజూరు చేస్తుంది."</string>
<string name="bluetooth_pairing_error_message" msgid="6626399020672335565">"<xliff:g id="DEVICE_NAME">%1$s</xliff:g>తో జత చేయడం సాధ్యపడలేదు."</string>
<string name="bluetooth_pairing_pin_error_message" msgid="264422127613704940">"పిన్ లేదా పాస్‌కీ చెల్లని కారణంగా <xliff:g id="DEVICE_NAME">%1$s</xliff:g>తో పెయిర్ చేయడం సాధ్యపడలేదు."</string>
@@ -523,7 +523,7 @@
<string name="wifi_tether_connected_summary" msgid="5282919920463340158">"{count,plural, =0{0 పరికరం కనెక్ట్ చేయబడింది}=1{1 పరికరం కనెక్ట్ చేయబడింది}other{# పరికరాలు కనెక్ట్ చేయబడ్డాయి}}"</string>
<string name="accessibility_manual_zen_more_time" msgid="5141801092071134235">"ఎక్కువ సమయం."</string>
<string name="accessibility_manual_zen_less_time" msgid="6828877595848229965">"తక్కువ సమయం."</string>
- <string name="cancel" msgid="5665114069455378395">"రద్దు చేయి"</string>
+ <string name="cancel" msgid="5665114069455378395">"రద్దు చేయండి"</string>
<string name="okay" msgid="949938843324579502">"సరే"</string>
<string name="done" msgid="381184316122520313">"పూర్తయింది"</string>
<string name="alarms_and_reminders_label" msgid="6918395649731424294">"అలారాలు, రిమైండర్‌లు"</string>
@@ -569,8 +569,8 @@
<string name="user_add_user_item_title" msgid="2394272381086965029">"యూజర్"</string>
<string name="user_add_profile_item_title" msgid="3111051717414643029">"పరిమితం చేయబడిన ప్రొఫైల్"</string>
<string name="user_add_user_title" msgid="5457079143694924885">"కొత్త యూజర్‌ను జోడించాలా?"</string>
- <string name="user_add_user_message_long" msgid="1527434966294733380">"అదనపు యూజర్‌లను క్రియేట్ చేయడం ద్వారా మీరు ఈ దేవైజ్‌ను ఇతరులతో షేర్ చేయవచ్చు. ప్రతి యూజర్‌కు‌ వారికంటూ ప్రత్యేక స్థలం ఉంటుంది, వారు ఆ స్థలాన్ని యాప్‌లు, వాల్‌పేపర్ మొదలైనవాటితో అనుకూలీకరించవచ్చు. యూజర్‌లు ప్రతి ఒక్కరిపై ప్రభావం చూపే Wi‑Fi వంటి పరికర సెట్టింగ్‌లను కూడా సర్దుబాటు చేయవచ్చు.\n\nమీరు కొత్త యూజర్ ను జోడించినప్పుడు, ఆ వ్యక్తి వారికంటూ స్వంత స్థలం సెట్ చేసుకోవాలి.\n\nఏ వినియోగదారు అయినా మిగిలిన అందరు యూజర్‌ల కోసం యాప్‌లను అప్‌డేట్ చేయవచ్చు. యాక్సెసిబిలిటీ సెట్టింగ్‌లు మరియు సేవలు కొత్త యూజర్‌కి బదిలీ కాకపోవచ్చు."</string>
- <string name="user_add_user_message_short" msgid="3295959985795716166">"మీరు కొత్త యూజర్‌ను = జోడించినప్పుడు, ఆ వ్యక్తి తన స్పేస్‌ను సెటప్ చేసుకోవాలి.\n\nఏ యూజర్ అయినా మిగతా యూజర్‌ల కోసం యాప్‌లను అప్‌డేట్‌ చేయగలరు."</string>
+ <string name="user_add_user_message_long" msgid="1527434966294733380">"అదనపు యూజర్‌లను క్రియేట్ చేయడం ద్వారా మీరు ఈ పరికరాన్ని ఇతరులతో షేర్ చేయవచ్చు. ప్రతి యూజర్‌కు‌ వారికంటూ ప్రత్యేక స్థలం ఉంటుంది, వారు ఆ స్థలాన్ని యాప్‌లు, వాల్‌పేపర్ మొదలైనవాటితో అనుకూలీకరించవచ్చు. యూజర్‌లు ప్రతి ఒక్కరిపై ప్రభావం చూపే Wi‑Fi వంటి పరికర సెట్టింగ్‌లను కూడా సర్దుబాటు చేయవచ్చు.\n\nమీరు కొత్త యూజర్‌ను జోడించినప్పుడు, ఆ వ్యక్తి వారికంటూ స్వంత స్థలం సెట్ చేసుకోవాలి.\n\nఏ యూజర్ అయినా మిగిలిన యూజర్‌లందరి కోసం యాప్‌లను అప్‌డేట్ చేయవచ్చు. యాక్సెసిబిలిటీ సెట్టింగ్‌లు, సర్వీస్‌లు కొత్త యూజర్‌కి బదిలీ కాకపోవచ్చు."</string>
+ <string name="user_add_user_message_short" msgid="3295959985795716166">"మీరు కొత్త యూజర్‌ను జోడించినప్పుడు, ఆ వ్యక్తి తన స్పేస్‌ను సెటప్ చేసుకోవాలి.\n\nఏ యూజర్ అయినా మిగతా యూజర్ల కోసం యాప్‌లను అప్‌డేట్‌ చేయగలరు."</string>
<string name="user_setup_dialog_title" msgid="8037342066381939995">"యూజర్‌ను ఇప్పుడే సెటప్ చేయాలా?"</string>
<string name="user_setup_dialog_message" msgid="269931619868102841">"పరికరాన్ని తీసుకోవడానికి వ్యక్తి అందుబాటులో ఉన్నారని నిర్ధారించుకొని, ఆపై వారికి నిల్వ స్థలాన్ని సెటప్ చేయండి"</string>
<string name="user_setup_profile_dialog_message" msgid="4788197052296962620">"ఇప్పుడు ప్రొఫైల్‌ను సెటప్ చేయాలా?"</string>
@@ -583,7 +583,7 @@
<string name="profile_info_settings_title" msgid="105699672534365099">"ప్రొఫైల్ సమాచారం"</string>
<string name="user_need_lock_message" msgid="4311424336209509301">"మీరు పరిమితం చేయబడిన ప్రొఫైల్‌ను క్రియేట్ చేయడానికి ముందు, మీ యాప్‌లు మరియు వ్యక్తిగత డేటాను రక్షించడానికి స్క్రీన్ లాక్‌ను సెటప్ చేయాల్సి ఉంటుంది."</string>
<string name="user_set_lock_button" msgid="1427128184982594856">"లాక్‌ను సెట్ చేయి"</string>
- <string name="user_switch_to_user" msgid="6975428297154968543">"<xliff:g id="USER_NAME">%s</xliff:g>‌కు స్విచ్ చేయి"</string>
+ <string name="user_switch_to_user" msgid="6975428297154968543">"<xliff:g id="USER_NAME">%s</xliff:g>‌కు స్విచ్ చేయండి"</string>
<string name="creating_new_user_dialog_message" msgid="7232880257538970375">"కొత్త యూజర్‌ను క్రియేట్ చేస్తోంది…"</string>
<string name="creating_new_guest_dialog_message" msgid="1114905602181350690">"కొత్త అతిథిని క్రియేట్ చేస్తోంది…"</string>
<string name="add_user_failed" msgid="4809887794313944872">"కొత్త యూజర్‌ను క్రియేట్ చేయడం విఫలమైంది"</string>
@@ -601,13 +601,13 @@
<string name="guest_reset_and_restart_dialog_title" msgid="3396657008451616041">"గెస్ట్ సెషన్‌ను రీసెట్ చేయాలా?"</string>
<string name="guest_reset_and_restart_dialog_message" msgid="2764425635305200790">"ఇది కొత్త గెస్ట్ సెషన్‌ను ప్రారంభిస్తుంది, ప్రస్తుత సెషన్ నుండి అన్ని యాప్‌లు, డేటాను తొలగిస్తుంది."</string>
<string name="guest_exit_dialog_title" msgid="1846494656849381804">"గెస్ట్ మోడ్ నిష్క్రమించాలా?"</string>
- <string name="guest_exit_dialog_message" msgid="1743218864242719783">"ఇది ప్రస్తుత గెస్ట్ సెషన్ నుండి యాప్‌లు, డేటాను తొలగిస్తుంది"</string>
+ <string name="guest_exit_dialog_message" msgid="1743218864242719783">"ఇది ప్రస్తుత గెస్ట్ సెషన్ నుండి యాప్‌లను వాటితో పాటు డేటాను తొలగిస్తుంది"</string>
<string name="guest_exit_dialog_button" msgid="1736401897067442044">"నిష్క్రమించండి"</string>
<string name="guest_exit_dialog_title_non_ephemeral" msgid="7675327443743162986">"గెస్ట్ యాక్టివిటీని సేవ్ చేయాలా?"</string>
<string name="guest_exit_dialog_message_non_ephemeral" msgid="223385323235719442">"మీరు సెషన్ నుండి యాక్టివిటీని సేవ్ చేయవచ్చు, అన్ని యాప్‌లు, డేటాను తొలగించవచ్చు"</string>
<string name="guest_exit_clear_data_button" msgid="3425812652180679014">"తొలగించండి"</string>
<string name="guest_exit_save_data_button" msgid="3690974510644963547">"సేవ్ చేయండి"</string>
- <string name="guest_exit_button" msgid="5774985819191803960">"గెస్ట్ మోడ్ నుండి నిష్క్రమణ"</string>
+ <string name="guest_exit_button" msgid="5774985819191803960">"గెస్ట్ మోడ్ నుండి వైదొలగండి"</string>
<string name="guest_reset_button" msgid="2515069346223503479">"గెస్ట్ సెషన్‌ను రీసెట్ చేయండి"</string>
<string name="guest_exit_quick_settings_button" msgid="1912362095913765471">"గెస్ట్ మోడ్ నుండి నిష్క్రమించండి"</string>
<string name="guest_notification_ephemeral" msgid="7263252466950923871">"నిష్క్రమణ సమయంలో మొత్తం యాక్టివిటీ తొలగించబడుతుంది"</string>
@@ -667,9 +667,6 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"స్క్రీన్‌ను ఆన్ చేయండి"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"స్క్రీన్‌ను ఆన్ చేయడానికి అనుమతించండి"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"స్క్రీన్‌ను ఆన్ చేయడానికి యాప్‌ను అనుమతించండి. మంజూరు చేయబడితే, మీ స్పష్టమైన ఉద్దేశం లేకుండా యాప్ ఎప్పుడైనా స్క్రీన్‌ను ఆన్ చేయవచ్చు."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"QR కోడ్‌ను స్కాన్ చేయండి"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"వినడం ప్రారంభించడానికి, కింద ఉన్న QR కోడ్‌ను మధ్యలో ఉంచండి"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"QR కోడ్ చెల్లుబాటు అయ్యే ఫార్మాట్‌లో లేదు"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"<xliff:g id="APP_NAME">%1$s</xliff:g> ప్రసారం చేయడాన్ని ఆపివేయాలా?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"మీరు <xliff:g id="SWITCHAPP">%1$s</xliff:g> ప్రసారం చేస్తే లేదా అవుట్‌పుట్‌ను మార్చినట్లయితే, మీ ప్రస్తుత ప్రసారం ఆగిపోతుంది"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"<xliff:g id="SWITCHAPP">%1$s</xliff:g> ప్రసారం చేయండి"</string>
diff --git a/packages/SettingsLib/res/values-th/strings.xml b/packages/SettingsLib/res/values-th/strings.xml
index 649d8de0f816..fd4022be2495 100644
--- a/packages/SettingsLib/res/values-th/strings.xml
+++ b/packages/SettingsLib/res/values-th/strings.xml
@@ -601,7 +601,7 @@
<string name="guest_reset_and_restart_dialog_title" msgid="3396657008451616041">"รีเซ็ตเซสชันผู้ใช้ชั่วคราวไหม"</string>
<string name="guest_reset_and_restart_dialog_message" msgid="2764425635305200790">"การดำเนินการนี้จะเริ่มเซสชันผู้ใช้ชั่วคราวใหม่ และจะลบแอปและข้อมูลทั้งหมดจากเซสชันปัจจุบัน"</string>
<string name="guest_exit_dialog_title" msgid="1846494656849381804">"ออกจากโหมดผู้ใช้ชั่วคราวไหม"</string>
- <string name="guest_exit_dialog_message" msgid="1743218864242719783">"การดำเนินการนี้จะลบแอปและข้อมูลออกจากเซสชันผู้มาเยือนในปัจจุบัน"</string>
+ <string name="guest_exit_dialog_message" msgid="1743218864242719783">"การดำเนินการนี้จะลบแอปและข้อมูลออกจากเซสชันผู้ใช้ชั่วคราวในปัจจุบัน"</string>
<string name="guest_exit_dialog_button" msgid="1736401897067442044">"ออก"</string>
<string name="guest_exit_dialog_title_non_ephemeral" msgid="7675327443743162986">"บันทึกกิจกรรมของผู้ใช้ชั่วคราวไหม"</string>
<string name="guest_exit_dialog_message_non_ephemeral" msgid="223385323235719442">"คุณสามารถบันทึกกิจกรรมจากเซสชันปัจจุบันหรือจะลบแอปและข้อมูลทั้งหมดก็ได้"</string>
@@ -667,9 +667,6 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"เปิดหน้าจอ"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"อนุญาตให้เปิดหน้าจอ"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"อนุญาตให้แอปเปิดหน้าจอ หากอนุญาต แอปอาจเปิดหน้าจอได้ทุกเมื่อแม้คุณไม่ได้ระบุเจตนาที่ชัดแจ้ง"</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"สแกนคิวอาร์โค้ด"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"ถือให้คิวอาร์โค้ดอยู่กลางช่องด้านล่างเพื่อเริ่มฟัง"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"คิวอาร์โค้ดมีรูปแบบไม่ถูกต้อง"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"หยุดการออกอากาศ <xliff:g id="APP_NAME">%1$s</xliff:g> ไหม"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"หากคุณออกอากาศ <xliff:g id="SWITCHAPP">%1$s</xliff:g> หรือเปลี่ยนแปลงเอาต์พุต การออกอากาศในปัจจุบันจะหยุดลง"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"ออกอากาศ <xliff:g id="SWITCHAPP">%1$s</xliff:g>"</string>
diff --git a/packages/SettingsLib/res/values-tl/strings.xml b/packages/SettingsLib/res/values-tl/strings.xml
index bb8ba5222f39..137a43980989 100644
--- a/packages/SettingsLib/res/values-tl/strings.xml
+++ b/packages/SettingsLib/res/values-tl/strings.xml
@@ -570,7 +570,7 @@
<string name="user_add_profile_item_title" msgid="3111051717414643029">"Pinaghihigpitang profile"</string>
<string name="user_add_user_title" msgid="5457079143694924885">"Magdagdag ng bagong user?"</string>
<string name="user_add_user_message_long" msgid="1527434966294733380">"Puwede mong ibahagi ang device na ito sa ibang tao sa pamamagitan ng paggawa ng mga karagdagang user. May sariling espasyo ang bawat user na maaari nilang i-customize gamit ang mga app, wallpaper, at iba pa. Puwede ring isaayos ng mga user ang mga setting ng device tulad ng Wi‑Fi na nakakaapekto sa lahat.\n\nKapag nagdagdag ka ng bagong user, kailangang i-set up ng taong iyon ang kanyang espasyo.\n\nMaaaring mag-update ng mga app ang sinumang user para sa lahat ng iba pang user. Maaaring hindi malipat sa bagong user ang mga setting at serbisyo sa pagiging naa-access."</string>
- <string name="user_add_user_message_short" msgid="3295959985795716166">"Kapag nagdagdag ka ng bagong user, kailangang i-set up ng taong iyon ang kanyang espasyo.\n\nAng sinumang user ay maaaring mag-update ng mga app para sa lahat ng iba pang user."</string>
+ <string name="user_add_user_message_short" msgid="3295959985795716166">"Kapag nagdagdag ka ng bagong user, kailangang i-set up ng taong iyon ang kanyang espasyo.\n\nAng sinumang user ay puwedeng mag-update ng mga app para sa lahat ng iba pang user."</string>
<string name="user_setup_dialog_title" msgid="8037342066381939995">"I-set up ang user ngayon?"</string>
<string name="user_setup_dialog_message" msgid="269931619868102841">"Tiyaking available ang tao na kunin ang device at i-set up ang kanyang space"</string>
<string name="user_setup_profile_dialog_message" msgid="4788197052296962620">"Mag-set up ng profile ngayon?"</string>
@@ -667,9 +667,6 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"I-on ang screen"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Payagan ang pag-on sa screen"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Nagpapahintulot sa app na i-on ang screen. Kung papayagan, puwedeng i-on ng app ang screen anumang oras nang wala ng iyong malinaw na intent."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"I-scan ang QR code"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Para simulang makinig, igitna ang QR code sa ibaba"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"Hindi valid na format ang QR code"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"Ihinto ang pag-broadcast ng <xliff:g id="APP_NAME">%1$s</xliff:g>?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"Kung magbo-broadcast ka ng <xliff:g id="SWITCHAPP">%1$s</xliff:g> o babaguhin mo ang output, hihinto ang iyong kasalukuyang broadcast"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"I-broadcast ang <xliff:g id="SWITCHAPP">%1$s</xliff:g>"</string>
diff --git a/packages/SettingsLib/res/values-tr/strings.xml b/packages/SettingsLib/res/values-tr/strings.xml
index 3cde80416779..f8b230498733 100644
--- a/packages/SettingsLib/res/values-tr/strings.xml
+++ b/packages/SettingsLib/res/values-tr/strings.xml
@@ -569,7 +569,7 @@
<string name="user_add_user_item_title" msgid="2394272381086965029">"Kullanıcı"</string>
<string name="user_add_profile_item_title" msgid="3111051717414643029">"Kısıtlı profil"</string>
<string name="user_add_user_title" msgid="5457079143694924885">"Yeni kullanıcı eklensin mi?"</string>
- <string name="user_add_user_message_long" msgid="1527434966294733380">"Ek kullanıcılar oluşturarak bu cihazı başkalarıyla paylaşabilirsiniz. Her kullanıcının uygulamalarla, duvar kağıdıyla ve başka ayarlarla özelleştirebileceği kendi alanı olur. Kullanıcılar ayrıca kablosuz ağ gibi herkesi etkileyen cihaz ayarlarını değiştirebilirler.\n\nYeni bir kullanıcı eklediğinizde, ilgili kişinin kendi alanını ayarlaması gerekir.\n\nHer kullanıcı diğer tüm kullanıcılar için uygulamaları güncelleyebilir."</string>
+ <string name="user_add_user_message_long" msgid="1527434966294733380">"Ek kullanıcılar oluşturarak bu cihazı başkalarıyla paylaşabilirsiniz. Her kullanıcının uygulamalarla, duvar kağıdıyla ve başka ayarlarla özelleştirebileceği kendi alanı olur. Kullanıcılar ayrıca kablosuz ağ gibi herkesi etkileyen cihaz ayarlarını değiştirebilirler.\n\nYeni bir kullanıcı eklediğinizde, ilgili kişinin kendi alanını ayarlaması gerekir.\n\nHer kullanıcı diğer tüm kullanıcılar için uygulamaları güncelleyebilir. Erişilebilirlik ayarları ve hizmetleri yeni kullanıcıya aktarılamayabilir."</string>
<string name="user_add_user_message_short" msgid="3295959985795716166">"Yeni bir kullanıcı eklediğinizde, bu kişinin kendi alanını ayarlaması gerekir.\n\nHerhangi bir kullanıcı, diğer tüm kullanıcılar için uygulamaları güncelleyebilir."</string>
<string name="user_setup_dialog_title" msgid="8037342066381939995">"Kullanıcı şimdi ayarlansın mı?"</string>
<string name="user_setup_dialog_message" msgid="269931619868102841">"İlgili kişinin cihazı almak ve kendi alanını ayarlamak için müsait olduğundan emin olun"</string>
@@ -667,17 +667,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Ekranı aç"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Ekranı açmaya izin ver"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Bir uygulamanın ekranı açmasına izin verin. İzin verildiğinde, uygulama sizin belirgin niyetiniz olmadan istediği zaman ekranı açabilir."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"QR kodunu tara"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Dinlemeye başlamak için aşağıdaki QR kodunu ortalayın"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"QR kodu geçerli bir biçim değil"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"<xliff:g id="APP_NAME">%1$s</xliff:g> uygulamasında anons durdurulsun mu?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"<xliff:g id="SWITCHAPP">%1$s</xliff:g> uygulamasında anons yapar veya çıkışı değiştirirseniz mevcut anonsunuz duraklatılır"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"<xliff:g id="SWITCHAPP">%1$s</xliff:g> uygulamasında anons yapın"</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"Çıkışı değiştirme"</string>
- <!-- no translation found for back_navigation_animation (8105467568421689484) -->
- <skip />
- <!-- no translation found for back_navigation_animation_summary (741292224121599456) -->
- <skip />
- <!-- no translation found for back_navigation_animation_dialog (8696966520944625596) -->
- <skip />
+ <string name="back_navigation_animation" msgid="8105467568421689484">"Tahmine dayalı geri hareketi animasyonları"</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"Tahmine dayalı geri hareketi için sistem animasyonlarını etkinleştirin"</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"Bu ayar, tahmine dayalı hareket animasyonu için sistem animasyonlarını etkinleştirir. Her uygulamanın manifest dosyasında enableOnBackInvokedCallback\'in doğru değerine ayarlanması gerekir."</string>
</resources>
diff --git a/packages/SettingsLib/res/values-uk/strings.xml b/packages/SettingsLib/res/values-uk/strings.xml
index 1377667c79bd..9666bd6604f8 100644
--- a/packages/SettingsLib/res/values-uk/strings.xml
+++ b/packages/SettingsLib/res/values-uk/strings.xml
@@ -610,7 +610,7 @@
<string name="guest_exit_button" msgid="5774985819191803960">"Вийти з режиму гостя"</string>
<string name="guest_reset_button" msgid="2515069346223503479">"Скинути сеанс у режимі гостя"</string>
<string name="guest_exit_quick_settings_button" msgid="1912362095913765471">"Вийти з режиму гостя"</string>
- <string name="guest_notification_ephemeral" msgid="7263252466950923871">"Під час виходу буде видалено всі дії"</string>
+ <string name="guest_notification_ephemeral" msgid="7263252466950923871">"Під час виходу буде видалено історію всіх дій"</string>
<string name="guest_notification_non_ephemeral" msgid="6843799963012259330">"Під час виходу можна зберегти або видалити ваші дії"</string>
<string name="guest_notification_non_ephemeral_non_first_login" msgid="8009307983766934876">"Можна скинути історію сеансу просто зараз або видалити чи зберегти її під час виходу."</string>
<string name="user_image_take_photo" msgid="467512954561638530">"Зробити фотографію"</string>
@@ -667,17 +667,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Увімкнення екрана"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Дозволити ввімкнення екрана"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Дозвольте додатку вмикати екран. Якщо ви надасте цей дозвіл, додаток зможе будь-коли вмикати екран пристрою навіть без вашого явного наміру."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"Сканування QR-коду"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Щоб почати слухати аудіо, наведіть камеру на QR-код нижче"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"Недійсний формат QR-коду"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"Зупинити трансляцію з додатка <xliff:g id="APP_NAME">%1$s</xliff:g>?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"Якщо ви зміните додаток (<xliff:g id="SWITCHAPP">%1$s</xliff:g>) або аудіовихід, поточну трансляцію буде припинено"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"Змінити додаток для трансляції на <xliff:g id="SWITCHAPP">%1$s</xliff:g>"</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"Змінити аудіовихід"</string>
- <!-- no translation found for back_navigation_animation (8105467568421689484) -->
- <skip />
- <!-- no translation found for back_navigation_animation_summary (741292224121599456) -->
- <skip />
- <!-- no translation found for back_navigation_animation_dialog (8696966520944625596) -->
- <skip />
+ <string name="back_navigation_animation" msgid="8105467568421689484">"Анімації з підказками для жесту \"Назад\""</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"Увімкніть системну анімацію з підказками для жесту \"Назад\"."</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"Якщо вибрати це налаштування, для жесту \"Назад\" відображатиметься анімація з підказками. У файлі маніфесту атрибуту enableOnBackInvokedCallback додатка потрібно присвоїти значення true."</string>
</resources>
diff --git a/packages/SettingsLib/res/values-ur/strings.xml b/packages/SettingsLib/res/values-ur/strings.xml
index 7a0dcbbc73cc..c8f396ea386a 100644
--- a/packages/SettingsLib/res/values-ur/strings.xml
+++ b/packages/SettingsLib/res/values-ur/strings.xml
@@ -667,9 +667,6 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"اسکرین آن کریں"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"اسکرین آن کرنے کی اجازت دیں"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"ایپ کو اسکرین آن کرنے کی اجازت دیں۔ اگر اجازت دی گئی تو ایپ آپ کے واضح مقصد کے بغیر کسی بھی وقت اسکرین کو آن کر سکتی ہے۔"</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"‏QR کوڈ اسکین کریں"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"‏سننا شروع کرنے کے لیے، نیچے کے QR کوڈ کو سینٹر میں رکھیں"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"‏QR کوڈ درست فارمیٹ نہیں ہے"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"<xliff:g id="APP_NAME">%1$s</xliff:g> براڈکاسٹنگ روکیں؟"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"اگر آپ <xliff:g id="SWITCHAPP">%1$s</xliff:g> براڈکاسٹ کرتے ہیں یا آؤٹ پٹ کو تبدیل کرتے ہیں تو آپ کا موجودہ براڈکاسٹ رک جائے گا"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"<xliff:g id="SWITCHAPP">%1$s</xliff:g> پر براڈکاسٹ کریں"</string>
diff --git a/packages/SettingsLib/res/values-uz/strings.xml b/packages/SettingsLib/res/values-uz/strings.xml
index 92f21df6942b..6c4763ef20ee 100644
--- a/packages/SettingsLib/res/values-uz/strings.xml
+++ b/packages/SettingsLib/res/values-uz/strings.xml
@@ -121,7 +121,7 @@
<string name="bluetooth_profile_pbap_summary" msgid="2955819694801952056">"Kontaktlarni ulashish uchun ishlatilsin"</string>
<string name="bluetooth_profile_pan_nap" msgid="7871974753822470050">"Internet aloqasi ulashmasi"</string>
<string name="bluetooth_profile_map" msgid="8907204701162107271">"SMS xabarlari"</string>
- <string name="bluetooth_profile_sap" msgid="8304170950447934386">"SIM-kartaga kirish"</string>
+ <string name="bluetooth_profile_sap" msgid="8304170950447934386">"SIM kartaga kirish"</string>
<string name="bluetooth_profile_a2dp_high_quality" msgid="4739440941324792775">"HD audio: <xliff:g id="CODEC_NAME">%1$s</xliff:g>"</string>
<string name="bluetooth_profile_a2dp_high_quality_unknown_codec" msgid="2477639096903834374">"HD audio"</string>
<string name="bluetooth_profile_hearing_aid" msgid="58154575573984914">"Eshitish apparatlari"</string>
@@ -610,7 +610,7 @@
<string name="guest_exit_button" msgid="5774985819191803960">"Mehmon rejimidan chiqish"</string>
<string name="guest_reset_button" msgid="2515069346223503479">"Mehmon seansini tiklash"</string>
<string name="guest_exit_quick_settings_button" msgid="1912362095913765471">"Mehmon rejimidan chiqish"</string>
- <string name="guest_notification_ephemeral" msgid="7263252466950923871">"Chiqish vaqtida faoliyat butunlay tozalanadi"</string>
+ <string name="guest_notification_ephemeral" msgid="7263252466950923871">"Chiqishda faolliklar tarixi tozalab tashlanadi"</string>
<string name="guest_notification_non_ephemeral" msgid="6843799963012259330">"Chiqish vaqtida faoliyatni saqlash yoki tozalash mumkin"</string>
<string name="guest_notification_non_ephemeral_non_first_login" msgid="8009307983766934876">"Faoliyat hozir tozalanib tiklanishi yoki chiqish vaqtida saqlanishi yoki tozalanishi mumkin"</string>
<string name="user_image_take_photo" msgid="467512954561638530">"Suratga olish"</string>
@@ -667,9 +667,6 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Ekranni yoqish"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Ekranni yoqishga ruxsat"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Ilovaga ekranni yoqishga ruxsat berish. Ruxsat berilsa, ilova istalgan vaqt ruxsatingizsiz ekranni yoqishi mumkin."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"QR kodni skanerlash"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Tinglashni boshlash uchun quyidagi QR kodni markazga joylang"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"QR xato formatda"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"<xliff:g id="APP_NAME">%1$s</xliff:g> ilovasiga translatsiya toʻxtatilsinmi?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"Agar <xliff:g id="SWITCHAPP">%1$s</xliff:g> ilovasiga translatsiya qilsangiz yoki ovoz chiqishini oʻzgartirsangiz, joriy translatsiya toʻxtab qoladi"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"<xliff:g id="SWITCHAPP">%1$s</xliff:g> ilovasiga translatsiya"</string>
diff --git a/packages/SettingsLib/res/values-vi/strings.xml b/packages/SettingsLib/res/values-vi/strings.xml
index 2fa22b4fbc42..6be9b8a161c9 100644
--- a/packages/SettingsLib/res/values-vi/strings.xml
+++ b/packages/SettingsLib/res/values-vi/strings.xml
@@ -667,9 +667,6 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Bật màn hình"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Cho phép bật màn hình"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Cho phép ứng dụng bật màn hình. Nếu được phép, ứng dụng có thể bật màn hình bất kỳ lúc nào kể cả khi bạn không có ý định như vậy."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"Quét mã QR"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Để bắt đầu nghe, hãy hướng máy ảnh vào mã QR bên dưới và căn sao cho mã nằm chính giữa"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"Định dạng của mã QR là không hợp lệ"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"Dừng phát <xliff:g id="APP_NAME">%1$s</xliff:g>?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"Nếu bạn phát <xliff:g id="SWITCHAPP">%1$s</xliff:g> hoặc thay đổi đầu ra, phiên truyền phát hiện tại sẽ dừng"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"Phát <xliff:g id="SWITCHAPP">%1$s</xliff:g>"</string>
diff --git a/packages/SettingsLib/res/values-zh-rCN/strings.xml b/packages/SettingsLib/res/values-zh-rCN/strings.xml
index e9227fd2a8e0..6f678f4036e0 100644
--- a/packages/SettingsLib/res/values-zh-rCN/strings.xml
+++ b/packages/SettingsLib/res/values-zh-rCN/strings.xml
@@ -570,7 +570,7 @@
<string name="user_add_profile_item_title" msgid="3111051717414643029">"受限个人资料"</string>
<string name="user_add_user_title" msgid="5457079143694924885">"要添加新用户吗?"</string>
<string name="user_add_user_message_long" msgid="1527434966294733380">"创建新用户后,您就能够与其他人共用此设备。每位用户都有自己的专属空间,而且在自己的个人空间内还可以自行安装自己想要的应用、设置壁纸等。此外,用户还可以调整会影响所有用户的设备设置(例如 WLAN 设置)。\n\n当您添加新用户后,该用户需要自行设置个人空间。\n\n任何用户都可以为所有其他用户更新应用。无障碍功能设置和服务可能无法转移给新用户。"</string>
- <string name="user_add_user_message_short" msgid="3295959985795716166">"您添加新用户后,该用户必须设置自己的空间。\n\n任何用户均可为其他所有用户更新应用。"</string>
+ <string name="user_add_user_message_short" msgid="3295959985795716166">"当您添加新用户后,该用户需要自行设置个人空间。\n\n任何用户都可以为所有其他用户更新应用。"</string>
<string name="user_setup_dialog_title" msgid="8037342066381939995">"要现在设置该用户吗?"</string>
<string name="user_setup_dialog_message" msgid="269931619868102841">"请让相应用户操作设备并设置他们自己的空间。"</string>
<string name="user_setup_profile_dialog_message" msgid="4788197052296962620">"要立即设置个人资料吗?"</string>
@@ -610,7 +610,7 @@
<string name="guest_exit_button" msgid="5774985819191803960">"退出访客模式"</string>
<string name="guest_reset_button" msgid="2515069346223503479">"重置访客会话"</string>
<string name="guest_exit_quick_settings_button" msgid="1912362095913765471">"退出访客模式"</string>
- <string name="guest_notification_ephemeral" msgid="7263252466950923871">"系统会在退出时删除所有活动记录"</string>
+ <string name="guest_notification_ephemeral" msgid="7263252466950923871">"退出时所有活动记录都将被删除"</string>
<string name="guest_notification_non_ephemeral" msgid="6843799963012259330">"您可以在退出时保存或删除您的活动记录"</string>
<string name="guest_notification_non_ephemeral_non_first_login" msgid="8009307983766934876">"请立即重置以删除会话活动记录;或者,您也可以在退出时保存或删除活动记录"</string>
<string name="user_image_take_photo" msgid="467512954561638530">"拍摄照片"</string>
@@ -667,9 +667,6 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"开启屏幕"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"允许开启屏幕"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"允许应用开启屏幕。如获授权,该应用便可在您未明确表达意愿的情况下随时开启屏幕。"</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"扫描二维码"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"将取景框对准二维码,即可开始收听"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"二维码的格式无效"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"要停止广播“<xliff:g id="APP_NAME">%1$s</xliff:g>”的内容吗?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"如果广播“<xliff:g id="SWITCHAPP">%1$s</xliff:g>”的内容或更改输出来源,当前的广播就会停止"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"广播“<xliff:g id="SWITCHAPP">%1$s</xliff:g>”的内容"</string>
diff --git a/packages/SettingsLib/res/values-zh-rHK/strings.xml b/packages/SettingsLib/res/values-zh-rHK/strings.xml
index fae79cb61a51..03d4559b1949 100644
--- a/packages/SettingsLib/res/values-zh-rHK/strings.xml
+++ b/packages/SettingsLib/res/values-zh-rHK/strings.xml
@@ -667,17 +667,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"開啟螢幕"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"允許開啟螢幕"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"允許應用程式開啟螢幕。應用程式獲授權後,可在您未有明確表明意圖的情況下隨時開啟螢幕。"</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"掃瞄 QR 碼"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"如要開始收聽,請將掃瞄器對準下方的 QR 碼"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"QR 碼格式無效"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"要停止廣播「<xliff:g id="APP_NAME">%1$s</xliff:g>」的內容嗎?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"如要廣播「<xliff:g id="SWITCHAPP">%1$s</xliff:g>」的內容或變更輸出來源,系統就會停止廣播目前的內容"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"廣播「<xliff:g id="SWITCHAPP">%1$s</xliff:g>」的內容"</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"變更輸出來源"</string>
- <!-- no translation found for back_navigation_animation (8105467568421689484) -->
- <skip />
- <!-- no translation found for back_navigation_animation_summary (741292224121599456) -->
- <skip />
- <!-- no translation found for back_navigation_animation_dialog (8696966520944625596) -->
- <skip />
+ <string name="back_navigation_animation" msgid="8105467568421689484">"預測返回手勢動畫"</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"為預測返回手勢啟用系統動畫。"</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"此設定會啟用系統動畫作為預測手勢動畫。這必須在資訊清單檔案中將個別應用程式的 enableOnBackInvokedCallback 設定為 true。"</string>
</resources>
diff --git a/packages/SettingsLib/res/values-zh-rTW/strings.xml b/packages/SettingsLib/res/values-zh-rTW/strings.xml
index 19ab135b5c68..16baf82435a8 100644
--- a/packages/SettingsLib/res/values-zh-rTW/strings.xml
+++ b/packages/SettingsLib/res/values-zh-rTW/strings.xml
@@ -568,7 +568,7 @@
<string name="user_add_profile_item_summary" msgid="5418602404308968028">"你可以限制他人透過你的帳戶存取應用程式和內容"</string>
<string name="user_add_user_item_title" msgid="2394272381086965029">"使用者"</string>
<string name="user_add_profile_item_title" msgid="3111051717414643029">"設有限制的個人資料"</string>
- <string name="user_add_user_title" msgid="5457079143694924885">"新增使用者?"</string>
+ <string name="user_add_user_title" msgid="5457079143694924885">"要新增使用者嗎?"</string>
<string name="user_add_user_message_long" msgid="1527434966294733380">"你可以建立其他使用者,藉此與他人共用這個裝置。每位使用者都有自己的專屬空間,並可使用應用程式、桌布等項目自訂個人空間。此外,使用者也可以調整會影響所有人的裝置設定,例如 Wi‑Fi 設定。\n\n新增的使用者需要自行設定個人空間。\n\n任何使用者都可以為所有其他使用者更新應用程式。無障礙設定和服務可能無法轉移到新的使用者。"</string>
<string name="user_add_user_message_short" msgid="3295959985795716166">"新增的使用者需要自行設定個人空間。\n\n任何使用者皆可為其他所有使用者更新應用程式。"</string>
<string name="user_setup_dialog_title" msgid="8037342066381939995">"立即設定使用者?"</string>
@@ -667,17 +667,11 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"開啟螢幕"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"允許開啟螢幕"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"允許應用程式開啟螢幕。如果授予這項權限,即使你未明確指示,應用程式也隨時可能會開啟螢幕。"</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"掃描 QR 圖碼"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"如要開始收聽,請將掃描器對準下方的 QR 圖碼"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"QR 圖碼格式無效"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"要停止播送「<xliff:g id="APP_NAME">%1$s</xliff:g>」的內容嗎?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"如果播送「<xliff:g id="SWITCHAPP">%1$s</xliff:g>」的內容或變更輸出來源,系統就會停止播送目前的內容"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"播送「<xliff:g id="SWITCHAPP">%1$s</xliff:g>」的內容"</string>
<string name="bt_le_audio_broadcast_dialog_different_output" msgid="2638402023060391333">"變更輸出來源"</string>
- <!-- no translation found for back_navigation_animation (8105467568421689484) -->
- <skip />
- <!-- no translation found for back_navigation_animation_summary (741292224121599456) -->
- <skip />
- <!-- no translation found for back_navigation_animation_dialog (8696966520944625596) -->
- <skip />
+ <string name="back_navigation_animation" msgid="8105467568421689484">"預測返回操作動畫"</string>
+ <string name="back_navigation_animation_summary" msgid="741292224121599456">"為預測返回操作啟用系統動畫。"</string>
+ <string name="back_navigation_animation_dialog" msgid="8696966520944625596">"這項設定會啟用系統動畫做為預測手勢動畫。這必須在資訊清單檔案中將個別應用程式的 enableOnBackInvokedCallback 設為 true。"</string>
</resources>
diff --git a/packages/SettingsLib/res/values-zu/strings.xml b/packages/SettingsLib/res/values-zu/strings.xml
index 1f29525bda71..e2fab129f354 100644
--- a/packages/SettingsLib/res/values-zu/strings.xml
+++ b/packages/SettingsLib/res/values-zu/strings.xml
@@ -667,9 +667,6 @@
<string name="turn_screen_on_title" msgid="3266937298097573424">"Vula isikrini"</string>
<string name="allow_turn_screen_on" msgid="6194845766392742639">"Vumela ukuvula isikrini"</string>
<string name="allow_turn_screen_on_description" msgid="43834403291575164">"Vumela i-app ivule isikrini. Uma kuvunyiwe, i-app ingavula isikrini noma nini ngaphandle kwenhloso yakho esobala."</string>
- <string name="bt_le_audio_scan_qr_code" msgid="3521809854780392679">"Skena ikhodi ye-QR"</string>
- <string name="bt_le_audio_scan_qr_code_scanner" msgid="4679500020630341107">"Ukuze uqale ukulalela, beka ikhodi ye-QR ngezansi"</string>
- <string name="bt_le_audio_qr_code_is_not_valid_format" msgid="6092191081849434734">"Ikhodi ye-QR ayiyona ifomethi evumelekile"</string>
<string name="bt_le_audio_broadcast_dialog_title" msgid="5392738488989777074">"Misa ukusakaza i-<xliff:g id="APP_NAME">%1$s</xliff:g>?"</string>
<string name="bt_le_audio_broadcast_dialog_sub_title" msgid="268234802198852753">"Uma usakaza i-<xliff:g id="SWITCHAPP">%1$s</xliff:g> noma ushintsha okuphumayo, ukusakaza kwakho kwamanje kuzoma"</string>
<string name="bt_le_audio_broadcast_dialog_switch_app" msgid="5749813313369517812">"Sakaza i-<xliff:g id="SWITCHAPP">%1$s</xliff:g>"</string>
diff --git a/packages/SettingsLib/res/values/dimens.xml b/packages/SettingsLib/res/values/dimens.xml
index cbc79d2d5d93..226b119ebb76 100644
--- a/packages/SettingsLib/res/values/dimens.xml
+++ b/packages/SettingsLib/res/values/dimens.xml
@@ -115,12 +115,6 @@
<!-- Minimum density scale. This is available on all devices. -->
<fraction name="display_density_min_scale">85%</fraction>
- <!-- QR code picture size -->
- <dimen name="qrcode_preview_size">360dp</dimen>
- <dimen name="qrcode_preview_margin">40dp</dimen>
- <dimen name="qrcode_preview_radius">30dp</dimen>
- <dimen name="qrcode_icon_size">27dp</dimen>
-
<!-- Broadcast dialog -->
<dimen name="broadcast_dialog_title_img_margin_top">18dp</dimen>
<dimen name="broadcast_dialog_title_text_size">24sp</dimen>
diff --git a/packages/SettingsLib/res/values/strings.xml b/packages/SettingsLib/res/values/strings.xml
index d8990af75a8b..4bf4f4d46c28 100644
--- a/packages/SettingsLib/res/values/strings.xml
+++ b/packages/SettingsLib/res/values/strings.xml
@@ -1627,13 +1627,6 @@
<!-- Description for a setting which controls whether an app can turn the screen on [CHAR LIMIT=NONE] -->
<string name="allow_turn_screen_on_description">Allow an app to turn the screen on. If granted, the app may turn on the screen at any time without your explicit intent.</string>
- <!-- [CHAR LIMIT=NONE] Le audio QR code scanner title -->
- <string name="bt_le_audio_scan_qr_code">Scan QR code</string>
- <!-- [CHAR LIMIT=NONE] Le audio QR code scanner sub-title -->
- <string name="bt_le_audio_scan_qr_code_scanner">To start listening, center the QR code below</string>
- <!-- [CHAR LIMIT=NONE] Hint for QR code process failure -->
- <string name="bt_le_audio_qr_code_is_not_valid_format">QR code isn\u0027t a valid format</string>
-
<!-- [CHAR LIMIT=NONE] Le audio broadcast dialog, title -->
<string name="bt_le_audio_broadcast_dialog_title">Stop broadcasting <xliff:g id="app_name" example="App Name 1">%1$s</xliff:g>?</string>
<!-- [CHAR LIMIT=NONE] Le audio broadcast dialog, sub-title -->
diff --git a/packages/SettingsLib/res/values/styles.xml b/packages/SettingsLib/res/values/styles.xml
index 32345150531d..5237b4fa1c3d 100644
--- a/packages/SettingsLib/res/values/styles.xml
+++ b/packages/SettingsLib/res/values/styles.xml
@@ -33,13 +33,6 @@
<item name="android:textColor">?android:attr/colorError</item>
</style>
- <style name="QrCodeScanner">
- <item name="android:fontFamily">@*android:string/config_headlineFontFamily</item>
- <item name="android:textSize">16sp</item>
- <item name="android:textColor">?android:attr/textColorPrimary</item>
- <item name="android:textDirection">locale</item>
- </style>
-
<style name="BroadcastDialogTitleStyle">
<item name="android:textAppearance">@style/TextAppearanceBroadcastDialogTitle</item>
<item name="android:layout_marginStart">@dimen/broadcast_dialog_title_text_margin</item>
diff --git a/packages/SettingsLib/src/com/android/settingslib/bluetooth/BluetoothUtils.java b/packages/SettingsLib/src/com/android/settingslib/bluetooth/BluetoothUtils.java
index c9af4d53f9a8..fea7475fc087 100644
--- a/packages/SettingsLib/src/com/android/settingslib/bluetooth/BluetoothUtils.java
+++ b/packages/SettingsLib/src/com/android/settingslib/bluetooth/BluetoothUtils.java
@@ -30,6 +30,9 @@ import com.android.settingslib.widget.AdaptiveOutlineDrawable;
import java.io.IOException;
import java.util.List;
+import java.util.Locale;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
public class BluetoothUtils {
private static final String TAG = "BluetoothUtils";
@@ -39,6 +42,8 @@ public class BluetoothUtils {
public static final int META_INT_ERROR = -1;
public static final String BT_ADVANCED_HEADER_ENABLED = "bt_advanced_header_enabled";
+ private static final int METADATA_FAST_PAIR_CUSTOMIZED_FIELDS = 25;
+ private static final String KEY_HEARABLE_CONTROL_SLICE = "HEARABLE_CONTROL_SLICE_WITH_WIDTH";
private static ErrorListener sErrorListener;
@@ -384,8 +389,43 @@ public class BluetoothUtils {
return Uri.parse(data);
}
+ /**
+ * Get URI Bluetooth metadata for extra control
+ *
+ * @param bluetoothDevice the BluetoothDevice to get metadata
+ * @return the URI metadata
+ */
+ public static String getControlUriMetaData(BluetoothDevice bluetoothDevice) {
+ String data = getStringMetaData(bluetoothDevice, METADATA_FAST_PAIR_CUSTOMIZED_FIELDS);
+ return extraTagValue(KEY_HEARABLE_CONTROL_SLICE, data);
+ }
+
@SuppressLint("NewApi") // Hidden API made public
private static boolean doesClassMatch(BluetoothClass btClass, int classId) {
return btClass.doesClassMatch(classId);
}
+
+ private static String extraTagValue(String tag, String metaData) {
+ if (TextUtils.isEmpty(metaData)) {
+ return null;
+ }
+ Pattern pattern = Pattern.compile(generateExpressionWithTag(tag, "(.*?)"));
+ Matcher matcher = pattern.matcher(metaData);
+ if (matcher.find()) {
+ return matcher.group(1);
+ }
+ return null;
+ }
+
+ private static String getTagStart(String tag) {
+ return String.format(Locale.ENGLISH, "<%s>", tag);
+ }
+
+ private static String getTagEnd(String tag) {
+ return String.format(Locale.ENGLISH, "</%s>", tag);
+ }
+
+ private static String generateExpressionWithTag(String tag, String value) {
+ return getTagStart(tag) + value + getTagEnd(tag);
+ }
}
diff --git a/packages/SettingsLib/src/com/android/settingslib/bluetooth/CachedBluetoothDevice.java b/packages/SettingsLib/src/com/android/settingslib/bluetooth/CachedBluetoothDevice.java
index 6919cf237853..4229b6881f73 100644
--- a/packages/SettingsLib/src/com/android/settingslib/bluetooth/CachedBluetoothDevice.java
+++ b/packages/SettingsLib/src/com/android/settingslib/bluetooth/CachedBluetoothDevice.java
@@ -77,6 +77,8 @@ public class CachedBluetoothDevice implements Comparable<CachedBluetoothDevice>
private final LocalBluetoothProfileManager mProfileManager;
private final Object mProfileLock = new Object();
BluetoothDevice mDevice;
+ private int mDeviceSide;
+ private int mDeviceMode;
private long mHiSyncId;
private int mGroupId;
// Need this since there is no method for getting RSSI
@@ -335,6 +337,22 @@ public class CachedBluetoothDevice implements Comparable<CachedBluetoothDevice>
connectDevice();
}
+ public int getDeviceSide() {
+ return mDeviceSide;
+ }
+
+ public void setDeviceSide(int side) {
+ mDeviceSide = side;
+ }
+
+ public int getDeviceMode() {
+ return mDeviceMode;
+ }
+
+ public void setDeviceMode(int mode) {
+ mDeviceMode = mode;
+ }
+
public long getHiSyncId() {
return mHiSyncId;
}
@@ -1111,7 +1129,8 @@ public class CachedBluetoothDevice implements Comparable<CachedBluetoothDevice>
stringRes = R.string.bluetooth_battery_level;
}
- // Set active string in following device connected situation.
+ // Set active string in following device connected situation, also show battery
+ // information if they have.
// 1. Hearing Aid device active.
// 2. Headset device active with in-calling state.
// 3. A2DP device active without in-calling state.
@@ -1130,6 +1149,24 @@ public class CachedBluetoothDevice implements Comparable<CachedBluetoothDevice>
stringRes = R.string.bluetooth_active_no_battery_level;
}
}
+
+ // Try to show left/right information if can not get it from battery for hearing
+ // aids specifically.
+ if (mIsActiveDeviceHearingAid
+ && stringRes == R.string.bluetooth_active_no_battery_level) {
+ final CachedBluetoothDevice subDevice = getSubDevice();
+ if (subDevice != null && subDevice.isConnected()) {
+ stringRes = R.string.bluetooth_hearing_aid_left_and_right_active;
+ } else {
+ if (mDeviceSide == HearingAidProfile.DeviceSide.SIDE_LEFT) {
+ stringRes = R.string.bluetooth_hearing_aid_left_active;
+ } else if (mDeviceSide == HearingAidProfile.DeviceSide.SIDE_RIGHT) {
+ stringRes = R.string.bluetooth_hearing_aid_right_active;
+ } else {
+ stringRes = R.string.bluetooth_active_no_battery_level;
+ }
+ }
+ }
}
}
diff --git a/packages/SettingsLib/src/com/android/settingslib/bluetooth/HearingAidProfile.java b/packages/SettingsLib/src/com/android/settingslib/bluetooth/HearingAidProfile.java
index 6f2d4decf033..a491455da963 100644
--- a/packages/SettingsLib/src/com/android/settingslib/bluetooth/HearingAidProfile.java
+++ b/packages/SettingsLib/src/com/android/settingslib/bluetooth/HearingAidProfile.java
@@ -29,13 +29,48 @@ import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.util.Log;
+import androidx.annotation.IntDef;
+import androidx.annotation.NonNull;
+
import com.android.settingslib.R;
import com.android.settingslib.Utils;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
public class HearingAidProfile implements LocalBluetoothProfile {
+ @Retention(RetentionPolicy.SOURCE)
+ @IntDef({
+ DeviceSide.SIDE_INVALID,
+ DeviceSide.SIDE_LEFT,
+ DeviceSide.SIDE_RIGHT
+ })
+
+ /** Side definition for hearing aids. See {@link BluetoothHearingAid}. */
+ public @interface DeviceSide {
+ int SIDE_INVALID = -1;
+ int SIDE_LEFT = 0;
+ int SIDE_RIGHT = 1;
+ }
+
+ @Retention(RetentionPolicy.SOURCE)
+ @IntDef({
+ DeviceMode.MODE_INVALID,
+ DeviceMode.MODE_MONAURAL,
+ DeviceMode.MODE_BINAURAL
+ })
+
+ /** Mode definition for hearing aids. See {@link BluetoothHearingAid}. */
+ public @interface DeviceMode {
+ int MODE_INVALID = -1;
+ int MODE_MONAURAL = 0;
+ int MODE_BINAURAL = 1;
+ }
+
private static final String TAG = "HearingAidProfile";
private static boolean V = true;
@@ -212,6 +247,11 @@ public class HearingAidProfile implements LocalBluetoothProfile {
return isEnabled;
}
+ /**
+ * Tells remote device to set an absolute volume.
+ *
+ * @param volume Absolute volume to be set on remote
+ */
public void setVolume(int volume) {
if (mService == null) {
return;
@@ -219,6 +259,12 @@ public class HearingAidProfile implements LocalBluetoothProfile {
mService.setVolume(volume);
}
+ /**
+ * Gets the HiSyncId (unique hearing aid device identifier) of the device.
+ *
+ * @param device Bluetooth device
+ * @return the HiSyncId of the device
+ */
public long getHiSyncId(BluetoothDevice device) {
if (mService == null || device == null) {
return BluetoothHearingAid.HI_SYNC_ID_INVALID;
@@ -226,6 +272,59 @@ public class HearingAidProfile implements LocalBluetoothProfile {
return mService.getHiSyncId(device);
}
+ /**
+ * Gets the side of the device.
+ *
+ * @param device Bluetooth device.
+ * @return side of the device. See {@link DeviceSide}.
+ */
+ @DeviceSide
+ public int getDeviceSide(@NonNull BluetoothDevice device) {
+ final int defaultValue = DeviceSide.SIDE_INVALID;
+ if (mService == null) {
+ Log.w(TAG, "Proxy not attached to HearingAidService");
+ return defaultValue;
+ }
+
+ try {
+ Method method = mService.getClass().getDeclaredMethod("getDeviceSideInternal",
+ BluetoothDevice.class);
+ method.setAccessible(true);
+ return (int) method.invoke(mService, device);
+ } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
+ Log.e(TAG, "fail to get getDeviceSideInternal\n" + e.toString() + "\n"
+ + Log.getStackTraceString(new Throwable()));
+ return defaultValue;
+ }
+ }
+
+ /**
+ * Gets the mode of the device.
+ *
+ * @param device Bluetooth device
+ * @return mode of the device. See {@link DeviceMode}.
+ */
+ @DeviceMode
+ public int getDeviceMode(@NonNull BluetoothDevice device) {
+ final int defaultValue = DeviceMode.MODE_INVALID;
+ if (mService == null) {
+ Log.w(TAG, "Proxy not attached to HearingAidService");
+ return defaultValue;
+ }
+
+ try {
+ Method method = mService.getClass().getDeclaredMethod("getDeviceModeInternal",
+ BluetoothDevice.class);
+ method.setAccessible(true);
+ return (int) method.invoke(mService, device);
+ } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
+ Log.e(TAG, "fail to get getDeviceModeInternal\n" + e.toString() + "\n"
+ + Log.getStackTraceString(new Throwable()));
+
+ return defaultValue;
+ }
+ }
+
public String toString() {
return NAME;
}
diff --git a/packages/SettingsLib/src/com/android/settingslib/bluetooth/LocalBluetoothProfileManager.java b/packages/SettingsLib/src/com/android/settingslib/bluetooth/LocalBluetoothProfileManager.java
index 0619986d21f6..58944f653869 100644
--- a/packages/SettingsLib/src/com/android/settingslib/bluetooth/LocalBluetoothProfileManager.java
+++ b/packages/SettingsLib/src/com/android/settingslib/bluetooth/LocalBluetoothProfileManager.java
@@ -340,6 +340,11 @@ public class LocalBluetoothProfileManager {
if (getHearingAidProfile() != null &&
mProfile instanceof HearingAidProfile &&
(newState == BluetoothProfile.STATE_CONNECTED)) {
+ final int side = getHearingAidProfile().getDeviceSide(cachedDevice.getDevice());
+ final int mode = getHearingAidProfile().getDeviceMode(cachedDevice.getDevice());
+ cachedDevice.setDeviceSide(side);
+ cachedDevice.setDeviceMode(mode);
+
// Check if the HiSyncID has being initialized
if (cachedDevice.getHiSyncId() == BluetoothHearingAid.HI_SYNC_ID_INVALID) {
long newHiSyncId = getHearingAidProfile().getHiSyncId(cachedDevice.getDevice());
diff --git a/packages/SettingsLib/src/com/android/settingslib/media/BluetoothMediaDevice.java b/packages/SettingsLib/src/com/android/settingslib/media/BluetoothMediaDevice.java
index dd7db21f765c..afafd9f27e95 100644
--- a/packages/SettingsLib/src/com/android/settingslib/media/BluetoothMediaDevice.java
+++ b/packages/SettingsLib/src/com/android/settingslib/media/BluetoothMediaDevice.java
@@ -59,7 +59,7 @@ public class BluetoothMediaDevice extends MediaDevice {
@Override
public Drawable getIcon() {
- return BluetoothUtils.getBtDrawableWithDescription(mContext, mCachedDevice).first;
+ return BluetoothUtils.getBtClassDrawableWithDescription(mContext, mCachedDevice).first;
}
@Override
diff --git a/packages/SettingsLib/src/com/android/settingslib/qrcode/QrCodeScanModeActivity.java b/packages/SettingsLib/src/com/android/settingslib/qrcode/QrCodeScanModeActivity.java
deleted file mode 100644
index 15a910e13aa8..000000000000
--- a/packages/SettingsLib/src/com/android/settingslib/qrcode/QrCodeScanModeActivity.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Copyright (C) 2022 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.settingslib.qrcode;
-
-import static com.android.settingslib.bluetooth.BluetoothBroadcastUtils.EXTRA_BLUETOOTH_DEVICE_SINK;
-import static com.android.settingslib.bluetooth.BluetoothBroadcastUtils.EXTRA_BLUETOOTH_SINK_IS_GROUP;
-
-import android.bluetooth.BluetoothDevice;
-import android.content.Intent;
-import android.os.Bundle;
-import android.util.Log;
-
-import androidx.fragment.app.FragmentTransaction;
-
-import com.android.settingslib.R;
-import com.android.settingslib.bluetooth.BluetoothBroadcastUtils;
-import com.android.settingslib.bluetooth.BluetoothUtils;
-
-public class QrCodeScanModeActivity extends QrCodeScanModeBaseActivity {
- private static final boolean DEBUG = BluetoothUtils.D;
- private static final String TAG = "QrCodeScanModeActivity";
-
- private boolean mIsGroupOp;
- private BluetoothDevice mSink;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- }
-
- @Override
- protected void handleIntent(Intent intent) {
- String action = intent != null ? intent.getAction() : null;
- if (DEBUG) {
- Log.d(TAG, "handleIntent(), action = " + action);
- }
-
- if (action == null) {
- finish();
- return;
- }
-
- switch (action) {
- case BluetoothBroadcastUtils.ACTION_BLUETOOTH_LE_AUDIO_QR_CODE_SCANNER:
- showQrCodeScannerFragment(intent);
- break;
- default:
- if (DEBUG) {
- Log.e(TAG, "Launch with an invalid action");
- }
- finish();
- }
- }
-
- protected void showQrCodeScannerFragment(Intent intent) {
- if (DEBUG) {
- Log.d(TAG, "showQrCodeScannerFragment");
- }
-
- if (intent != null) {
- mSink = intent.getParcelableExtra(EXTRA_BLUETOOTH_DEVICE_SINK);
- mIsGroupOp = intent.getBooleanExtra(EXTRA_BLUETOOTH_SINK_IS_GROUP, false);
- if (DEBUG) {
- Log.d(TAG, "get extra from intent");
- }
- } else {
- if (DEBUG) {
- Log.d(TAG, "intent is null, can not get bluetooth information from intent.");
- }
- }
-
- QrCodeScanModeFragment fragment =
- (QrCodeScanModeFragment) mFragmentManager.findFragmentByTag(
- BluetoothBroadcastUtils.TAG_FRAGMENT_QR_CODE_SCANNER);
-
- if (fragment == null) {
- fragment = new QrCodeScanModeFragment(mIsGroupOp, mSink);
- } else {
- if (fragment.isVisible()) {
- return;
- }
-
- // When the fragment in back stack but not on top of the stack, we can simply pop
- // stack because current fragment transactions are arranged in an order
- mFragmentManager.popBackStackImmediate();
- return;
- }
- final FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
-
- fragmentTransaction.replace(R.id.fragment_container, fragment,
- BluetoothBroadcastUtils.TAG_FRAGMENT_QR_CODE_SCANNER);
- fragmentTransaction.commit();
- }
-}
-
diff --git a/packages/SettingsLib/src/com/android/settingslib/qrcode/QrCodeScanModeBaseActivity.java b/packages/SettingsLib/src/com/android/settingslib/qrcode/QrCodeScanModeBaseActivity.java
deleted file mode 100644
index 361fd5b57556..000000000000
--- a/packages/SettingsLib/src/com/android/settingslib/qrcode/QrCodeScanModeBaseActivity.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/**
- * Copyright (C) 2022 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.settingslib.qrcode;
-
-import android.content.Intent;
-import android.os.Bundle;
-
-import androidx.fragment.app.FragmentManager;
-
-import com.android.settingslib.R;
-import com.android.settingslib.core.lifecycle.ObservableActivity;
-
-public abstract class QrCodeScanModeBaseActivity extends ObservableActivity {
-
- protected FragmentManager mFragmentManager;
-
- protected abstract void handleIntent(Intent intent);
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
-
- setTheme(R.style.SudThemeGlifV3_DayNight);
-
- setContentView(R.layout.qrcode_scan_mode_activity);
- mFragmentManager = getSupportFragmentManager();
-
- if (savedInstanceState == null) {
- handleIntent(getIntent());
- }
- }
-}
diff --git a/packages/SettingsLib/src/com/android/settingslib/qrcode/QrCodeScanModeController.java b/packages/SettingsLib/src/com/android/settingslib/qrcode/QrCodeScanModeController.java
deleted file mode 100644
index 153d2d20e801..000000000000
--- a/packages/SettingsLib/src/com/android/settingslib/qrcode/QrCodeScanModeController.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/**
- * Copyright (C) 2022 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.settingslib.qrcode;
-
-import android.bluetooth.BluetoothDevice;
-import android.bluetooth.BluetoothLeBroadcastMetadata;
-import android.content.Context;
-import android.util.Log;
-
-import com.android.settingslib.bluetooth.BluetoothUtils;
-import com.android.settingslib.bluetooth.CachedBluetoothDeviceManager;
-import com.android.settingslib.bluetooth.LocalBluetoothLeBroadcastAssistant;
-import com.android.settingslib.bluetooth.LocalBluetoothLeBroadcastMetadata;
-import com.android.settingslib.bluetooth.LocalBluetoothManager;
-import com.android.settingslib.bluetooth.LocalBluetoothProfileManager;
-
-public class QrCodeScanModeController {
-
- private static final boolean DEBUG = BluetoothUtils.D;
- private static final String TAG = "QrCodeScanModeController";
-
- private LocalBluetoothLeBroadcastMetadata mLocalBroadcastMetadata;
- private LocalBluetoothLeBroadcastAssistant mLocalBroadcastAssistant;
- private LocalBluetoothManager mLocalBluetoothManager;
- private LocalBluetoothProfileManager mProfileManager;
-
- private LocalBluetoothManager.BluetoothManagerCallback
- mOnInitCallback = new LocalBluetoothManager.BluetoothManagerCallback() {
- @Override
- public void onBluetoothManagerInitialized(Context appContext,
- LocalBluetoothManager bluetoothManager) {
- BluetoothUtils.setErrorListener(mErrorListener);
- }
- };
-
- private BluetoothUtils.ErrorListener
- mErrorListener = new BluetoothUtils.ErrorListener() {
- @Override
- public void onShowError(Context context, String name, int messageResId) {
- if (DEBUG) {
- Log.d(TAG, "Get error when initializing BluetoothManager. ");
- }
- }
- };
-
- public QrCodeScanModeController(Context context) {
- if (DEBUG) {
- Log.d(TAG, "QrCodeScanModeController constructor.");
- }
- mLocalBluetoothManager = LocalBluetoothManager.getInstance(context, mOnInitCallback);
- mProfileManager = mLocalBluetoothManager.getProfileManager();
- mLocalBroadcastMetadata = new LocalBluetoothLeBroadcastMetadata();
- CachedBluetoothDeviceManager cachedDeviceManager = new CachedBluetoothDeviceManager(context,
- mLocalBluetoothManager);
- mLocalBroadcastAssistant = new LocalBluetoothLeBroadcastAssistant(context,
- cachedDeviceManager, mProfileManager);
- }
-
- private BluetoothLeBroadcastMetadata convertToBroadcastMetadata(String qrCodeString) {
- return mLocalBroadcastMetadata.convertToBroadcastMetadata(qrCodeString);
- }
-
- public void addSource(BluetoothDevice sink, String sourceMetadata,
- boolean isGroupOp) {
- mLocalBroadcastAssistant.addSource(sink,
- convertToBroadcastMetadata(sourceMetadata), isGroupOp);
- }
-}
diff --git a/packages/SettingsLib/src/com/android/settingslib/qrcode/QrCodeScanModeFragment.java b/packages/SettingsLib/src/com/android/settingslib/qrcode/QrCodeScanModeFragment.java
deleted file mode 100644
index 069b9507ccef..000000000000
--- a/packages/SettingsLib/src/com/android/settingslib/qrcode/QrCodeScanModeFragment.java
+++ /dev/null
@@ -1,235 +0,0 @@
-/**
- * Copyright (C) 2022 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.settingslib.qrcode;
-
-import android.bluetooth.BluetoothDevice;
-import android.content.Context;
-import android.graphics.Matrix;
-import android.graphics.Outline;
-import android.graphics.Rect;
-import android.graphics.SurfaceTexture;
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.Message;
-import android.util.Log;
-import android.util.Size;
-import android.view.LayoutInflater;
-import android.view.TextureView;
-import android.view.View;
-import android.view.ViewGroup;
-import android.view.ViewOutlineProvider;
-import android.view.accessibility.AccessibilityEvent;
-import android.widget.TextView;
-
-import com.android.settingslib.R;
-import com.android.settingslib.bluetooth.BluetoothBroadcastUtils;
-import com.android.settingslib.bluetooth.BluetoothUtils;
-import com.android.settingslib.core.lifecycle.ObservableFragment;
-
-import androidx.annotation.NonNull;
-import androidx.annotation.StringRes;
-
-public class QrCodeScanModeFragment extends ObservableFragment implements
- TextureView.SurfaceTextureListener,
- QrCamera.ScannerCallback {
- private static final boolean DEBUG = BluetoothUtils.D;
- private static final String TAG = "QrCodeScanModeFragment";
-
- /** Message sent to hide error message */
- private static final int MESSAGE_HIDE_ERROR_MESSAGE = 1;
- /** Message sent to show error message */
- private static final int MESSAGE_SHOW_ERROR_MESSAGE = 2;
- /** Message sent to broadcast QR code */
- private static final int MESSAGE_SCAN_BROADCAST_SUCCESS = 3;
-
- private static final long SHOW_ERROR_MESSAGE_INTERVAL = 10000;
- private static final long SHOW_SUCCESS_SQUARE_INTERVAL = 1000;
-
- private boolean mIsGroupOp;
- private int mCornerRadius;
- private BluetoothDevice mSink;
- private String mBroadcastMetadata;
- private Context mContext;
- private QrCamera mCamera;
- private QrCodeScanModeController mController;
- private TextureView mTextureView;
- private TextView mSummary;
- private TextView mErrorMessage;
-
- public QrCodeScanModeFragment(boolean isGroupOp, BluetoothDevice sink) {
- mIsGroupOp = isGroupOp;
- mSink = sink;
- }
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- mContext = getContext();
- mController = new QrCodeScanModeController(mContext);
- }
-
- @Override
- public final View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- return inflater.inflate(R.layout.qrcode_scanner_fragment, container,
- /* attachToRoot */ false);
- }
-
- @Override
- public void onViewCreated(View view, Bundle savedInstanceState) {
- mTextureView = view.findViewById(R.id.preview_view);
- mCornerRadius = mContext.getResources().getDimensionPixelSize(
- R.dimen.qrcode_preview_radius);
- mTextureView.setSurfaceTextureListener(this);
- mTextureView.setOutlineProvider(new ViewOutlineProvider() {
- @Override
- public void getOutline(View view, Outline outline) {
- outline.setRoundRect(0,0, view.getWidth(), view.getHeight(), mCornerRadius);
- }
- });
- mTextureView.setClipToOutline(true);
- mErrorMessage = view.findViewById(R.id.error_message);
- }
-
- private void initCamera(SurfaceTexture surface) {
- // Check if the camera has already created.
- if (mCamera == null) {
- mCamera = new QrCamera(mContext, this);
- mCamera.start(surface);
- }
- }
-
- private void destroyCamera() {
- if (mCamera != null) {
- mCamera.stop();
- mCamera = null;
- }
- }
-
- @Override
- public void onSurfaceTextureAvailable(@NonNull SurfaceTexture surface, int width, int height) {
- initCamera(surface);
- }
-
- @Override
- public void onSurfaceTextureSizeChanged(@NonNull SurfaceTexture surface, int width,
- int height) {
- }
-
- @Override
- public boolean onSurfaceTextureDestroyed(@NonNull SurfaceTexture surface) {
- destroyCamera();
- return true;
- }
-
- @Override
- public void onSurfaceTextureUpdated(@NonNull SurfaceTexture surface) {
- }
-
- @Override
- public void handleSuccessfulResult(String qrCode) {
- if (DEBUG) {
- Log.d(TAG, "handleSuccessfulResult(), get the qr code string.");
- }
- mBroadcastMetadata = qrCode;
- handleBtLeAudioScanner();
- }
-
- @Override
- public void handleCameraFailure() {
- destroyCamera();
- }
-
- @Override
- public Size getViewSize() {
- return new Size(mTextureView.getWidth(), mTextureView.getHeight());
- }
-
- @Override
- public Rect getFramePosition(Size previewSize, int cameraOrientation) {
- return new Rect(0, 0, previewSize.getHeight(), previewSize.getHeight());
- }
-
- @Override
- public void setTransform(Matrix transform) {
- mTextureView.setTransform(transform);
- }
-
- @Override
- public boolean isValid(String qrCode) {
- if (qrCode.startsWith(BluetoothBroadcastUtils.SCHEME_BT_BROADCAST_METADATA)) {
- return true;
- } else {
- showErrorMessage(R.string.bt_le_audio_qr_code_is_not_valid_format);
- return false;
- }
- }
-
- protected boolean isDecodeTaskAlive() {
- return mCamera != null && mCamera.isDecodeTaskAlive();
- }
-
- private final Handler mHandler = new Handler() {
- @Override
- public void handleMessage(Message msg) {
- switch (msg.what) {
- case MESSAGE_HIDE_ERROR_MESSAGE:
- mErrorMessage.setVisibility(View.INVISIBLE);
- break;
-
- case MESSAGE_SHOW_ERROR_MESSAGE:
- final String errorMessage = (String) msg.obj;
-
- mErrorMessage.setVisibility(View.VISIBLE);
- mErrorMessage.setText(errorMessage);
- mErrorMessage.sendAccessibilityEvent(
- AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
-
- // Cancel any pending messages to hide error view and requeue the message so
- // user has time to see error
- removeMessages(MESSAGE_HIDE_ERROR_MESSAGE);
- sendEmptyMessageDelayed(MESSAGE_HIDE_ERROR_MESSAGE,
- SHOW_ERROR_MESSAGE_INTERVAL);
- break;
-
- case MESSAGE_SCAN_BROADCAST_SUCCESS:
- mController.addSource(mSink, mBroadcastMetadata, mIsGroupOp);
- updateSummary();
- mSummary.sendAccessibilityEvent(
- AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
- break;
- default:
- }
- }
- };
-
- private void showErrorMessage(@StringRes int messageResId) {
- final Message message = mHandler.obtainMessage(MESSAGE_SHOW_ERROR_MESSAGE,
- getString(messageResId));
- message.sendToTarget();
- }
-
- private void handleBtLeAudioScanner() {
- Message message = mHandler.obtainMessage(MESSAGE_SCAN_BROADCAST_SUCCESS);
- mHandler.sendMessageDelayed(message, SHOW_SUCCESS_SQUARE_INTERVAL);
- }
-
- private void updateSummary() {
- mSummary.setText(getString(R.string.bt_le_audio_scan_qr_code_scanner,
- null /* broadcast_name*/));;
- }
-}
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/bluetooth/BluetoothUtilsTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/bluetooth/BluetoothUtilsTest.java
index 2e855145e152..1c0ea1a1f4b0 100644
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/bluetooth/BluetoothUtilsTest.java
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/bluetooth/BluetoothUtilsTest.java
@@ -51,6 +51,11 @@ public class BluetoothUtilsTest {
private static final String STRING_METADATA = "string_metadata";
private static final String BOOL_METADATA = "true";
private static final String INT_METADATA = "25";
+ private static final int METADATA_FAST_PAIR_CUSTOMIZED_FIELDS = 25;
+ private static final String KEY_HEARABLE_CONTROL_SLICE = "HEARABLE_CONTROL_SLICE_WITH_WIDTH";
+ private static final String CONTROL_METADATA =
+ "<HEARABLE_CONTROL_SLICE_WITH_WIDTH>" + STRING_METADATA
+ + "</HEARABLE_CONTROL_SLICE_WITH_WIDTH>";
@Before
public void setUp() {
@@ -152,6 +157,15 @@ public class BluetoothUtilsTest {
}
@Test
+ public void getControlUriMetaData_hasMetaData_returnsCorrectMetaData() {
+ when(mBluetoothDevice.getMetadata(METADATA_FAST_PAIR_CUSTOMIZED_FIELDS)).thenReturn(
+ CONTROL_METADATA.getBytes());
+
+ assertThat(BluetoothUtils.getControlUriMetaData(mBluetoothDevice)).isEqualTo(
+ STRING_METADATA);
+ }
+
+ @Test
public void isAdvancedDetailsHeader_untetheredHeadset_returnTrue() {
when(mBluetoothDevice.getMetadata(
BluetoothDevice.METADATA_IS_UNTETHERED_HEADSET)).thenReturn(
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/bluetooth/CachedBluetoothDeviceTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/bluetooth/CachedBluetoothDeviceTest.java
index 55d125e01388..be2a55ede942 100644
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/bluetooth/CachedBluetoothDeviceTest.java
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/bluetooth/CachedBluetoothDeviceTest.java
@@ -78,6 +78,7 @@ public class CachedBluetoothDeviceTest {
@Mock
private BluetoothDevice mSubDevice;
private CachedBluetoothDevice mCachedDevice;
+ private CachedBluetoothDevice mSubCachedDevice;
private AudioManager mAudioManager;
private Context mContext;
private int mBatteryLevel = BluetoothDevice.BATTERY_LEVEL_UNKNOWN;
@@ -95,7 +96,9 @@ public class CachedBluetoothDeviceTest {
when(mPanProfile.isProfileReady()).thenReturn(true);
when(mHearingAidProfile.isProfileReady()).thenReturn(true);
mCachedDevice = spy(new CachedBluetoothDevice(mContext, mProfileManager, mDevice));
+ mSubCachedDevice = spy(new CachedBluetoothDevice(mContext, mProfileManager, mSubDevice));
doAnswer((invocation) -> mBatteryLevel).when(mCachedDevice).getBatteryLevel();
+ doAnswer((invocation) -> mBatteryLevel).when(mSubCachedDevice).getBatteryLevel();
}
@Test
@@ -351,8 +354,9 @@ public class CachedBluetoothDeviceTest {
assertThat(mCachedDevice.getConnectionSummary()).isNull();
// Set device as Active for Hearing Aid and test connection state summary
+ mCachedDevice.setDeviceSide(HearingAidProfile.DeviceSide.SIDE_LEFT);
mCachedDevice.onActiveDeviceChanged(true, BluetoothProfile.HEARING_AID);
- assertThat(mCachedDevice.getConnectionSummary()).isEqualTo("Active");
+ assertThat(mCachedDevice.getConnectionSummary()).isEqualTo("Active, left only");
// Set Hearing Aid profile to be disconnected and test connection state summary
mCachedDevice.onActiveDeviceChanged(false, BluetoothProfile.HEARING_AID);
@@ -390,17 +394,36 @@ public class CachedBluetoothDeviceTest {
}
@Test
- public void getConnectionSummary_testHearingAidInCall_returnActive() {
+ public void getConnectionSummary_testHearingAidRightEarInCall_returnActiveRightEar() {
// Arrange:
- // 1. Profile: {HEARING_AID, Connected, Active}
+ // 1. Profile: {HEARING_AID, Connected, Active, Right ear}
// 2. Audio Manager: In Call
updateProfileStatus(mHearingAidProfile, BluetoothProfile.STATE_CONNECTED);
+ mCachedDevice.setDeviceSide(HearingAidProfile.DeviceSide.SIDE_RIGHT);
mCachedDevice.onActiveDeviceChanged(true, BluetoothProfile.HEARING_AID);
mAudioManager.setMode(AudioManager.MODE_IN_CALL);
// Act & Assert:
// Get "Active" result without Battery Level.
- assertThat(mCachedDevice.getConnectionSummary()).isEqualTo("Active");
+ assertThat(mCachedDevice.getConnectionSummary()).isEqualTo("Active, right only");
+ }
+
+ @Test
+ public void getConnectionSummary_testHearingAidBothEarInCall_returnActiveBothEar() {
+ // Arrange:
+ // 1. Profile: {HEARING_AID, Connected, Active, Both ear}
+ // 2. Audio Manager: In Call
+ mCachedDevice.setDeviceSide(HearingAidProfile.DeviceSide.SIDE_RIGHT);
+ updateProfileStatus(mHearingAidProfile, BluetoothProfile.STATE_CONNECTED);
+ mSubCachedDevice.setDeviceSide(HearingAidProfile.DeviceSide.SIDE_LEFT);
+ updateSubDeviceProfileStatus(mHearingAidProfile, BluetoothProfile.STATE_CONNECTED);
+ mCachedDevice.setSubDevice(mSubCachedDevice);
+ mCachedDevice.onActiveDeviceChanged(true, BluetoothProfile.HEARING_AID);
+ mAudioManager.setMode(AudioManager.MODE_IN_CALL);
+
+ // Act & Assert:
+ // Get "Active" result without Battery Level.
+ assertThat(mCachedDevice.getConnectionSummary()).isEqualTo("Active, left and right");
}
@Test
@@ -925,39 +948,41 @@ public class CachedBluetoothDeviceTest {
mCachedDevice.onProfileStateChanged(profile, status);
}
+ private void updateSubDeviceProfileStatus(LocalBluetoothProfile profile, int status) {
+ doReturn(status).when(profile).getConnectionStatus(mSubDevice);
+ mSubCachedDevice.onProfileStateChanged(profile, status);
+ }
+
@Test
public void getSubDevice_setSubDevice() {
- CachedBluetoothDevice subCachedDevice = new CachedBluetoothDevice(mContext, mProfileManager,
- mSubDevice);
- mCachedDevice.setSubDevice(subCachedDevice);
+ mCachedDevice.setSubDevice(mSubCachedDevice);
- assertThat(mCachedDevice.getSubDevice()).isEqualTo(subCachedDevice);
+ assertThat(mCachedDevice.getSubDevice()).isEqualTo(mSubCachedDevice);
}
@Test
public void switchSubDeviceContent() {
- CachedBluetoothDevice subCachedDevice = new CachedBluetoothDevice(mContext, mProfileManager,
- mSubDevice);
+
mCachedDevice.mRssi = RSSI_1;
mCachedDevice.mJustDiscovered = JUSTDISCOVERED_1;
- subCachedDevice.mRssi = RSSI_2;
- subCachedDevice.mJustDiscovered = JUSTDISCOVERED_2;
- mCachedDevice.setSubDevice(subCachedDevice);
+ mSubCachedDevice.mRssi = RSSI_2;
+ mSubCachedDevice.mJustDiscovered = JUSTDISCOVERED_2;
+ mCachedDevice.setSubDevice(mSubCachedDevice);
assertThat(mCachedDevice.mRssi).isEqualTo(RSSI_1);
assertThat(mCachedDevice.mJustDiscovered).isEqualTo(JUSTDISCOVERED_1);
assertThat(mCachedDevice.mDevice).isEqualTo(mDevice);
- assertThat(subCachedDevice.mRssi).isEqualTo(RSSI_2);
- assertThat(subCachedDevice.mJustDiscovered).isEqualTo(JUSTDISCOVERED_2);
- assertThat(subCachedDevice.mDevice).isEqualTo(mSubDevice);
+ assertThat(mSubCachedDevice.mRssi).isEqualTo(RSSI_2);
+ assertThat(mSubCachedDevice.mJustDiscovered).isEqualTo(JUSTDISCOVERED_2);
+ assertThat(mSubCachedDevice.mDevice).isEqualTo(mSubDevice);
mCachedDevice.switchSubDeviceContent();
assertThat(mCachedDevice.mRssi).isEqualTo(RSSI_2);
assertThat(mCachedDevice.mJustDiscovered).isEqualTo(JUSTDISCOVERED_2);
assertThat(mCachedDevice.mDevice).isEqualTo(mSubDevice);
- assertThat(subCachedDevice.mRssi).isEqualTo(RSSI_1);
- assertThat(subCachedDevice.mJustDiscovered).isEqualTo(JUSTDISCOVERED_1);
- assertThat(subCachedDevice.mDevice).isEqualTo(mDevice);
+ assertThat(mSubCachedDevice.mRssi).isEqualTo(RSSI_1);
+ assertThat(mSubCachedDevice.mJustDiscovered).isEqualTo(JUSTDISCOVERED_1);
+ assertThat(mSubCachedDevice.mDevice).isEqualTo(mDevice);
}
@Test
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsBackupAgent.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsBackupAgent.java
index 0c6d40aa9910..5088533ccdd8 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsBackupAgent.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsBackupAgent.java
@@ -1074,13 +1074,63 @@ public class SettingsBackupAgent extends BackupAgentHelper {
if (DEBUG) Log.d(TAG, "Successfully unMarshaled SoftApConfiguration ");
// Depending on device hardware, we may need to notify the user of a setting change
SoftApConfiguration storedConfig = mWifiManager.getSoftApConfiguration();
- if (!storedConfig.equals(configInCloud)) {
+
+ if (isNeedToNotifyUserConfigurationHasChanged(configInCloud, storedConfig)) {
Log.d(TAG, "restored ap configuration requires a conversion, notify the user");
WifiSoftApConfigChangedNotifier.notifyUserOfConfigConversion(this);
}
}
}
+ private boolean isNeedToNotifyUserConfigurationHasChanged(SoftApConfiguration configInCloud,
+ SoftApConfiguration storedConfig) {
+ // Check if the cloud configuration was modified when restored to the device.
+ // All elements of the configuration are compared except:
+ // 1. Persistent randomized MAC address (which is per device)
+ // 2. The flag indicating whether the configuration is "user modified"
+ return !(Objects.equals(configInCloud.getWifiSsid(), storedConfig.getWifiSsid())
+ && Objects.equals(configInCloud.getBssid(), storedConfig.getBssid())
+ && Objects.equals(configInCloud.getPassphrase(), storedConfig.getPassphrase())
+ && configInCloud.isHiddenSsid() == storedConfig.isHiddenSsid()
+ && configInCloud.getChannels().toString().equals(
+ storedConfig.getChannels().toString())
+ && configInCloud.getSecurityType() == storedConfig.getSecurityType()
+ && configInCloud.getMaxNumberOfClients() == storedConfig.getMaxNumberOfClients()
+ && configInCloud.isAutoShutdownEnabled() == storedConfig.isAutoShutdownEnabled()
+ && configInCloud.getShutdownTimeoutMillis()
+ == storedConfig.getShutdownTimeoutMillis()
+ && configInCloud.isClientControlByUserEnabled()
+ == storedConfig.isClientControlByUserEnabled()
+ && Objects.equals(configInCloud.getBlockedClientList(),
+ storedConfig.getBlockedClientList())
+ && Objects.equals(configInCloud.getAllowedClientList(),
+ storedConfig.getAllowedClientList())
+ && configInCloud.getMacRandomizationSetting()
+ == storedConfig.getMacRandomizationSetting()
+ && configInCloud.isBridgedModeOpportunisticShutdownEnabled()
+ == storedConfig.isBridgedModeOpportunisticShutdownEnabled()
+ && configInCloud.isIeee80211axEnabled() == storedConfig.isIeee80211axEnabled()
+ && configInCloud.isIeee80211beEnabled() == storedConfig.isIeee80211beEnabled()
+ && configInCloud.getBridgedModeOpportunisticShutdownTimeoutMillis()
+ == storedConfig.getBridgedModeOpportunisticShutdownTimeoutMillis()
+ && Objects.equals(configInCloud.getVendorElements(),
+ storedConfig.getVendorElements())
+ && (configInCloud.getPersistentRandomizedMacAddress() != null
+ ? Objects.equals(configInCloud.getPersistentRandomizedMacAddress(),
+ storedConfig.getPersistentRandomizedMacAddress()) : true)
+ && Arrays.equals(configInCloud.getAllowedAcsChannels(
+ SoftApConfiguration.BAND_2GHZ),
+ storedConfig.getAllowedAcsChannels(SoftApConfiguration.BAND_2GHZ))
+ && Arrays.equals(configInCloud.getAllowedAcsChannels(
+ SoftApConfiguration.BAND_5GHZ),
+ storedConfig.getAllowedAcsChannels(SoftApConfiguration.BAND_5GHZ))
+ && Arrays.equals(configInCloud.getAllowedAcsChannels(
+ SoftApConfiguration.BAND_6GHZ),
+ storedConfig.getAllowedAcsChannels(SoftApConfiguration.BAND_6GHZ))
+ && configInCloud.getMaxChannelBandwidth() == storedConfig.getMaxChannelBandwidth()
+ );
+ }
+
private byte[] getNetworkPolicies() {
NetworkPolicyManager networkPolicyManager =
(NetworkPolicyManager) getSystemService(NETWORK_POLICY_SERVICE);
diff --git a/packages/SystemUI/AndroidManifest.xml b/packages/SystemUI/AndroidManifest.xml
index 290ce345694e..4d0888ab8d2d 100644
--- a/packages/SystemUI/AndroidManifest.xml
+++ b/packages/SystemUI/AndroidManifest.xml
@@ -323,6 +323,8 @@
<!-- To read safety center status -->
<uses-permission android:name="android.permission.READ_SAFETY_CENTER_STATUS" />
+ <uses-permission android:name="android.permission.SET_UNRESTRICTED_KEEP_CLEAR_AREAS" />
+
<protected-broadcast android:name="com.android.settingslib.action.REGISTER_SLICE_RECEIVER" />
<protected-broadcast android:name="com.android.settingslib.action.UNREGISTER_SLICE_RECEIVER" />
<protected-broadcast android:name="com.android.settings.flashlight.action.FLASHLIGHT_CHANGED" />
diff --git a/packages/SystemUI/TEST_MAPPING b/packages/SystemUI/TEST_MAPPING
index d146fc91bfb5..b01fd6de5243 100644
--- a/packages/SystemUI/TEST_MAPPING
+++ b/packages/SystemUI/TEST_MAPPING
@@ -124,49 +124,5 @@
}
]
}
- ],
- "hubui-postsubmit": [
- {
- "name": "PlatformScenarioTests",
- "options": [
- {
- "include-filter": "android.platform.test.scenario.hubui"
- },
- {
- "include-annotation": "android.platform.test.scenario.annotation.HubUi"
- },
- {
- "exclude-annotation": "org.junit.Ignore"
- },
- {
- "exclude-annotation": "androidx.test.filters.FlakyTest"
- }
- ]
- }
- ],
- "hubui-presubmit": [
- {
- "name": "PlatformScenarioTests",
- "options": [
- {
- "include-annotation": "android.platform.test.annotations.Presubmit"
- },
- {
- "include-annotation": "android.platform.test.scenario.annotation.HubUi"
- },
- {
- "include-filter": "android.platform.test.scenario.hubui"
- },
- {
- "exclude-annotation": "org.junit.Ignore"
- },
- {
- "exclude-annotation": "androidx.test.filters.FlakyTest"
- },
- {
- "exclude-annotation": "android.platform.test.annotations.Postsubmit"
- }
- ]
- }
]
}
diff --git a/packages/SystemUI/monet/src/com/android/systemui/monet/ColorScheme.kt b/packages/SystemUI/monet/src/com/android/systemui/monet/ColorScheme.kt
index dd45b6f39bdd..0c8202260907 100644
--- a/packages/SystemUI/monet/src/com/android/systemui/monet/ColorScheme.kt
+++ b/packages/SystemUI/monet/src/com/android/systemui/monet/ColorScheme.kt
@@ -21,7 +21,6 @@ import android.app.WallpaperColors
import android.graphics.Color
import com.android.internal.graphics.ColorUtils
import com.android.internal.graphics.cam.Cam
-import com.android.internal.graphics.cam.CamUtils.lstarFromInt
import kotlin.math.absoluteValue
import kotlin.math.max
import kotlin.math.roundToInt
@@ -50,7 +49,7 @@ internal interface Hue {
val previousHue = hueAndRotations[previousIndex].first
if (ColorScheme.angleIsBetween(sourceHue, thisHue, previousHue)) {
return ColorScheme.wrapDegreesDouble(sourceHue.toDouble() +
- hueAndRotations[previousIndex].first)
+ hueAndRotations[previousIndex].second)
}
}
@@ -143,12 +142,24 @@ internal class ChromaMinimum(val chroma: Double) : Chroma {
}
}
+internal class ChromaMultiple(val multiple: Double) : Chroma {
+ override fun get(sourceColor: Cam): Double {
+ return sourceColor.chroma * multiple
+ }
+}
+
internal class ChromaConstant(val chroma: Double) : Chroma {
override fun get(sourceColor: Cam): Double {
return chroma
}
}
+internal class ChromaSource : Chroma {
+ override fun get(sourceColor: Cam): Double {
+ return sourceColor.chroma.toDouble()
+ }
+}
+
internal class TonalSpec(val hue: Hue = HueSource(), val chroma: Chroma) {
fun shades(sourceColor: Cam): List<Int> {
val hue = hue.get(sourceColor)
@@ -184,8 +195,8 @@ enum class Style(internal val coreSpec: CoreSpec) {
a1 = TonalSpec(HueSource(), ChromaMinimum(48.0)),
a2 = TonalSpec(HueVibrantSecondary(), ChromaConstant(24.0)),
a3 = TonalSpec(HueVibrantTertiary(), ChromaConstant(32.0)),
- n1 = TonalSpec(HueSource(), ChromaConstant(10.0)),
- n2 = TonalSpec(HueSource(), ChromaConstant(12.0))
+ n1 = TonalSpec(HueSource(), ChromaConstant(12.0)),
+ n2 = TonalSpec(HueSource(), ChromaConstant(14.0))
)),
EXPRESSIVE(CoreSpec(
a1 = TonalSpec(HueAdd(240.0), ChromaConstant(40.0)),
@@ -208,6 +219,13 @@ enum class Style(internal val coreSpec: CoreSpec) {
n1 = TonalSpec(HueSource(), ChromaConstant(10.0)),
n2 = TonalSpec(HueSource(), ChromaConstant(16.0))
)),
+ CONTENT(CoreSpec(
+ a1 = TonalSpec(HueSource(), ChromaSource()),
+ a2 = TonalSpec(HueSource(), ChromaMultiple(0.33)),
+ a3 = TonalSpec(HueSource(), ChromaMultiple(0.66)),
+ n1 = TonalSpec(HueSource(), ChromaMultiple(0.0833)),
+ n2 = TonalSpec(HueSource(), ChromaMultiple(0.1666))
+ )),
}
class ColorScheme(
@@ -231,7 +249,7 @@ class ColorScheme(
darkTheme: Boolean,
style: Style = Style.TONAL_SPOT
):
- this(getSeedColor(wallpaperColors), darkTheme, style)
+ this(getSeedColor(wallpaperColors, style != Style.CONTENT), darkTheme, style)
val allAccentColors: List<Int>
get() {
@@ -260,7 +278,7 @@ class ColorScheme(
val proposedSeedCam = Cam.fromInt(seed)
val seedArgb = if (seed == Color.TRANSPARENT) {
GOOGLE_BLUE
- } else if (proposedSeedCam.chroma < 5) {
+ } else if (style != Style.CONTENT && proposedSeedCam.chroma < 5) {
GOOGLE_BLUE
} else {
seed
@@ -289,22 +307,26 @@ class ColorScheme(
* Identifies a color to create a color scheme from.
*
* @param wallpaperColors Colors extracted from an image via quantization.
+ * @param filter If false, allow colors that have low chroma, creating grayscale themes.
* @return ARGB int representing the color
*/
@JvmStatic
+ @JvmOverloads
@ColorInt
- fun getSeedColor(wallpaperColors: WallpaperColors): Int {
- return getSeedColors(wallpaperColors).first()
+ fun getSeedColor(wallpaperColors: WallpaperColors, filter: Boolean = true): Int {
+ return getSeedColors(wallpaperColors, filter).first()
}
/**
* Filters and ranks colors from WallpaperColors.
*
* @param wallpaperColors Colors extracted from an image via quantization.
+ * @param filter If false, allow colors that have low chroma, creating grayscale themes.
* @return List of ARGB ints, ordered from highest scoring to lowest.
*/
@JvmStatic
- fun getSeedColors(wallpaperColors: WallpaperColors): List<Int> {
+ @JvmOverloads
+ fun getSeedColors(wallpaperColors: WallpaperColors, filter: Boolean = true): List<Int> {
val totalPopulation = wallpaperColors.allColors.values.reduce { a, b -> a + b }
.toDouble()
val totalPopulationMeaningless = (totalPopulation == 0.0)
@@ -317,9 +339,12 @@ class ColorScheme(
val distinctColors = wallpaperColors.mainColors.map {
it.toArgb()
}.distinct().filter {
- Cam.fromInt(it).chroma >= MIN_CHROMA
+ if (!filter) {
+ true
+ } else {
+ Cam.fromInt(it).chroma >= MIN_CHROMA
+ }
}.toList()
-
if (distinctColors.isEmpty()) {
return listOf(GOOGLE_BLUE)
}
@@ -332,7 +357,7 @@ class ColorScheme(
val intToCam = wallpaperColors.allColors.mapValues { Cam.fromInt(it.key) }
// Get an array with 360 slots. A slot contains the percentage of colors with that hue.
- val hueProportions = huePopulations(intToCam, intToProportion)
+ val hueProportions = huePopulations(intToCam, intToProportion, filter)
// Map each color to the percentage of the image with its hue.
val intToHueProportion = wallpaperColors.allColors.mapValues {
val cam = intToCam[it.key]!!
@@ -346,13 +371,12 @@ class ColorScheme(
// Remove any inappropriate seed colors. For example, low chroma colors look grayscale
// raising their chroma will turn them to a much louder color that may not have been
// in the image.
- val filteredIntToCam = intToCam.filter {
+ val filteredIntToCam = if (!filter) intToCam else (intToCam.filter {
val cam = it.value
- val lstar = lstarFromInt(it.key)
val proportion = intToHueProportion[it.key]!!
cam.chroma >= MIN_CHROMA &&
(totalPopulationMeaningless || proportion > 0.01)
- }
+ })
// Sort the colors by score, from high to low.
val intToScoreIntermediate = filteredIntToCam.mapValues {
score(it.value, intToHueProportion[it.key]!!)
@@ -444,7 +468,8 @@ class ColorScheme(
private fun huePopulations(
camByColor: Map<Int, Cam>,
- populationByColor: Map<Int, Double>
+ populationByColor: Map<Int, Double>,
+ filter: Boolean = true
): List<Double> {
val huePopulation = List(size = 360, init = { 0.0 }).toMutableList()
@@ -452,7 +477,7 @@ class ColorScheme(
val population = populationByColor[entry.key]!!
val cam = camByColor[entry.key]!!
val hue = cam.hue.roundToInt() % 360
- if (cam.chroma <= MIN_CHROMA) {
+ if (filter && cam.chroma <= MIN_CHROMA) {
continue
}
huePopulation[hue] = huePopulation[hue] + population
diff --git a/packages/SettingsLib/res/layout/qrcode_scan_mode_activity.xml b/packages/SystemUI/res/drawable/broadcast_dialog_btn_bg.xml
index f0a182b3d67b..5fd7ee29d838 100644
--- a/packages/SettingsLib/res/layout/qrcode_scan_mode_activity.xml
+++ b/packages/SystemUI/res/drawable/broadcast_dialog_btn_bg.xml
@@ -15,16 +15,9 @@
limitations under the License.
-->
-<LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/root"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical">
-
- <LinearLayout
- android:id="@+id/fragment_container"
- android:layout_width="match_parent"
- android:layout_height="match_parent"/>
-
-</LinearLayout>
+<shape xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:androidprv="http://schemas.android.com/apk/prv/res/android"
+ android:shape="rectangle">
+ <solid android:color="?androidprv:attr/colorAccentPrimary" />
+ <corners android:radius="@dimen/broadcast_dialog_btn_radius" />
+</shape>
diff --git a/packages/SystemUI/res/drawable/ic_chevron_icon.xml b/packages/SystemUI/res/drawable/ic_chevron_icon.xml
index acbbbcb21503..d60cc8c74e80 100644
--- a/packages/SystemUI/res/drawable/ic_chevron_icon.xml
+++ b/packages/SystemUI/res/drawable/ic_chevron_icon.xml
@@ -15,14 +15,6 @@
~ limitations under the License.
-->
-<vector xmlns:android="http://schemas.android.com/apk/res/android"
- android:width="18dp"
- android:height="31dp"
- android:viewportWidth="18"
- android:viewportHeight="31">
- <path
- android:pathData="M0.0061,27.8986L2.6906,30.5831L17.9219,15.3518L2.6906,0.1206L0.0061,2.8051L12.5338,15.3518"
- android:strokeAlpha="0.7"
- android:fillColor="#FFFFFF"
- android:fillAlpha="0.7"/>
-</vector>
+<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24" android:tint="?attr/colorControlNormal">
+ <path android:fillColor="@android:color/white" android:pathData="M9.4,18 L8,16.6 12.6,12 8,7.4 9.4,6 15.4,12Z"/>
+</vector> \ No newline at end of file
diff --git a/packages/SettingsLib/res/drawable/ic_qr_code_scanner.xml b/packages/SystemUI/res/drawable/ic_qs_screen_saver.xml
index f6f63c5ae7fa..263a3d1c894c 100644
--- a/packages/SettingsLib/res/drawable/ic_qr_code_scanner.xml
+++ b/packages/SystemUI/res/drawable/ic_qs_screen_saver.xml
@@ -1,4 +1,3 @@
-<?xml version="1.0" encoding="utf-8"?>
<!--
Copyright (C) 2022 The Android Open Source Project
@@ -14,10 +13,12 @@
See the License for the specific language governing permissions and
limitations under the License.
-->
-
-<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp"
- android:height="24dp" android:viewportWidth="24" android:viewportHeight="24"
- android:tint="?attr/colorControlNormal">
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24"
+ android:tint="?android:attr/colorControlNormal">
<path android:fillColor="@android:color/white"
- android:pathData="M2,7V2H7V4H4V7ZM2,22V17H4V20H7V22ZM17,22V20H20V17H22V22ZM20,7V4H17V2H22V7ZM17.5,17.5H19V19H17.5ZM17.5,14.5H19V16H17.5ZM16,16H17.5V17.5H16ZM14.5,17.5H16V19H14.5ZM13,16H14.5V17.5H13ZM16,13H17.5V14.5H16ZM14.5,14.5H16V16H14.5ZM13,13H14.5V14.5H13ZM19,5V11H13V5ZM11,13V19H5V13ZM11,5V11H5V5ZM9.5,17.5V14.5H6.5V17.5ZM9.5,9.5V6.5H6.5V9.5ZM17.5,9.5V6.5H14.5V9.5Z"/>
+ android:pathData="M5,15H19L14.5,9L11,13.5L8.5,10.5ZM6,21Q5.575,21 5.287,20.712Q5,20.425 5,20V19H3Q2.175,19 1.588,18.413Q1,17.825 1,17V6Q1,5.175 1.588,4.588Q2.175,4 3,4H21Q21.825,4 22.413,4.588Q23,5.175 23,6V17Q23,17.825 22.413,18.413Q21.825,19 21,19H19V20Q19,20.425 18.712,20.712Q18.425,21 18,21ZM3,17H21Q21,17 21,17Q21,17 21,17V6Q21,6 21,6Q21,6 21,6H3Q3,6 3,6Q3,6 3,6V17Q3,17 3,17Q3,17 3,17ZM3,17Q3,17 3,17Q3,17 3,17V6Q3,6 3,6Q3,6 3,6Q3,6 3,6Q3,6 3,6V17Q3,17 3,17Q3,17 3,17Z"/>
</vector> \ No newline at end of file
diff --git a/packages/SystemUI/res/drawable/media_output_status_check.xml b/packages/SystemUI/res/drawable/media_output_status_check.xml
index 5fbc42b245b8..3d64f83eabe3 100644
--- a/packages/SystemUI/res/drawable/media_output_status_check.xml
+++ b/packages/SystemUI/res/drawable/media_output_status_check.xml
@@ -21,6 +21,6 @@
android:viewportHeight="24"
android:tint="?attr/colorControlNormal">
<path
- android:fillColor="@color/media_dialog_item_main_content"
- android:pathData="M9,16.2L4.8,12l-1.4,1.4L9,19 21,7l-1.4,-1.4L9,16.2z"/>
+ android:fillColor="@android:color/white"
+ android:pathData="M12,22Q9.925,22 8.1,21.212Q6.275,20.425 4.925,19.075Q3.575,17.725 2.788,15.9Q2,14.075 2,12Q2,9.925 2.788,8.1Q3.575,6.275 4.925,4.925Q6.275,3.575 8.1,2.787Q9.925,2 12,2Q14.075,2 15.9,2.787Q17.725,3.575 19.075,4.925Q20.425,6.275 21.212,8.1Q22,9.925 22,12Q22,14.075 21.212,15.9Q20.425,17.725 19.075,19.075Q17.725,20.425 15.9,21.212Q14.075,22 12,22ZM10.6,16.6 L17.65,9.55 16.25,8.15 10.6,13.8 7.75,10.95 6.35,12.35Z"/>
</vector>
diff --git a/packages/SystemUI/res/drawable/overlay_cancel.xml b/packages/SystemUI/res/drawable/overlay_cancel.xml
index f9786e22b2d4..3fa12ddca70a 100644
--- a/packages/SystemUI/res/drawable/overlay_cancel.xml
+++ b/packages/SystemUI/res/drawable/overlay_cancel.xml
@@ -24,6 +24,6 @@
android:fillColor="?androidprv:attr/colorAccentTertiary"
android:pathData="M16,16m-16,0a16,16 0,1 1,32 0a16,16 0,1 1,-32 0"/>
<path
- android:fillColor="?android:attr/textColorPrimary"
+ android:fillColor="?attr/overlayButtonTextColor"
android:pathData="M23,10.41L21.59,9 16,14.59 10.41,9 9,10.41 14.59,16 9,21.59 10.41,23 16,17.41 21.59,23 23,21.59 17.41,16z"/>
</vector>
diff --git a/packages/SystemUI/res/drawable/settings_input_antenna.xml b/packages/SystemUI/res/drawable/settings_input_antenna.xml
new file mode 100644
index 000000000000..f2adcaf069ef
--- /dev/null
+++ b/packages/SystemUI/res/drawable/settings_input_antenna.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ Copyright (C) 2022 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+
+<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp"
+ android:height="24dp" android:viewportWidth="24" android:viewportHeight="24"
+ android:tint="?android:attr/textColorSecondary">
+ <path android:fillColor="#FF000000"
+ android:pathData="M9,22.4 L7.6,21 11,17.6V14.3Q10.325,14 9.913,13.375Q9.5,12.75 9.5,12Q9.5,10.95 10.225,10.225Q10.95,9.5 12,9.5Q13.05,9.5 13.775,10.225Q14.5,10.95 14.5,12Q14.5,12.75 14.088,13.375Q13.675,14 13,14.3V17.6L16.4,21L15,22.4L12,19.4ZM5,12Q5,9.05 7.05,7.025Q9.1,5 12,5Q14.9,5 16.95,7.025Q19,9.05 19,12H17Q17,9.925 15.538,8.462Q14.075,7 12,7Q9.925,7 8.463,8.462Q7,9.925 7,12ZM1,12Q1,9.7 1.863,7.7Q2.725,5.7 4.225,4.212Q5.725,2.725 7.725,1.862Q9.725,1 12,1Q14.275,1 16.275,1.862Q18.275,2.725 19.775,4.212Q21.275,5.7 22.138,7.7Q23,9.7 23,12H21Q21,10.125 20.288,8.487Q19.575,6.85 18.35,5.625Q17.125,4.4 15.488,3.7Q13.85,3 12,3Q10.15,3 8.512,3.7Q6.875,4.4 5.65,5.625Q4.425,6.85 3.712,8.487Q3,10.125 3,12Z"/>
+</vector> \ No newline at end of file
diff --git a/packages/SystemUI/res/layout/broadcast_dialog.xml b/packages/SystemUI/res/layout/broadcast_dialog.xml
new file mode 100644
index 000000000000..5ba2afe5b172
--- /dev/null
+++ b/packages/SystemUI/res/layout/broadcast_dialog.xml
@@ -0,0 +1,79 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2022 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:id="@+id/dialog_bg"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:orientation="vertical">
+
+ <LinearLayout
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_marginBottom="@dimen/broadcast_dialog_margin"
+ android:orientation="vertical">
+
+ <ImageView
+ android:id="@+id/dialog_icon"
+ android:layout_width="@dimen/broadcast_dialog_icon_size"
+ android:layout_height="@dimen/broadcast_dialog_icon_size"
+ android:layout_marginTop="@dimen/broadcast_dialog_icon_margin_top"
+ android:layout_marginBottom="@dimen/broadcast_dialog_title_img_margin_top"
+ android:layout_gravity="center"
+ android:src="@drawable/settings_input_antenna"/>
+
+ <TextView
+ style="@style/BroadcastDialogTitleStyle"
+ android:id="@+id/dialog_title"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:gravity="center"
+ android:layout_gravity="center"/>
+
+ <TextView
+ style="@style/BroadcastDialogBodyStyle"
+ android:id="@+id/dialog_subtitle"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:gravity="center"
+ android:layout_gravity="center"/>
+ </LinearLayout>
+
+ <LinearLayout
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_marginHorizontal="@dimen/broadcast_dialog_margin"
+ android:layout_marginBottom="@dimen/broadcast_dialog_margin"
+ android:orientation="vertical">
+
+ <Button
+ android:layout_marginBottom="@dimen/broadcast_dialog_btn_margin_bottom"
+ android:id="@+id/switch_broadcast"
+ style="@style/BroadcastDialogButtonStyle"/>
+
+ <Button
+ android:layout_marginBottom="@dimen/broadcast_dialog_btn_margin_bottom"
+ android:id="@+id/change_output"
+ android:text="@string/bt_le_audio_broadcast_dialog_different_output"
+ style="@style/BroadcastDialogButtonStyle"/>
+
+ <Button
+ android:id="@+id/cancel"
+ android:text="@android:string/cancel"
+ style="@style/BroadcastDialogButtonStyle"/>
+ </LinearLayout>
+
+</LinearLayout>
diff --git a/packages/SystemUI/res/layout/clipboard_edit_text_activity.xml b/packages/SystemUI/res/layout/clipboard_edit_text_activity.xml
index 1122ca6bd4dc..1c09e81f92ca 100644
--- a/packages/SystemUI/res/layout/clipboard_edit_text_activity.xml
+++ b/packages/SystemUI/res/layout/clipboard_edit_text_activity.xml
@@ -12,6 +12,7 @@
android:layout_height="48dp"
android:layout_marginTop="8dp"
android:layout_marginStart="12dp"
+ android:paddingHorizontal="16dp"
android:background="@drawable/overlay_button_background"
android:text="@string/clipboard_edit_text_done"
app:layout_constraintStart_toStartOf="parent"
diff --git a/packages/SystemUI/res/layout/clipboard_overlay.xml b/packages/SystemUI/res/layout/clipboard_overlay.xml
index 085a5810608f..1712b4876b31 100644
--- a/packages/SystemUI/res/layout/clipboard_overlay.xml
+++ b/packages/SystemUI/res/layout/clipboard_overlay.xml
@@ -67,9 +67,9 @@
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="@dimen/overlay_offset_x"
- android:layout_marginBottom="8dp"
+ android:layout_marginBottom="12dp"
app:layout_constraintStart_toStartOf="parent"
- app:layout_constraintBottom_toBottomOf="@id/actions_container_background"
+ app:layout_constraintBottom_toBottomOf="parent"
android:elevation="7dp"
app:layout_constraintEnd_toEndOf="@id/clipboard_preview_end"
app:layout_constraintTop_toTopOf="@id/clipboard_preview_top"
diff --git a/packages/SystemUI/res/values/defaults.xml b/packages/SystemUI/res/values/defaults.xml
deleted file mode 100644
index f96c178b119a..000000000000
--- a/packages/SystemUI/res/values/defaults.xml
+++ /dev/null
@@ -1,23 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/**
- * Copyright (c) 2009, The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
--->
-<resources>
- <!-- Default for SystemUiDeviceConfigFlags.DEFAULT_QR_CODE_SCANNER.
- To be set if the device wants to support out of the box QR code scanning experience -->
- <string name="def_qr_code_component" translatable="false"></string>
-</resources>
diff --git a/packages/SystemUI/res/values/dimens.xml b/packages/SystemUI/res/values/dimens.xml
index 0bc3594ef183..7cafb21d3c74 100644
--- a/packages/SystemUI/res/values/dimens.xml
+++ b/packages/SystemUI/res/values/dimens.xml
@@ -30,10 +30,10 @@
<dimen name="navigation_bar_deadzone_size_max">32dp</dimen>
<!-- dimensions for the navigation bar handle -->
- <dimen name="navigation_handle_radius">1dp</dimen>
- <dimen name="navigation_handle_bottom">6dp</dimen>
+ <dimen name="navigation_handle_radius">2dp</dimen>
+ <dimen name="navigation_handle_bottom">8dp</dimen>
<dimen name="navigation_handle_sample_horizontal_margin">10dp</dimen>
- <dimen name="navigation_home_handle_width">72dp</dimen>
+ <dimen name="navigation_home_handle_width">108dp</dimen>
<!-- Size of the nav bar edge panels, should be greater to the
edge sensitivity + the drag threshold -->
@@ -1463,4 +1463,18 @@
<dimen name="media_output_broadcast_info_title_height">24dp</dimen>
<dimen name="media_output_broadcast_info_summary_height">20dp</dimen>
<dimen name="media_output_broadcast_info_edit">18dp</dimen>
+
+ <!-- Broadcast dialog -->
+ <dimen name="broadcast_dialog_title_img_margin_top">18dp</dimen>
+ <dimen name="broadcast_dialog_title_text_size">24sp</dimen>
+ <dimen name="broadcast_dialog_title_text_margin">16dp</dimen>
+ <dimen name="broadcast_dialog_title_text_margin_top">18dp</dimen>
+ <dimen name="broadcast_dialog_subtitle_text_size">14sp</dimen>
+ <dimen name="broadcast_dialog_icon_size">24dp</dimen>
+ <dimen name="broadcast_dialog_icon_margin_top">25dp</dimen>
+ <dimen name="broadcast_dialog_btn_radius">100dp</dimen>
+ <dimen name="broadcast_dialog_btn_margin_bottom">4dp</dimen>
+ <dimen name="broadcast_dialog_btn_text_size">16sp</dimen>
+ <dimen name="broadcast_dialog_btn_minHeight">44dp</dimen>
+ <dimen name="broadcast_dialog_margin">16dp</dimen>
</resources>
diff --git a/packages/SystemUI/res/values/strings.xml b/packages/SystemUI/res/values/strings.xml
index 1a05970759e6..000d6eef143f 100644
--- a/packages/SystemUI/res/values/strings.xml
+++ b/packages/SystemUI/res/values/strings.xml
@@ -819,6 +819,14 @@
<string name="keyguard_face_successful_unlock_press_alt_3">Face recognized. Press the unlock icon to open.</string>
+ <!-- Messages shown when users press outside of udfps region during -->
+ <string-array name="udfps_accessibility_touch_hints">
+ <item>Move left</item>
+ <item>Move down</item>
+ <item>Move right</item>
+ <item>Move up</item>
+ </string-array>
+
<!-- Message shown when face authentication fails and the pin pad is visible. [CHAR LIMIT=60] -->
<string name="keyguard_retry">Swipe up to try again</string>
@@ -1901,8 +1909,10 @@
<string name="notification_channel_battery">Battery</string>
<!-- Title for the notification channel dedicated to screenshot progress. [CHAR LIMIT=NONE] -->
<string name="notification_channel_screenshot">Screenshots</string>
- <!-- Title for the notification channel for miscellaneous notices. [CHAR LIMIT=NONE] -->
- <string name="notification_channel_general">General Messages</string>
+ <!-- Title for the notification channel for instant app notices. [CHAR LIMIT=NONE] -->
+ <string name="notification_channel_instant">Instant Apps</string>
+ <!-- Title for the notification channel for setup notices. [CHAR LIMIT=NONE] -->
+ <string name="notification_channel_setup">Setup</string>
<!-- Title for the notification channel for problems with storage (i.e. low disk). [CHAR LIMIT=NONE] -->
<string name="notification_channel_storage">Storage</string>
<!-- Title for the notification channel for hints and suggestions. [CHAR LIMIT=NONE] -->
@@ -2297,6 +2307,8 @@
<string name="media_output_dialog_unknown_launch_app_name">Unknown app</string>
<!-- Button text for stopping casting [CHAR LIMIT=60] -->
<string name="media_output_dialog_button_stop_casting">Stop casting</string>
+ <!-- Accessibility text describing purpose of media output dialog. [CHAR LIMIT=NONE] -->
+ <string name="media_output_dialog_accessibility_title">Available devices for audio output.</string>
<!-- Media Output Broadcast Dialog -->
<!-- Title for Broadcast First Notify Dialog [CHAR LIMIT=60] -->
@@ -2510,6 +2522,12 @@
<string name="clipboard_send_nearby_description">Send to nearby device</string>
<!-- Text informing user that copied content is hidden [CHAR LIMIT=NONE] -->
<string name="clipboard_text_hidden">Tap to view</string>
+ <!-- Accessibility announcement informing user that text has been copied [CHAR LIMIT=NONE] -->
+ <string name="clipboard_text_copied">Text copied</string>
+ <!-- Accessibility announcement informing user that text has been copied [CHAR LIMIT=NONE] -->
+ <string name="clipboard_image_copied">Image copied</string>
+ <!-- Accessibility announcement informing user that something has been copied [CHAR LIMIT=NONE] -->
+ <string name="clipboard_content_copied">Content copied</string>
<!-- Generic "add" string [CHAR LIMIT=NONE] -->
<string name="add">Add</string>
@@ -2534,4 +2552,18 @@
=1 {# notification}
other {# notifications}
}</string>
+
+ <!-- [CHAR LIMIT=NONE] Le audio broadcast dialog, media app is broadcasting -->
+ <string name="broadcasting_description_is_broadcasting">Broadcasting</string>
+ <!-- [CHAR LIMIT=NONE] Le audio broadcast dialog, title -->
+ <string name="bt_le_audio_broadcast_dialog_title">Stop broadcasting <xliff:g id="app_name" example="App Name 1">%1$s</xliff:g>?</string>
+ <!-- [CHAR LIMIT=NONE] Le audio broadcast dialog, sub-title -->
+ <string name="bt_le_audio_broadcast_dialog_sub_title">If you broadcast <xliff:g id="switchApp" example="App Name 2">%1$s</xliff:g> or change the output, your current broadcast will stop</string>
+ <!-- [CHAR LIMIT=NONE] Le audio broadcast dialog, switch to others app. -->
+ <string name="bt_le_audio_broadcast_dialog_switch_app">Broadcast <xliff:g id="switchApp" example="App Name 2">%1$s</xliff:g></string>
+ <!-- [CHAR LIMIT=NONE] Le audio broadcast dialog, different output. -->
+ <string name="bt_le_audio_broadcast_dialog_different_output">Change output</string>
+ <!-- [CHAR LIMIT=NONE] Le audio broadcast dialog, media app is unknown -->
+ <string name="bt_le_audio_broadcast_dialog_unknown_name">Unknown</string>
+
</resources>
diff --git a/packages/SystemUI/res/values/styles.xml b/packages/SystemUI/res/values/styles.xml
index 0c25f5473416..8b2481cff2a9 100644
--- a/packages/SystemUI/res/values/styles.xml
+++ b/packages/SystemUI/res/values/styles.xml
@@ -1196,4 +1196,48 @@
<item name="android:shadowColor">@color/keyguard_shadow_color</item>
<item name="android:shadowRadius">?attr/shadowRadius</item>
</style>
+
+ <style name="BroadcastDialogTitleStyle">
+ <item name="android:textAppearance">@style/TextAppearanceBroadcastDialogTitle</item>
+ <item name="android:layout_marginStart">@dimen/broadcast_dialog_title_text_margin</item>
+ <item name="android:layout_marginEnd">@dimen/broadcast_dialog_title_text_margin</item>
+ <item name="android:layout_marginTop">@dimen/broadcast_dialog_title_text_margin_top</item>
+ <item name="android:layout_marginBottom">18dp</item>
+ </style>
+
+ <style name="TextAppearanceBroadcastDialogTitle" parent="@android:style/TextAppearance.DeviceDefault.Headline">
+ <item name="android:textSize">@dimen/broadcast_dialog_title_text_size</item>
+ <item name="android:textColor">?android:attr/textColorPrimary</item>
+ <item name="android:textDirection">locale</item>
+ <item name="android:ellipsize">end</item>
+ </style>
+
+ <style name="BroadcastDialogBodyStyle">
+ <item name="android:textAppearance">@style/TextAppearanceBroadcastDialogSubTitle</item>
+ <item name="android:layout_margin">@dimen/broadcast_dialog_title_text_margin</item>
+ </style>
+
+ <style name="TextAppearanceBroadcastDialogSubTitle" parent="@android:style/TextAppearance.DeviceDefault.Headline">
+ <item name="android:textSize">@dimen/broadcast_dialog_subtitle_text_size</item>
+ <item name="android:textColor">?android:attr/textColorSecondary</item>
+ <item name="android:textDirection">locale</item>
+ <item name="android:ellipsize">end</item>
+ </style>
+
+ <style name="BroadcastDialogButtonStyle">
+ <item name="android:textAppearance">@style/TextAppearanceBroadcastDialogButton</item>
+ <item name="android:layout_width">match_parent</item>
+ <item name="android:layout_height">wrap_content</item>
+ <item name="android:layout_gravity">center</item>
+ <item name="android:gravity">center</item>
+ <item name="android:stateListAnimator">@null</item>
+ <item name="android:elevation">0dp</item>
+ <item name="android:minHeight">@dimen/broadcast_dialog_btn_minHeight</item>
+ <item name="android:background">@drawable/broadcast_dialog_btn_bg</item>
+ </style>
+
+ <style name="TextAppearanceBroadcastDialogButton" parent="@android:style/TextAppearance.DeviceDefault.Headline">
+ <item name="android:textColor">?androidprv:attr/textColorOnAccent</item>
+ <item name="android:textSize">@dimen/broadcast_dialog_btn_text_size</item>
+ </style>
</resources>
diff --git a/packages/SystemUI/shared/Android.bp b/packages/SystemUI/shared/Android.bp
index 3cf5bc1bf13a..9f790c66302d 100644
--- a/packages/SystemUI/shared/Android.bp
+++ b/packages/SystemUI/shared/Android.bp
@@ -47,6 +47,7 @@ android_library {
],
static_libs: [
"PluginCoreLib",
+ "SystemUIUnfoldLib",
"androidx.dynamicanimation_dynamicanimation",
"androidx.concurrent_concurrent-futures",
"dagger2",
diff --git a/packages/SystemUI/shared/src/com/android/systemui/unfold/config/ResourceUnfoldTransitionConfig.kt b/packages/SystemUI/shared/src/com/android/systemui/unfold/config/ResourceUnfoldTransitionConfig.kt
deleted file mode 100644
index d1b06394b818..000000000000
--- a/packages/SystemUI/shared/src/com/android/systemui/unfold/config/ResourceUnfoldTransitionConfig.kt
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.systemui.unfold.config
-
-import android.content.Context
-import android.os.SystemProperties
-
-internal class ResourceUnfoldTransitionConfig(private val context: Context) :
- UnfoldTransitionConfig {
-
- override val isEnabled: Boolean
- get() = readIsEnabledResource() && isPropertyEnabled
-
- override val isHingeAngleEnabled: Boolean
- get() = readIsHingeAngleEnabled()
-
- private val isPropertyEnabled: Boolean
- get() =
- SystemProperties.getInt(
- UNFOLD_TRANSITION_MODE_PROPERTY_NAME, UNFOLD_TRANSITION_PROPERTY_ENABLED) ==
- UNFOLD_TRANSITION_PROPERTY_ENABLED
-
- private fun readIsEnabledResource(): Boolean =
- context.resources.getBoolean(com.android.internal.R.bool.config_unfoldTransitionEnabled)
-
- private fun readIsHingeAngleEnabled(): Boolean =
- context.resources.getBoolean(com.android.internal.R.bool.config_unfoldTransitionHingeAngle)
-}
-
-/**
- * Temporary persistent property to control unfold transition mode.
- *
- * See [com.android.unfold.config.AnimationMode].
- */
-private const val UNFOLD_TRANSITION_MODE_PROPERTY_NAME = "persist.unfold.transition_enabled"
-private const val UNFOLD_TRANSITION_PROPERTY_ENABLED = 1
diff --git a/packages/SystemUI/shared/src/com/android/systemui/unfold/system/ActivityManagerActivityTypeProvider.kt b/packages/SystemUI/shared/src/com/android/systemui/unfold/system/ActivityManagerActivityTypeProvider.kt
new file mode 100644
index 000000000000..7f2933e44b32
--- /dev/null
+++ b/packages/SystemUI/shared/src/com/android/systemui/unfold/system/ActivityManagerActivityTypeProvider.kt
@@ -0,0 +1,35 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the
+ * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package com.android.systemui.unfold.system
+
+import android.app.ActivityManager
+import android.app.WindowConfiguration
+import com.android.systemui.unfold.util.CurrentActivityTypeProvider
+import javax.inject.Inject
+import javax.inject.Singleton
+
+@Singleton
+class ActivityManagerActivityTypeProvider @Inject constructor(
+ private val activityManager: ActivityManager
+) : CurrentActivityTypeProvider {
+
+ override val isHomeActivity: Boolean?
+ get() {
+ val activityType = activityManager.getRunningTasks(/* maxNum= */ 1)
+ ?.getOrNull(0)?.topActivityType ?: return null
+
+ return activityType == WindowConfiguration.ACTIVITY_TYPE_HOME
+ }
+}
diff --git a/packages/SystemUI/shared/src/com/android/systemui/unfold/system/DeviceStateManagerFoldProvider.kt b/packages/SystemUI/shared/src/com/android/systemui/unfold/system/DeviceStateManagerFoldProvider.kt
new file mode 100644
index 000000000000..3b8d318a3a79
--- /dev/null
+++ b/packages/SystemUI/shared/src/com/android/systemui/unfold/system/DeviceStateManagerFoldProvider.kt
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the
+ * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package com.android.systemui.unfold.system
+
+import android.content.Context
+import android.hardware.devicestate.DeviceStateManager
+import com.android.systemui.unfold.updates.FoldProvider
+import com.android.systemui.unfold.updates.FoldProvider.FoldCallback
+import java.util.concurrent.Executor
+import javax.inject.Inject
+import javax.inject.Singleton
+
+@Singleton
+class DeviceStateManagerFoldProvider @Inject constructor(
+ private val deviceStateManager: DeviceStateManager,
+ private val context: Context
+) : FoldProvider {
+
+ private val callbacks: MutableMap<FoldCallback,
+ DeviceStateManager.DeviceStateCallback> = hashMapOf()
+
+ override fun registerCallback(callback: FoldCallback, executor: Executor) {
+ val listener = FoldStateListener(context, callback)
+ deviceStateManager.registerCallback(executor, listener)
+ callbacks[callback] = listener
+ }
+
+ override fun unregisterCallback(callback: FoldCallback) {
+ val listener = callbacks.remove(callback)
+ listener?.let {
+ deviceStateManager.unregisterCallback(it)
+ }
+ }
+
+ private inner class FoldStateListener(
+ context: Context,
+ listener: FoldCallback
+ ) : DeviceStateManager.FoldStateListener(context, { listener.onFoldUpdated(it) })
+}
diff --git a/packages/SystemUI/shared/src/com/android/systemui/unfold/system/SystemUnfoldSharedModule.kt b/packages/SystemUI/shared/src/com/android/systemui/unfold/system/SystemUnfoldSharedModule.kt
new file mode 100644
index 000000000000..24ae42ae4db2
--- /dev/null
+++ b/packages/SystemUI/shared/src/com/android/systemui/unfold/system/SystemUnfoldSharedModule.kt
@@ -0,0 +1,61 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the
+ * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package com.android.systemui.unfold.system
+
+import android.os.Handler
+import com.android.systemui.dagger.qualifiers.Main
+import com.android.systemui.dagger.qualifiers.UiBackground
+import com.android.systemui.unfold.config.ResourceUnfoldTransitionConfig
+import com.android.systemui.unfold.config.UnfoldTransitionConfig
+import com.android.systemui.unfold.dagger.UnfoldBackground
+import com.android.systemui.unfold.dagger.UnfoldMain
+import com.android.systemui.unfold.updates.FoldProvider
+import com.android.systemui.unfold.util.CurrentActivityTypeProvider
+import dagger.Binds
+import dagger.Module
+import java.util.concurrent.Executor
+
+/**
+ * Dagger module with system-only dependencies for the unfold animation.
+ * The code that is used to calculate unfold transition progress
+ * depends on some hidden APIs that are not available in normal
+ * apps. In order to re-use this code and use alternative implementations
+ * of these classes in other apps and hidden APIs here.
+ */
+@Module
+abstract class SystemUnfoldSharedModule {
+
+ @Binds
+ abstract fun activityTypeProvider(executor: ActivityManagerActivityTypeProvider):
+ CurrentActivityTypeProvider
+
+ @Binds
+ abstract fun config(config: ResourceUnfoldTransitionConfig): UnfoldTransitionConfig
+
+ @Binds
+ abstract fun foldState(provider: DeviceStateManagerFoldProvider): FoldProvider
+
+ @Binds
+ @UnfoldMain
+ abstract fun mainExecutor(@Main executor: Executor): Executor
+
+ @Binds
+ @UnfoldMain
+ abstract fun mainHandler(@Main handler: Handler): Handler
+
+ @Binds
+ @UnfoldBackground
+ abstract fun backgroundExecutor(@UiBackground executor: Executor): Executor
+}
diff --git a/packages/SystemUI/shared/src/com/android/systemui/unfold/updates/hinge/EmptyHingeAngleProvider.kt b/packages/SystemUI/shared/src/com/android/systemui/unfold/updates/hinge/EmptyHingeAngleProvider.kt
deleted file mode 100644
index b351585de364..000000000000
--- a/packages/SystemUI/shared/src/com/android/systemui/unfold/updates/hinge/EmptyHingeAngleProvider.kt
+++ /dev/null
@@ -1,13 +0,0 @@
-package com.android.systemui.unfold.updates.hinge
-
-import androidx.core.util.Consumer
-
-internal object EmptyHingeAngleProvider : HingeAngleProvider {
- override fun start() {}
-
- override fun stop() {}
-
- override fun removeCallback(listener: Consumer<Float>) {}
-
- override fun addCallback(listener: Consumer<Float>) {}
-}
diff --git a/packages/SystemUI/shared/src/com/android/systemui/unfold/updates/hinge/HingeAngleProvider.kt b/packages/SystemUI/shared/src/com/android/systemui/unfold/updates/hinge/HingeAngleProvider.kt
deleted file mode 100644
index 48a5b12c759a..000000000000
--- a/packages/SystemUI/shared/src/com/android/systemui/unfold/updates/hinge/HingeAngleProvider.kt
+++ /dev/null
@@ -1,19 +0,0 @@
-package com.android.systemui.unfold.updates.hinge
-
-import androidx.core.util.Consumer
-import com.android.systemui.statusbar.policy.CallbackController
-
-/**
- * Emits device hinge angle values (angle between two integral parts of the device).
- *
- * The hinge angle could be from 0 to 360 degrees inclusive. For foldable devices usually 0
- * corresponds to fully closed (folded) state and 180 degrees corresponds to fully open (flat)
- * state.
- */
-interface HingeAngleProvider : CallbackController<Consumer<Float>> {
- fun start()
- fun stop()
-}
-
-const val FULLY_OPEN_DEGREES = 180f
-const val FULLY_CLOSED_DEGREES = 0f
diff --git a/packages/SystemUI/shared/src/com/android/systemui/unfold/util/NaturalRotationUnfoldProgressProvider.kt b/packages/SystemUI/shared/src/com/android/systemui/unfold/util/NaturalRotationUnfoldProgressProvider.kt
index 53c528ff24a8..ec938b219933 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/unfold/util/NaturalRotationUnfoldProgressProvider.kt
+++ b/packages/SystemUI/shared/src/com/android/systemui/unfold/util/NaturalRotationUnfoldProgressProvider.kt
@@ -1,3 +1,17 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the
+ * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
package com.android.systemui.unfold.util
import android.content.Context
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardHostViewController.java b/packages/SystemUI/src/com/android/keyguard/KeyguardHostViewController.java
index 804d14681812..12fa401d7fea 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardHostViewController.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardHostViewController.java
@@ -71,13 +71,16 @@ public class KeyguardHostViewController extends ViewController<KeyguardHostView>
public void onTrustGrantedWithFlags(int flags, int userId) {
if (userId != KeyguardUpdateMonitor.getCurrentUser()) return;
boolean bouncerVisible = mView.isVisibleToUser();
+ boolean temporaryAndRenewable =
+ (flags & TrustAgentService.FLAG_GRANT_TRUST_TEMPORARY_AND_RENEWABLE)
+ != 0;
boolean initiatedByUser =
(flags & TrustAgentService.FLAG_GRANT_TRUST_INITIATED_BY_USER) != 0;
boolean dismissKeyguard =
(flags & TrustAgentService.FLAG_GRANT_TRUST_DISMISS_KEYGUARD) != 0;
if (initiatedByUser || dismissKeyguard) {
- if (mViewMediatorCallback.isScreenOn()
+ if ((mViewMediatorCallback.isScreenOn() || temporaryAndRenewable)
&& (bouncerVisible || dismissKeyguard)) {
if (!bouncerVisible) {
// The trust agent dismissed the keyguard without the user proving
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardPasswordView.java b/packages/SystemUI/src/com/android/keyguard/KeyguardPasswordView.java
index 5c9f5dba1f3f..2cc5ccdc3fa1 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardPasswordView.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardPasswordView.java
@@ -32,6 +32,7 @@ import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Insets;
import android.graphics.Rect;
+import android.os.Trace;
import android.util.AttributeSet;
import android.view.WindowInsetsAnimationControlListener;
import android.view.WindowInsetsAnimationController;
@@ -44,6 +45,7 @@ import androidx.annotation.Nullable;
import com.android.internal.widget.LockscreenCredential;
import com.android.internal.widget.TextViewInputDisabler;
+import com.android.systemui.DejankUtils;
import com.android.systemui.R;
import com.android.systemui.animation.Interpolators;
/**
@@ -194,9 +196,17 @@ public class KeyguardPasswordView extends KeyguardAbsKeyInputView {
@Override
public void onAnimationEnd(Animator animation) {
- controller.finish(false);
- runOnFinishImeAnimationRunnable();
- finishRunnable.run();
+ // Run this in the next frame since it results in a slow binder call
+ // to InputMethodManager#hideSoftInput()
+ DejankUtils.postAfterTraversal(() -> {
+ Trace.beginSection("KeyguardPasswordView#onAnimationEnd");
+ // // TODO(b/230620476): Make hideSoftInput oneway
+ // controller.finish() eventually calls hideSoftInput
+ controller.finish(false);
+ runOnFinishImeAnimationRunnable();
+ finishRunnable.run();
+ Trace.endSection();
+ });
}
});
anim.setInterpolator(Interpolators.FAST_OUT_LINEAR_IN);
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainer.java b/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainer.java
index f8c0590a8d75..cce516d981a5 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainer.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainer.java
@@ -15,6 +15,8 @@
*/
package com.android.keyguard;
+import static android.app.admin.DevicePolicyResources.Strings.SystemUi.KEYGUARD_DIALOG_FAILED_ATTEMPTS_ALMOST_ERASING_PROFILE;
+import static android.app.admin.DevicePolicyResources.Strings.SystemUi.KEYGUARD_DIALOG_FAILED_ATTEMPTS_ERASING_PROFILE;
import static android.view.WindowInsets.Type.ime;
import static android.view.WindowInsets.Type.systemBars;
import static android.view.WindowInsetsAnimation.Callback.DISPATCH_MODE_STOP;
@@ -32,6 +34,7 @@ import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.app.AlertDialog;
+import android.app.admin.DevicePolicyManager;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
@@ -676,7 +679,11 @@ public class KeyguardSecurityContainer extends FrameLayout {
attempts, remaining);
break;
case USER_TYPE_WORK_PROFILE:
- message = mContext.getString(R.string.kg_failed_attempts_almost_at_erase_profile,
+ message = mContext.getSystemService(DevicePolicyManager.class).getResources()
+ .getString(KEYGUARD_DIALOG_FAILED_ATTEMPTS_ALMOST_ERASING_PROFILE,
+ () -> mContext.getString(
+ R.string.kg_failed_attempts_almost_at_erase_profile,
+ attempts, remaining),
attempts, remaining);
break;
}
@@ -695,7 +702,10 @@ public class KeyguardSecurityContainer extends FrameLayout {
attempts);
break;
case USER_TYPE_WORK_PROFILE:
- message = mContext.getString(R.string.kg_failed_attempts_now_erasing_profile,
+ message = mContext.getSystemService(DevicePolicyManager.class).getResources()
+ .getString(KEYGUARD_DIALOG_FAILED_ATTEMPTS_ERASING_PROFILE,
+ () -> mContext.getString(
+ R.string.kg_failed_attempts_now_erasing_profile, attempts),
attempts);
break;
}
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java b/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java
index 7df3b69667bb..98f3d946256f 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java
@@ -2437,7 +2437,7 @@ public class KeyguardUpdateMonitor implements TrustManager.TrustListener, Dumpab
// Triggers:
final boolean triggerActiveUnlockForAssistant = shouldTriggerActiveUnlockForAssistant();
final boolean awakeKeyguard = mBouncerFullyShown || mUdfpsBouncerShowing
- || (mKeyguardIsVisible && mDeviceInteractive && !mGoingToSleep
+ || (mKeyguardIsVisible && !mGoingToSleep
&& mStatusBarState != StatusBarState.SHADE_LOCKED);
// Gates:
diff --git a/packages/SystemUI/src/com/android/keyguard/LockIconViewController.java b/packages/SystemUI/src/com/android/keyguard/LockIconViewController.java
index d79b1454514e..680b8bd70837 100644
--- a/packages/SystemUI/src/com/android/keyguard/LockIconViewController.java
+++ b/packages/SystemUI/src/com/android/keyguard/LockIconViewController.java
@@ -123,7 +123,7 @@ public class LockIconViewController extends ViewController<LockIconView> impleme
private float mHeightPixels;
private float mWidthPixels;
private int mBottomPaddingPx;
- private int mScaledPaddingPx;
+ private int mDefaultPaddingPx;
private boolean mShowUnlockIcon;
private boolean mShowLockIcon;
@@ -188,7 +188,6 @@ public class LockIconViewController extends ViewController<LockIconView> impleme
protected void onViewAttached() {
updateIsUdfpsEnrolled();
updateConfiguration();
- updateLockIconLocation();
updateKeyguardShowing();
mUserUnlockedWithBiometric = false;
@@ -340,25 +339,27 @@ public class LockIconViewController extends ViewController<LockIconView> impleme
mWidthPixels = bounds.right;
mHeightPixels = bounds.bottom;
mBottomPaddingPx = getResources().getDimensionPixelSize(R.dimen.lock_icon_margin_bottom);
+ mDefaultPaddingPx =
+ getResources().getDimensionPixelSize(R.dimen.lock_icon_padding);
mUnlockedLabel = mView.getContext().getResources().getString(
R.string.accessibility_unlock_button);
mLockedLabel = mView.getContext()
.getResources().getString(R.string.accessibility_lock_icon);
+ updateLockIconLocation();
}
private void updateLockIconLocation() {
+ final float scaleFactor = mAuthController.getScaleFactor();
+ final int scaledPadding = (int) (mDefaultPaddingPx * scaleFactor);
if (mUdfpsSupported) {
- final int defaultPaddingPx =
- getResources().getDimensionPixelSize(R.dimen.lock_icon_padding);
- mScaledPaddingPx = (int) (defaultPaddingPx * mAuthController.getScaleFactor());
mView.setCenterLocation(mAuthController.getUdfpsLocation(),
- mAuthController.getUdfpsRadius(), mScaledPaddingPx);
+ mAuthController.getUdfpsRadius(), scaledPadding);
} else {
mView.setCenterLocation(
new PointF(mWidthPixels / 2,
- mHeightPixels - mBottomPaddingPx - sLockIconRadiusPx),
- sLockIconRadiusPx, mScaledPaddingPx);
+ mHeightPixels - ((mBottomPaddingPx + sLockIconRadiusPx) * scaleFactor)),
+ sLockIconRadiusPx * scaleFactor, scaledPadding);
}
}
@@ -690,7 +691,6 @@ public class LockIconViewController extends ViewController<LockIconView> impleme
mExecutor.execute(() -> {
updateIsUdfpsEnrolled();
updateConfiguration();
- updateLockIconLocation();
});
}
@@ -707,7 +707,7 @@ public class LockIconViewController extends ViewController<LockIconView> impleme
@Override
public void onUdfpsLocationChanged() {
- updateLockIconLocation();
+ updateUdfpsConfig();
}
};
diff --git a/packages/SystemUI/src/com/android/systemui/DisplayCutoutBaseView.kt b/packages/SystemUI/src/com/android/systemui/DisplayCutoutBaseView.kt
index e51a63fbcd10..032a27a6fbcd 100644
--- a/packages/SystemUI/src/com/android/systemui/DisplayCutoutBaseView.kt
+++ b/packages/SystemUI/src/com/android/systemui/DisplayCutoutBaseView.kt
@@ -54,7 +54,7 @@ open class DisplayCutoutBaseView : View, RegionInterceptableView {
@VisibleForTesting(otherwise = VisibleForTesting.PROTECTED)
@JvmField val displayInfo = DisplayInfo()
- @JvmField protected var pendingRotationChange = false
+ @JvmField protected var pendingConfigChange = false
@JvmField protected val paint = Paint()
@JvmField protected val cutoutPath = Path()
@@ -145,7 +145,7 @@ open class DisplayCutoutBaseView : View, RegionInterceptableView {
@VisibleForTesting(otherwise = VisibleForTesting.PROTECTED)
open fun updateCutout() {
- if (pendingRotationChange) {
+ if (pendingConfigChange) {
return
}
cutoutPath.reset()
@@ -225,7 +225,7 @@ open class DisplayCutoutBaseView : View, RegionInterceptableView {
}
protected open fun updateProtectionBoundingPath() {
- if (pendingRotationChange) {
+ if (pendingConfigChange) {
return
}
val m = Matrix()
diff --git a/packages/SystemUI/src/com/android/systemui/ScreenDecorations.java b/packages/SystemUI/src/com/android/systemui/ScreenDecorations.java
index dd312186afee..685c585a52be 100644
--- a/packages/SystemUI/src/com/android/systemui/ScreenDecorations.java
+++ b/packages/SystemUI/src/com/android/systemui/ScreenDecorations.java
@@ -53,6 +53,7 @@ import android.provider.Settings.Secure;
import android.util.DisplayUtils;
import android.util.Log;
import android.util.Size;
+import android.view.Display;
import android.view.DisplayCutout;
import android.view.DisplayCutout.BoundsPosition;
import android.view.DisplayInfo;
@@ -151,12 +152,13 @@ public class ScreenDecorations extends CoreStartable implements Tunable , Dumpab
private SettingObserver mColorInversionSetting;
private DelayableExecutor mExecutor;
private Handler mHandler;
- boolean mPendingRotationChange;
+ boolean mPendingConfigChange;
@VisibleForTesting
String mDisplayUniqueId;
private int mTintColor = Color.BLACK;
@VisibleForTesting
protected DisplayDecorationSupport mHwcScreenDecorationSupport;
+ private Display.Mode mDisplayMode;
private CameraAvailabilityListener.CameraTransitionCallback mCameraTransitionCallback =
new CameraAvailabilityListener.CameraTransitionCallback() {
@@ -324,6 +326,7 @@ public class ScreenDecorations extends CoreStartable implements Tunable , Dumpab
mWindowManager = mContext.getSystemService(WindowManager.class);
mDisplayManager = mContext.getSystemService(DisplayManager.class);
mRotation = mContext.getDisplay().getRotation();
+ mDisplayMode = mContext.getDisplay().getMode();
mDisplayUniqueId = mContext.getDisplay().getUniqueId();
mRoundedCornerResDelegate = new RoundedCornerResDelegate(mContext.getResources(),
mDisplayUniqueId);
@@ -349,8 +352,10 @@ public class ScreenDecorations extends CoreStartable implements Tunable , Dumpab
@Override
public void onDisplayChanged(int displayId) {
final int newRotation = mContext.getDisplay().getRotation();
+ final Display.Mode newDisplayMode = mContext.getDisplay().getMode();
if ((mOverlays != null || mScreenDecorHwcWindow != null)
- && mRotation != newRotation) {
+ && (mRotation != newRotation
+ || displayModeChanged(mDisplayMode, newDisplayMode))) {
// We cannot immediately update the orientation. Otherwise
// WindowManager is still deferring layout until it has finished dispatching
// the config changes, which may cause divergence between what we draw
@@ -358,10 +363,16 @@ public class ScreenDecorations extends CoreStartable implements Tunable , Dumpab
// Instead we wait until either:
// - we are trying to redraw. This because WM resized our window and told us to.
// - the config change has been dispatched, so WM is no longer deferring layout.
- mPendingRotationChange = true;
+ mPendingConfigChange = true;
if (DEBUG) {
- Log.i(TAG, "Rotation changed, deferring " + newRotation + ", staying at "
- + mRotation);
+ if (mRotation != newRotation) {
+ Log.i(TAG, "Rotation changed, deferring " + newRotation
+ + ", staying at " + mRotation);
+ }
+ if (displayModeChanged(mDisplayMode, newDisplayMode)) {
+ Log.i(TAG, "Resolution changed, deferring " + newDisplayMode
+ + ", staying at " + mDisplayMode);
+ }
}
if (mOverlays != null) {
@@ -369,7 +380,8 @@ public class ScreenDecorations extends CoreStartable implements Tunable , Dumpab
if (mOverlays[i] != null) {
final ViewGroup overlayView = mOverlays[i].getRootView();
overlayView.getViewTreeObserver().addOnPreDrawListener(
- new RestartingPreDrawListener(overlayView, i, newRotation));
+ new RestartingPreDrawListener(
+ overlayView, i, newRotation, newDisplayMode));
}
}
}
@@ -379,7 +391,10 @@ public class ScreenDecorations extends CoreStartable implements Tunable , Dumpab
new RestartingPreDrawListener(
mScreenDecorHwcWindow,
-1, // Pass -1 for views with no specific position.
- newRotation));
+ newRotation, newDisplayMode));
+ }
+ if (mScreenDecorHwcLayer != null) {
+ mScreenDecorHwcLayer.pendingConfigChange = true;
}
}
@@ -435,7 +450,7 @@ public class ScreenDecorations extends CoreStartable implements Tunable , Dumpab
};
mDisplayManager.registerDisplayListener(mDisplayListener, mHandler);
- updateOrientation();
+ updateConfiguration();
}
@Nullable
@@ -807,6 +822,17 @@ public class ScreenDecorations extends CoreStartable implements Tunable , Dumpab
}
}
+ private static boolean displayModeChanged(Display.Mode oldMode, Display.Mode newMode) {
+ if (oldMode == null) {
+ return true;
+ }
+
+ // We purposely ignore refresh rate and id changes here, because we don't need to
+ // invalidate for those, and they can trigger the refresh rate to increase
+ return oldMode.getPhysicalWidth() != newMode.getPhysicalWidth()
+ || oldMode.getPhysicalHeight() != newMode.getPhysicalHeight();
+ }
+
private int getOverlayWindowGravity(@BoundsPosition int pos) {
final int rotated = getBoundPositionFromRotation(pos, mRotation);
switch (rotated) {
@@ -913,8 +939,8 @@ public class ScreenDecorations extends CoreStartable implements Tunable , Dumpab
mExecutor.execute(() -> {
int oldRotation = mRotation;
- mPendingRotationChange = false;
- updateOrientation();
+ mPendingConfigChange = false;
+ updateConfiguration();
if (DEBUG) Log.i(TAG, "onConfigChanged from rot " + oldRotation + " to " + mRotation);
setupDecorations();
if (mOverlays != null) {
@@ -941,7 +967,7 @@ public class ScreenDecorations extends CoreStartable implements Tunable , Dumpab
pw.println(" DEBUG_DISABLE_SCREEN_DECORATIONS:" + DEBUG_DISABLE_SCREEN_DECORATIONS);
pw.println(" mIsPrivacyDotEnabled:" + isPrivacyDotEnabled());
pw.println(" isOnlyPrivacyDotInSwLayer:" + isOnlyPrivacyDotInSwLayer());
- pw.println(" mPendingRotationChange:" + mPendingRotationChange);
+ pw.println(" mPendingConfigChange:" + mPendingConfigChange);
if (mHwcScreenDecorationSupport != null) {
pw.println(" mHwcScreenDecorationSupport:");
pw.println(" format="
@@ -957,15 +983,23 @@ public class ScreenDecorations extends CoreStartable implements Tunable , Dumpab
} else {
pw.println(" mScreenDecorHwcLayer: null");
}
- pw.println(" mOverlays(left,top,right,bottom)=("
- + (mOverlays != null && mOverlays[BOUNDS_POSITION_LEFT] != null) + ","
- + (mOverlays != null && mOverlays[BOUNDS_POSITION_TOP] != null) + ","
- + (mOverlays != null && mOverlays[BOUNDS_POSITION_RIGHT] != null) + ","
- + (mOverlays != null && mOverlays[BOUNDS_POSITION_BOTTOM] != null) + ")");
+ if (mOverlays != null) {
+ pw.println(" mOverlays(left,top,right,bottom)=("
+ + (mOverlays[BOUNDS_POSITION_LEFT] != null) + ","
+ + (mOverlays[BOUNDS_POSITION_TOP] != null) + ","
+ + (mOverlays[BOUNDS_POSITION_RIGHT] != null) + ","
+ + (mOverlays[BOUNDS_POSITION_BOTTOM] != null) + ")");
+
+ for (int i = BOUNDS_POSITION_LEFT; i < BOUNDS_POSITION_LENGTH; i++) {
+ if (mOverlays[i] != null) {
+ mOverlays[i].dump(pw, getWindowTitleByPos(i));
+ }
+ }
+ }
mRoundedCornerResDelegate.dump(pw, args);
}
- private void updateOrientation() {
+ private void updateConfiguration() {
Preconditions.checkState(mHandler.getLooper().getThread() == Thread.currentThread(),
"must call on " + mHandler.getLooper().getThread()
+ ", but was " + Thread.currentThread());
@@ -974,11 +1008,14 @@ public class ScreenDecorations extends CoreStartable implements Tunable , Dumpab
if (mRotation != newRotation) {
mDotViewController.setNewRotation(newRotation);
}
+ final Display.Mode newMod = mContext.getDisplay().getMode();
- if (!mPendingRotationChange && newRotation != mRotation) {
+ if (!mPendingConfigChange
+ && (newRotation != mRotation || displayModeChanged(mDisplayMode, newMod))) {
mRotation = newRotation;
+ mDisplayMode = newMod;
if (mScreenDecorHwcLayer != null) {
- mScreenDecorHwcLayer.pendingRotationChange = false;
+ mScreenDecorHwcLayer.pendingConfigChange = false;
mScreenDecorHwcLayer.updateRotation(mRotation);
updateHwLayerRoundedCornerExistAndSize();
updateHwLayerRoundedCornerDrawable();
@@ -1189,7 +1226,7 @@ public class ScreenDecorations extends CoreStartable implements Tunable , Dumpab
@VisibleForTesting(otherwise = VisibleForTesting.PROTECTED)
@Override
public void updateCutout() {
- if (!isAttachedToWindow() || pendingRotationChange) {
+ if (!isAttachedToWindow() || pendingConfigChange) {
return;
}
mPosition = getBoundPositionFromRotation(mInitialPosition, mRotation);
@@ -1330,40 +1367,47 @@ public class ScreenDecorations extends CoreStartable implements Tunable , Dumpab
private final View mView;
private final int mTargetRotation;
+ private final Display.Mode mTargetDisplayMode;
// Pass -1 for ScreenDecorHwcLayer since it's a fullscreen window and has no specific
// position.
private final int mPosition;
private RestartingPreDrawListener(View view, @BoundsPosition int position,
- int targetRotation) {
+ int targetRotation, Display.Mode targetDisplayMode) {
mView = view;
mTargetRotation = targetRotation;
+ mTargetDisplayMode = targetDisplayMode;
mPosition = position;
}
@Override
public boolean onPreDraw() {
mView.getViewTreeObserver().removeOnPreDrawListener(this);
-
- if (mTargetRotation == mRotation) {
+ if (mTargetRotation == mRotation
+ && !displayModeChanged(mDisplayMode, mTargetDisplayMode)) {
if (DEBUG) {
final String title = mPosition < 0 ? "ScreenDecorHwcLayer"
: getWindowTitleByPos(mPosition);
Log.i(TAG, title + " already in target rot "
- + mTargetRotation + ", allow draw without restarting it");
+ + mTargetRotation + " and in target resolution "
+ + mTargetDisplayMode.getPhysicalWidth() + "x"
+ + mTargetDisplayMode.getPhysicalHeight()
+ + ", allow draw without restarting it");
}
return true;
}
- mPendingRotationChange = false;
+ mPendingConfigChange = false;
// This changes the window attributes - we need to restart the traversal for them to
// take effect.
- updateOrientation();
+ updateConfiguration();
if (DEBUG) {
final String title = mPosition < 0 ? "ScreenDecorHwcLayer"
: getWindowTitleByPos(mPosition);
Log.i(TAG, title
- + " restarting listener fired, restarting draw for rot " + mRotation);
+ + " restarting listener fired, restarting draw for rot " + mRotation
+ + ", resolution " + mDisplayMode.getPhysicalWidth() + "x"
+ + mDisplayMode.getPhysicalHeight());
}
mView.invalidate();
return false;
@@ -1371,8 +1415,8 @@ public class ScreenDecorations extends CoreStartable implements Tunable , Dumpab
}
/**
- * A pre-draw listener, that validates that the rotation we draw in matches the displays
- * rotation before continuing the draw.
+ * A pre-draw listener, that validates that the rotation and display resolution we draw in
+ * matches the display's rotation and resolution before continuing the draw.
*
* This is to prevent a race condition, where we have not received the display changed event
* yet, and would thus draw in an old orientation.
@@ -1388,10 +1432,20 @@ public class ScreenDecorations extends CoreStartable implements Tunable , Dumpab
@Override
public boolean onPreDraw() {
final int displayRotation = mContext.getDisplay().getRotation();
- if (displayRotation != mRotation && !mPendingRotationChange) {
+ final Display.Mode displayMode = mContext.getDisplay().getMode();
+ if (displayRotation != mRotation && displayModeChanged(mDisplayMode, displayMode)
+ && !mPendingConfigChange) {
if (DEBUG) {
- Log.i(TAG, "Drawing rot " + mRotation + ", but display is at rot "
- + displayRotation + ". Restarting draw");
+ if (displayRotation != mRotation) {
+ Log.i(TAG, "Drawing rot " + mRotation + ", but display is at rot "
+ + displayRotation + ". Restarting draw");
+ }
+ if (displayModeChanged(mDisplayMode, displayMode)) {
+ Log.i(TAG, "Drawing at " + mDisplayMode.getPhysicalWidth()
+ + "x" + mDisplayMode.getPhysicalHeight() + ", but display is at "
+ + displayMode.getPhysicalWidth() + "x"
+ + displayMode.getPhysicalHeight() + ". Restarting draw");
+ }
}
mView.invalidate();
return false;
diff --git a/packages/SystemUI/src/com/android/systemui/SwipeHelper.java b/packages/SystemUI/src/com/android/systemui/SwipeHelper.java
index 3d0c08bb5237..fe6dbe5de8f0 100644
--- a/packages/SystemUI/src/com/android/systemui/SwipeHelper.java
+++ b/packages/SystemUI/src/com/android/systemui/SwipeHelper.java
@@ -46,6 +46,8 @@ import com.android.systemui.plugins.statusbar.NotificationMenuRowPlugin;
import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
import com.android.wm.shell.animation.FlingAnimationUtils;
+import java.util.function.Consumer;
+
public class SwipeHelper implements Gefingerpoken {
static final String TAG = "com.android.systemui.SwipeHelper";
private static final boolean DEBUG = false;
@@ -399,7 +401,7 @@ public class SwipeHelper implements Gefingerpoken {
* @param useAccelerateInterpolator Should an accelerating Interpolator be used
* @param fixedDuration If not 0, this exact duration will be taken
*/
- public void dismissChild(final View animView, float velocity, final Runnable endAction,
+ public void dismissChild(final View animView, float velocity, final Consumer<Boolean> endAction,
long delay, boolean useAccelerateInterpolator, long fixedDuration,
boolean isDismissAll) {
final boolean canBeDismissed = mCallback.canChildBeDismissed(animView);
@@ -487,7 +489,7 @@ public class SwipeHelper implements Gefingerpoken {
resetSwipeState();
}
if (endAction != null) {
- endAction.run();
+ endAction.accept(mCancelled);
}
if (!mDisableHwLayers) {
animView.setLayerType(View.LAYER_TYPE_NONE, null);
diff --git a/packages/SystemUI/src/com/android/systemui/SystemUIFactory.java b/packages/SystemUI/src/com/android/systemui/SystemUIFactory.java
index d70ea9bba936..2dade21caca7 100644
--- a/packages/SystemUI/src/com/android/systemui/SystemUIFactory.java
+++ b/packages/SystemUI/src/com/android/systemui/SystemUIFactory.java
@@ -119,7 +119,6 @@ public class SystemUIFactory {
.setBubbles(mWMComponent.getBubbles())
.setHideDisplayCutout(mWMComponent.getHideDisplayCutout())
.setShellCommandHandler(mWMComponent.getShellCommandHandler())
- .setAppPairs(mWMComponent.getAppPairs())
.setTaskViewFactory(mWMComponent.getTaskViewFactory())
.setTransitions(mWMComponent.getTransitions())
.setStartingSurface(mWMComponent.getStartingSurface())
@@ -139,7 +138,6 @@ public class SystemUIFactory {
.setBubbles(Optional.ofNullable(null))
.setHideDisplayCutout(Optional.ofNullable(null))
.setShellCommandHandler(Optional.ofNullable(null))
- .setAppPairs(Optional.ofNullable(null))
.setTaskViewFactory(Optional.ofNullable(null))
.setTransitions(new ShellTransitions() {})
.setDisplayAreaHelper(Optional.ofNullable(null))
diff --git a/packages/SystemUI/src/com/android/systemui/appops/AppOpsControllerImpl.java b/packages/SystemUI/src/com/android/systemui/appops/AppOpsControllerImpl.java
index 56fbe6d9bf14..6b859763eb6f 100644
--- a/packages/SystemUI/src/com/android/systemui/appops/AppOpsControllerImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/appops/AppOpsControllerImpl.java
@@ -102,6 +102,7 @@ public class AppOpsControllerImpl extends BroadcastReceiver implements AppOpsCon
AppOpsManager.OP_PHONE_CALL_CAMERA,
AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
AppOpsManager.OP_RECORD_AUDIO,
+ AppOpsManager.OP_RECEIVE_AMBIENT_TRIGGER_AUDIO,
AppOpsManager.OP_PHONE_CALL_MICROPHONE,
AppOpsManager.OP_COARSE_LOCATION,
AppOpsManager.OP_FINE_LOCATION
@@ -375,7 +376,7 @@ public class AppOpsControllerImpl extends BroadcastReceiver implements AppOpsCon
Log.w(TAG, String.format("onActiveChanged(%d,%d,%s,%s,%d,%d)", code, uid, packageName,
Boolean.toString(active), attributionChainId, attributionFlags));
}
- if (attributionChainId != AppOpsManager.ATTRIBUTION_CHAIN_ID_NONE
+ if (active && attributionChainId != AppOpsManager.ATTRIBUTION_CHAIN_ID_NONE
&& attributionFlags != AppOpsManager.ATTRIBUTION_FLAGS_NONE
&& (attributionFlags & AppOpsManager.ATTRIBUTION_FLAG_ACCESSOR) == 0
&& (attributionFlags & AppOpsManager.ATTRIBUTION_FLAG_TRUSTED) == 0) {
@@ -535,7 +536,8 @@ public class AppOpsControllerImpl extends BroadcastReceiver implements AppOpsCon
}
private boolean isOpMicrophone(int op) {
- return op == AppOpsManager.OP_RECORD_AUDIO || op == AppOpsManager.OP_PHONE_CALL_MICROPHONE;
+ return op == AppOpsManager.OP_RECORD_AUDIO || op == AppOpsManager.OP_PHONE_CALL_MICROPHONE
+ || op == AppOpsManager.OP_RECEIVE_AMBIENT_TRIGGER_AUDIO;
}
protected class H extends Handler {
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/AuthBiometricFingerprintView.kt b/packages/SystemUI/src/com/android/systemui/biometrics/AuthBiometricFingerprintView.kt
index 368bc3aadb70..ebed2962a33b 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/AuthBiometricFingerprintView.kt
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/AuthBiometricFingerprintView.kt
@@ -22,6 +22,7 @@ import android.util.Log
import android.widget.FrameLayout
import android.widget.TextView
import com.android.systemui.R
+import com.android.systemui.biometrics.AuthController.ScaleFactorProvider
private const val TAG = "AuthBiometricFingerprintView"
@@ -35,6 +36,7 @@ open class AuthBiometricFingerprintView(
private set
private var udfpsAdapter: UdfpsDialogMeasureAdapter? = null
+ private var scaleFactorProvider: ScaleFactorProvider? = null
/** Set the [sensorProps] of this sensor so the view can be customized prior to layout. */
fun setSensorProperties(sensorProps: FingerprintSensorPropertiesInternal) {
@@ -42,9 +44,15 @@ open class AuthBiometricFingerprintView(
udfpsAdapter = if (isUdfps) UdfpsDialogMeasureAdapter(this, sensorProps) else null
}
+ fun setScaleFactorProvider(scaleProvider: ScaleFactorProvider?) {
+ scaleFactorProvider = scaleProvider
+ }
+
override fun onMeasureInternal(width: Int, height: Int): AuthDialog.LayoutParams {
val layoutParams = super.onMeasureInternal(width, height)
- return udfpsAdapter?.onMeasureInternal(width, height, layoutParams) ?: layoutParams
+ val scale = scaleFactorProvider?.provide() ?: 1.0f
+ return udfpsAdapter?.onMeasureInternal(width, height, layoutParams,
+ scale) ?: layoutParams
}
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/AuthContainerView.java b/packages/SystemUI/src/com/android/systemui/biometrics/AuthContainerView.java
index 233f3648aeb3..3c2de895bf26 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/AuthContainerView.java
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/AuthContainerView.java
@@ -56,6 +56,7 @@ import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.widget.LockPatternUtils;
import com.android.systemui.R;
import com.android.systemui.animation.Interpolators;
+import com.android.systemui.biometrics.AuthController.ScaleFactorProvider;
import com.android.systemui.dagger.qualifiers.Background;
import com.android.systemui.keyguard.WakefulnessLifecycle;
import com.android.systemui.util.concurrency.DelayableExecutor;
@@ -133,6 +134,7 @@ public class AuthContainerView extends LinearLayout
long mRequestId = -1;
boolean mSkipAnimation = false;
@BiometricMultiSensorMode int mMultiSensorConfig = BIOMETRIC_MULTI_SENSOR_DEFAULT;
+ ScaleFactorProvider mScaleProvider;
}
public static class Builder {
@@ -196,6 +198,11 @@ public class AuthContainerView extends LinearLayout
return this;
}
+ public Builder setScaleFactorProvider(ScaleFactorProvider scaleProvider) {
+ mConfig.mScaleProvider = scaleProvider;
+ return this;
+ }
+
public AuthContainerView build(@Background DelayableExecutor bgExecutor, int[] sensorIds,
@Nullable List<FingerprintSensorPropertiesInternal> fpProps,
@Nullable List<FaceSensorPropertiesInternal> faceProps,
@@ -296,12 +303,14 @@ public class AuthContainerView extends LinearLayout
(AuthBiometricFingerprintAndFaceView) layoutInflater.inflate(
R.layout.auth_biometric_fingerprint_and_face_view, null, false);
fingerprintAndFaceView.setSensorProperties(fpProperties);
+ fingerprintAndFaceView.setScaleFactorProvider(config.mScaleProvider);
mBiometricView = fingerprintAndFaceView;
} else if (fpProperties != null) {
final AuthBiometricFingerprintView fpView =
(AuthBiometricFingerprintView) layoutInflater.inflate(
R.layout.auth_biometric_fingerprint_view, null, false);
fpView.setSensorProperties(fpProperties);
+ fpView.setScaleFactorProvider(config.mScaleProvider);
mBiometricView = fpView;
} else if (faceProperties != null) {
mBiometricView = (AuthBiometricFaceView) layoutInflater.inflate(
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/AuthController.java b/packages/SystemUI/src/com/android/systemui/biometrics/AuthController.java
index 75339aaa843d..8c59f373ec91 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/AuthController.java
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/AuthController.java
@@ -484,7 +484,13 @@ public class AuthController extends CoreStartable implements CommandQueue.Callba
if (mFaceProps == null || mFaceAuthSensorLocation == null) {
return null;
}
- return new PointF(mFaceAuthSensorLocation.x, mFaceAuthSensorLocation.y);
+ DisplayInfo displayInfo = new DisplayInfo();
+ mContext.getDisplay().getDisplayInfo(displayInfo);
+ final float scaleFactor = android.util.DisplayUtils.getPhysicalPixelDisplaySizeRatio(
+ mStableDisplaySize.x, mStableDisplaySize.y, displayInfo.getNaturalWidth(),
+ displayInfo.getNaturalHeight());
+ return new PointF(mFaceAuthSensorLocation.x * scaleFactor,
+ mFaceAuthSensorLocation.y * scaleFactor);
}
/**
@@ -1031,11 +1037,24 @@ public class AuthController extends CoreStartable implements CommandQueue.Callba
.setOperationId(operationId)
.setRequestId(requestId)
.setMultiSensorConfig(multiSensorConfig)
+ .setScaleFactorProvider(() -> {
+ return getScaleFactor();
+ })
.build(bgExecutor, sensorIds, mFpProps, mFaceProps, wakefulnessLifecycle,
userManager, lockPatternUtils);
}
/**
+ * Provides a float that represents the resolution scale(if the controller is for UDFPS).
+ */
+ public interface ScaleFactorProvider {
+ /**
+ * Returns a float representing the scaled resolution(if the controller if for UDFPS).
+ */
+ float provide();
+ }
+
+ /**
* AuthController callback used to receive signal for when biometric authenticators are
* registered.
*/
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsAnimationViewController.kt b/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsAnimationViewController.kt
index 5cfbdb0caf2d..742c65c2f854 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsAnimationViewController.kt
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsAnimationViewController.kt
@@ -192,4 +192,9 @@ abstract class UdfpsAnimationViewController<T : UdfpsAnimationView>(
* Called on touches outside of the view if listenForTouchesOutsideView returns true
*/
open fun onTouchOutsideView() {}
+
+ /**
+ * Called when a view should announce an accessibility event.
+ */
+ open fun doAnnounceForAccessibility(str: String) {}
} \ No newline at end of file
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsController.java b/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsController.java
index f0af858c3a74..c0e1be1d8283 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsController.java
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsController.java
@@ -51,7 +51,6 @@ import android.view.accessibility.AccessibilityManager;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.util.LatencyTracker;
-import com.android.keyguard.ActiveUnlockConfig;
import com.android.keyguard.KeyguardUpdateMonitor;
import com.android.systemui.animation.ActivityLaunchAnimator;
import com.android.systemui.broadcast.BroadcastSender;
@@ -382,6 +381,27 @@ public class UdfpsController implements DozeReceiver {
&& mOverlayParams.getSensorBounds().contains((int) x, (int) y);
}
+ private Point getTouchInNativeCoordinates(@NonNull MotionEvent event, int idx) {
+ Point portraitTouch = new Point(
+ (int) event.getRawX(idx),
+ (int) event.getRawY(idx)
+ );
+ final int rot = mOverlayParams.getRotation();
+ if (rot == Surface.ROTATION_90 || rot == Surface.ROTATION_270) {
+ RotationUtils.rotatePoint(portraitTouch,
+ RotationUtils.deltaRotation(rot, Surface.ROTATION_0),
+ mOverlayParams.getLogicalDisplayWidth(),
+ mOverlayParams.getLogicalDisplayHeight()
+ );
+ }
+
+ // Scale the coordinates to native resolution.
+ final float scale = mOverlayParams.getScaleFactor();
+ portraitTouch.x = (int) (portraitTouch.x / scale);
+ portraitTouch.y = (int) (portraitTouch.y / scale);
+ return portraitTouch;
+ }
+
@VisibleForTesting
boolean onTouch(long requestId, @NonNull MotionEvent event, boolean fromUdfpsView) {
if (mOverlay == null) {
@@ -435,6 +455,7 @@ public class UdfpsController implements DozeReceiver {
mKeyguardViewManager.notifyKeyguardAuthenticated(false /* strongAuth */);
mAttemptedToDismissKeyguard = true;
}
+
Trace.endSection();
break;
@@ -458,6 +479,8 @@ public class UdfpsController implements DozeReceiver {
mAttemptedToDismissKeyguard = true;
break;
}
+ // Map the touch to portrait mode if the device is in landscape mode.
+ final Point scaledTouch = getTouchInNativeCoordinates(event, idx);
if (actionMoveWithinSensorArea) {
if (mVelocityTracker == null) {
// touches could be injected, so the velocity tracker may not have
@@ -478,28 +501,13 @@ public class UdfpsController implements DozeReceiver {
final long sinceLastLog = mSystemClock.elapsedRealtime() - mTouchLogTime;
if (!isIlluminationRequested && !mAcquiredReceived
&& !exceedsVelocityThreshold) {
- // Map the touch to portrait mode if the device is in landscape mode.
- Point portraitTouch = new Point(
- (int) event.getRawX(idx),
- (int) event.getRawY(idx)
- );
- final int rot = mOverlayParams.getRotation();
- if (rot == Surface.ROTATION_90 || rot == Surface.ROTATION_270) {
- RotationUtils.rotatePoint(portraitTouch,
- RotationUtils.deltaRotation(rot, Surface.ROTATION_0),
- mOverlayParams.getLogicalDisplayWidth(),
- mOverlayParams.getLogicalDisplayHeight()
- );
- }
- // Scale the coordinates to native resolution.
final float scale = mOverlayParams.getScaleFactor();
- int scaledX = (int) (portraitTouch.x / scale);
- int scaledY = (int) (portraitTouch.y / scale);
float scaledMinor = minor / scale;
float scaledMajor = major / scale;
- onFingerDown(requestId, scaledX, scaledY, scaledMinor, scaledMajor);
+ onFingerDown(requestId, scaledTouch.x, scaledTouch.y, scaledMinor,
+ scaledMajor);
Log.v(TAG, "onTouch | finger down: " + touchInfo);
mTouchLogTime = mSystemClock.elapsedRealtime();
mPowerManager.userActivity(mSystemClock.uptimeMillis(),
@@ -512,6 +520,24 @@ public class UdfpsController implements DozeReceiver {
} else {
Log.v(TAG, "onTouch | finger outside");
onFingerUp(requestId, udfpsView);
+ // Maybe announce for accessibility.
+ mFgExecutor.execute(() -> {
+ if (mOverlay == null) {
+ Log.e(TAG, "touch outside sensor area received"
+ + "but serverRequest is null");
+ return;
+ }
+ // Scale the coordinates to native resolution.
+ final float scale = mOverlayParams.getScaleFactor();
+ final float scaledSensorX =
+ mOverlayParams.getSensorBounds().centerX() / scale;
+ final float scaledSensorY =
+ mOverlayParams.getSensorBounds().centerY() / scale;
+
+ mOverlay.onTouchOutsideOfSensorArea(
+ scaledTouch.x, scaledTouch.y, scaledSensorX, scaledSensorY,
+ mOverlayParams.getRotation());
+ });
}
}
Trace.endSection();
@@ -808,10 +834,6 @@ public class UdfpsController implements DozeReceiver {
if (!mKeyguardUpdateMonitor.isFaceDetectionRunning()) {
mKeyguardUpdateMonitor.requestFaceAuth(/* userInitiatedRequest */ false);
}
-
- mKeyguardUpdateMonitor.requestActiveUnlock(
- ActiveUnlockConfig.ACTIVE_UNLOCK_REQUEST_ORIGIN.UNLOCK_INTENT,
- "udfpsFingerDown");
}
mOnFingerDown = true;
if (mAlternateTouchProvider != null) {
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsControllerOverlay.kt b/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsControllerOverlay.kt
index faa93a5a2ad3..37db2bd51238 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsControllerOverlay.kt
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsControllerOverlay.kt
@@ -130,6 +130,8 @@ class UdfpsControllerOverlay(
val animationViewController: UdfpsAnimationViewController<*>?
get() = overlayView?.animationViewController
+ private var touchExplorationEnabled = false
+
/** Show the overlay or return false and do nothing if it is already showing. */
@SuppressLint("ClickableViewAccessibility")
fun show(controller: UdfpsController, params: UdfpsOverlayParams): Boolean {
@@ -154,14 +156,16 @@ class UdfpsControllerOverlay(
}
windowManager.addView(this, coreLayoutParams.updateDimensions(animation))
-
+ touchExplorationEnabled = accessibilityManager.isTouchExplorationEnabled
overlayTouchListener = TouchExplorationStateChangeListener {
if (accessibilityManager.isTouchExplorationEnabled) {
setOnHoverListener { v, event -> onTouch(v, event, true) }
setOnTouchListener(null)
+ touchExplorationEnabled = true
} else {
setOnHoverListener(null)
setOnTouchListener { v, event -> onTouch(v, event, true) }
+ touchExplorationEnabled = false
}
}
accessibilityManager.addTouchExplorationStateChangeListener(
@@ -179,7 +183,7 @@ class UdfpsControllerOverlay(
return false
}
- private fun inflateUdfpsAnimation(
+ fun inflateUdfpsAnimation(
view: UdfpsView,
controller: UdfpsController
): UdfpsAnimationViewController<*>? {
@@ -278,6 +282,88 @@ class UdfpsControllerOverlay(
enrollHelper?.onEnrollmentHelp()
}
+ /**
+ * This function computes the angle of touch relative to the sensor and maps
+ * the angle to a list of help messages which are announced if accessibility is enabled.
+ *
+ */
+ fun onTouchOutsideOfSensorArea(
+ touchX: Float,
+ touchY: Float,
+ sensorX: Float,
+ sensorY: Float,
+ rotation: Int
+ ) {
+
+ if (!touchExplorationEnabled) {
+ return
+ }
+ val touchHints =
+ context.resources.getStringArray(R.array.udfps_accessibility_touch_hints)
+ if (touchHints.size != 4) {
+ Log.e(TAG, "expected exactly 4 touch hints, got $touchHints.size?")
+ return
+ }
+ val theStr = onTouchOutsideOfSensorAreaImpl(touchX, touchY, sensorX, sensorY, rotation)
+ Log.v(TAG, "Announcing touch outside : " + theStr)
+ animationViewController?.doAnnounceForAccessibility(theStr)
+ }
+
+ /**
+ * This function computes the angle of touch relative to the sensor and maps
+ * the angle to a list of help messages which are announced if accessibility is enabled.
+ *
+ * There are 4 quadrants of the circle (90 degree arcs)
+ *
+ * [315, 360] && [0, 45) -> touchHints[0] = "Move Fingerprint to the left"
+ * [45, 135) -> touchHints[1] = "Move Fingerprint down"
+ * And so on.
+ */
+ fun onTouchOutsideOfSensorAreaImpl(
+ touchX: Float,
+ touchY: Float,
+ sensorX: Float,
+ sensorY: Float,
+ rotation: Int
+ ): String {
+ val touchHints =
+ context.resources.getStringArray(R.array.udfps_accessibility_touch_hints)
+
+ val xRelativeToSensor = touchX - sensorX
+ // Touch coordinates are with respect to the upper left corner, so reverse
+ // this calculation
+ val yRelativeToSensor = sensorY - touchY
+
+ var angleInRad =
+ Math.atan2(yRelativeToSensor.toDouble(), xRelativeToSensor.toDouble())
+ // If the radians are negative, that means we are counting clockwise.
+ // So we need to add 360 degrees
+ if (angleInRad < 0.0) {
+ angleInRad += 2.0 * Math.PI
+ }
+ // rad to deg conversion
+ val degrees = Math.toDegrees(angleInRad)
+
+ val degreesPerBucket = 360.0 / touchHints.size
+ val halfBucketDegrees = degreesPerBucket / 2.0
+ // The mapping should be as follows
+ // [315, 360] && [0, 45] -> 0
+ // [45, 135] -> 1
+ var index = (((degrees + halfBucketDegrees) % 360) / degreesPerBucket).toInt()
+ index %= touchHints.size
+
+ // A rotation of 90 degrees corresponds to increasing the index by 1.
+ if (rotation == Surface.ROTATION_90) {
+ index = (index + 1) % touchHints.size
+ }
+
+ if (rotation == Surface.ROTATION_270) {
+ index = (index + 3) % touchHints.size
+ }
+
+ return touchHints[index]
+ }
+
/** Cancel this request. */
fun cancel() {
try {
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsDialogMeasureAdapter.java b/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsDialogMeasureAdapter.java
index 8de721352069..2ab97e7cbf23 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsDialogMeasureAdapter.java
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsDialogMeasureAdapter.java
@@ -64,15 +64,16 @@ public class UdfpsDialogMeasureAdapter {
@NonNull
AuthDialog.LayoutParams onMeasureInternal(
- int width, int height, @NonNull AuthDialog.LayoutParams layoutParams) {
+ int width, int height, @NonNull AuthDialog.LayoutParams layoutParams,
+ float scaleFactor) {
final int displayRotation = mView.getDisplay().getRotation();
switch (displayRotation) {
case Surface.ROTATION_0:
- return onMeasureInternalPortrait(width, height);
+ return onMeasureInternalPortrait(width, height, scaleFactor);
case Surface.ROTATION_90:
case Surface.ROTATION_270:
- return onMeasureInternalLandscape(width, height);
+ return onMeasureInternalLandscape(width, height, scaleFactor);
default:
Log.e(TAG, "Unsupported display rotation: " + displayRotation);
return layoutParams;
@@ -90,7 +91,8 @@ public class UdfpsDialogMeasureAdapter {
}
@NonNull
- private AuthDialog.LayoutParams onMeasureInternalPortrait(int width, int height) {
+ private AuthDialog.LayoutParams onMeasureInternalPortrait(int width, int height,
+ float scaleFactor) {
final WindowMetrics windowMetrics = mWindowManager.getMaximumWindowMetrics();
// Figure out where the bottom of the sensor anim should be.
@@ -101,12 +103,13 @@ public class UdfpsDialogMeasureAdapter {
final Insets navbarInsets = getNavbarInsets(windowMetrics);
mBottomSpacerHeight = calculateBottomSpacerHeightForPortrait(
mSensorProps, displayHeight, textIndicatorHeight, buttonBarHeight,
- dialogMargin, navbarInsets.bottom);
+ dialogMargin, navbarInsets.bottom, scaleFactor);
// Go through each of the children and do the custom measurement.
int totalHeight = 0;
final int numChildren = mView.getChildCount();
- final int sensorDiameter = mSensorProps.getLocation().sensorRadius * 2;
+ final int sensorDiameter =
+ (int) (scaleFactor * mSensorProps.getLocation().sensorRadius * 2);
for (int i = 0; i < numChildren; i++) {
final View child = mView.getChildAt(i);
if (child.getId() == R.id.biometric_icon_frame) {
@@ -176,7 +179,8 @@ public class UdfpsDialogMeasureAdapter {
}
@NonNull
- private AuthDialog.LayoutParams onMeasureInternalLandscape(int width, int height) {
+ private AuthDialog.LayoutParams onMeasureInternalLandscape(int width, int height,
+ float scaleFactor) {
final WindowMetrics windowMetrics = mWindowManager.getMaximumWindowMetrics();
// Find the spacer height needed to vertically align the icon with the sensor.
@@ -197,9 +201,10 @@ public class UdfpsDialogMeasureAdapter {
final int dialogMargin = getDialogMarginPx();
final int horizontalInset = navbarInsets.left + navbarInsets.right;
final int horizontalSpacerWidth = calculateHorizontalSpacerWidthForLandscape(
- mSensorProps, displayWidth, dialogMargin, horizontalInset);
+ mSensorProps, displayWidth, dialogMargin, horizontalInset, scaleFactor);
- final int sensorDiameter = mSensorProps.getLocation().sensorRadius * 2;
+ final int sensorDiameter =
+ (int) (scaleFactor * mSensorProps.getLocation().sensorRadius * 2);
final int remeasuredWidth = sensorDiameter + 2 * horizontalSpacerWidth;
int remeasuredHeight = 0;
@@ -281,11 +286,11 @@ public class UdfpsDialogMeasureAdapter {
static int calculateBottomSpacerHeightForPortrait(
@NonNull FingerprintSensorPropertiesInternal sensorProperties, int displayHeightPx,
int textIndicatorHeightPx, int buttonBarHeightPx, int dialogMarginPx,
- int navbarBottomInsetPx) {
+ int navbarBottomInsetPx, float scaleFactor) {
final SensorLocationInternal location = sensorProperties.getLocation();
final int sensorDistanceFromBottom = displayHeightPx
- - location.sensorLocationY
- - location.sensorRadius;
+ - (int) (scaleFactor * location.sensorLocationY)
+ - (int) (scaleFactor * location.sensorRadius);
final int spacerHeight = sensorDistanceFromBottom
- textIndicatorHeightPx
@@ -298,7 +303,8 @@ public class UdfpsDialogMeasureAdapter {
+ ", Distance from bottom: " + sensorDistanceFromBottom
+ ", Bottom margin: " + dialogMarginPx
+ ", Navbar bottom inset: " + navbarBottomInsetPx
- + ", Bottom spacer height (portrait): " + spacerHeight);
+ + ", Bottom spacer height (portrait): " + spacerHeight
+ + ", Scale Factor: " + scaleFactor);
}
return spacerHeight;
@@ -346,11 +352,11 @@ public class UdfpsDialogMeasureAdapter {
@VisibleForTesting
static int calculateHorizontalSpacerWidthForLandscape(
@NonNull FingerprintSensorPropertiesInternal sensorProperties, int displayWidthPx,
- int dialogMarginPx, int navbarHorizontalInsetPx) {
+ int dialogMarginPx, int navbarHorizontalInsetPx, float scaleFactor) {
final SensorLocationInternal location = sensorProperties.getLocation();
final int sensorDistanceFromEdge = displayWidthPx
- - location.sensorLocationY
- - location.sensorRadius;
+ - (int) (scaleFactor * location.sensorLocationY)
+ - (int) (scaleFactor * location.sensorRadius);
final int horizontalPadding = sensorDistanceFromEdge
- dialogMarginPx
@@ -361,7 +367,8 @@ public class UdfpsDialogMeasureAdapter {
+ ", Distance from edge: " + sensorDistanceFromEdge
+ ", Dialog margin: " + dialogMarginPx
+ ", Navbar horizontal inset: " + navbarHorizontalInsetPx
- + ", Horizontal spacer width (landscape): " + horizontalPadding);
+ + ", Horizontal spacer width (landscape): " + horizontalPadding
+ + ", Scale Factor: " + scaleFactor);
}
return horizontalPadding;
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsEnrollViewController.java b/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsEnrollViewController.java
index 2ed60e555c58..0b7bddee41fa 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsEnrollViewController.java
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsEnrollViewController.java
@@ -99,4 +99,10 @@ public class UdfpsEnrollViewController extends UdfpsAnimationViewController<Udfp
public int getPaddingY() {
return mEnrollProgressBarRadius;
}
+
+ @Override
+ public void doAnnounceForAccessibility(String str) {
+ mView.announceForAccessibility(str);
+ }
+
}
diff --git a/packages/SystemUI/src/com/android/systemui/bluetooth/BroadcastDialog.java b/packages/SystemUI/src/com/android/systemui/bluetooth/BroadcastDialog.java
new file mode 100644
index 000000000000..9b7d49883222
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/bluetooth/BroadcastDialog.java
@@ -0,0 +1,134 @@
+/**
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.bluetooth;
+
+import android.content.Context;
+import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageManager;
+import android.os.Bundle;
+import android.text.TextUtils;
+import android.util.Log;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.Window;
+import android.view.WindowManager;
+import android.widget.Button;
+import android.widget.TextView;
+
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.logging.UiEvent;
+import com.android.internal.logging.UiEventLogger;
+import com.android.systemui.R;
+import com.android.systemui.media.MediaDataUtils;
+import com.android.systemui.media.dialog.MediaOutputDialogFactory;
+import com.android.systemui.statusbar.phone.SystemUIDialog;
+
+/**
+ * Dialog for showing le audio broadcasting dialog.
+ */
+public class BroadcastDialog extends SystemUIDialog {
+
+ private static final String TAG = "BroadcastDialog";
+ private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
+
+ private Context mContext;
+ private UiEventLogger mUiEventLogger;
+ @VisibleForTesting
+ protected View mDialogView;
+ private MediaOutputDialogFactory mMediaOutputDialogFactory;
+ private String mSwitchBroadcastApp;
+ private String mOutputPackageName;
+
+ public BroadcastDialog(Context context, MediaOutputDialogFactory mediaOutputDialogFactory,
+ String switchBroadcastApp, String outputPkgName, UiEventLogger uiEventLogger) {
+ super(context);
+ if (DEBUG) {
+ Log.d(TAG, "Init BroadcastDialog");
+ }
+
+ mContext = getContext();
+ mMediaOutputDialogFactory = mediaOutputDialogFactory;
+ mSwitchBroadcastApp = switchBroadcastApp;
+ mOutputPackageName = outputPkgName;
+ mUiEventLogger = uiEventLogger;
+ }
+
+ @Override
+ public void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ if (DEBUG) {
+ Log.d(TAG, "onCreate");
+ }
+
+ mUiEventLogger.log(BroadcastDialogEvent.BROADCAST_DIALOG_SHOW);
+ mDialogView = LayoutInflater.from(mContext).inflate(R.layout.broadcast_dialog, null);
+ final Window window = getWindow();
+ window.setContentView(mDialogView);
+
+ TextView title = mDialogView.requireViewById(R.id.dialog_title);
+ TextView subTitle = mDialogView.requireViewById(R.id.dialog_subtitle);
+ title.setText(
+ mContext.getString(R.string.bt_le_audio_broadcast_dialog_title,
+ MediaDataUtils.getAppLabel(mContext, mOutputPackageName,
+ mContext.getString(
+ R.string.bt_le_audio_broadcast_dialog_unknown_name))));
+ subTitle.setText(
+ mContext.getString(R.string.bt_le_audio_broadcast_dialog_sub_title,
+ mSwitchBroadcastApp));
+
+ Button switchBroadcast = mDialogView.requireViewById(R.id.switch_broadcast);
+ Button changeOutput = mDialogView.requireViewById(R.id.change_output);
+ Button cancelBtn = mDialogView.requireViewById(R.id.cancel);
+ switchBroadcast.setText(mContext.getString(
+ R.string.bt_le_audio_broadcast_dialog_switch_app, mSwitchBroadcastApp), null);
+ changeOutput.setOnClickListener((view) -> {
+ mMediaOutputDialogFactory.create(mOutputPackageName, true, null);
+ dismiss();
+ });
+ cancelBtn.setOnClickListener((view) -> {
+ if (DEBUG) {
+ Log.d(TAG, "BroadcastDialog dismiss.");
+ }
+ dismiss();
+ });
+ }
+
+ @Override
+ public void onWindowFocusChanged(boolean hasFocus) {
+ super.onWindowFocusChanged(hasFocus);
+ if (!hasFocus && isShowing()) {
+ dismiss();
+ }
+ }
+
+ public enum BroadcastDialogEvent implements UiEventLogger.UiEventEnum {
+ @UiEvent(doc = "The Broadcast dialog became visible on the screen.")
+ BROADCAST_DIALOG_SHOW(1062);
+
+ private final int mId;
+
+ BroadcastDialogEvent(int id) {
+ mId = id;
+ }
+
+ @Override
+ public int getId() {
+ return mId;
+ }
+ }
+
+}
diff --git a/packages/SystemUI/src/com/android/systemui/bluetooth/BroadcastDialogController.java b/packages/SystemUI/src/com/android/systemui/bluetooth/BroadcastDialogController.java
new file mode 100644
index 000000000000..8a54345ae28c
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/bluetooth/BroadcastDialogController.java
@@ -0,0 +1,60 @@
+/**
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.bluetooth;
+
+import android.content.Context;
+import android.view.View;
+
+import com.android.internal.logging.UiEventLogger;
+import com.android.systemui.animation.DialogLaunchAnimator;
+import com.android.systemui.dagger.SysUISingleton;
+import com.android.systemui.media.dialog.MediaOutputDialogFactory;
+
+import javax.inject.Inject;
+
+/**
+ * Controller to create BroadcastDialog objects.
+ */
+@SysUISingleton
+public class BroadcastDialogController {
+
+ private Context mContext;
+ private UiEventLogger mUiEventLogger;
+ private DialogLaunchAnimator mDialogLaunchAnimator;
+ private MediaOutputDialogFactory mMediaOutputDialogFactory;
+
+ @Inject
+ public BroadcastDialogController(Context context, UiEventLogger uiEventLogger,
+ DialogLaunchAnimator dialogLaunchAnimator,
+ MediaOutputDialogFactory mediaOutputDialogFactory) {
+ mContext = context;
+ mUiEventLogger = uiEventLogger;
+ mDialogLaunchAnimator = dialogLaunchAnimator;
+ mMediaOutputDialogFactory = mediaOutputDialogFactory;
+ }
+
+ public void createBroadcastDialog(String switchAppName, String outputPkgName,
+ boolean aboveStatusBar, View view) {
+ BroadcastDialog broadcastDialog = new BroadcastDialog(mContext, mMediaOutputDialogFactory,
+ switchAppName, outputPkgName, mUiEventLogger);
+ if (view != null) {
+ mDialogLaunchAnimator.showFromView(broadcastDialog, view);
+ } else {
+ broadcastDialog.show();
+ }
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/clipboardoverlay/ClipboardOverlayController.java b/packages/SystemUI/src/com/android/systemui/clipboardoverlay/ClipboardOverlayController.java
index 50550567ac16..c3dd29e91ea6 100644
--- a/packages/SystemUI/src/com/android/systemui/clipboardoverlay/ClipboardOverlayController.java
+++ b/packages/SystemUI/src/com/android/systemui/clipboardoverlay/ClipboardOverlayController.java
@@ -302,6 +302,7 @@ public class ClipboardOverlayController {
mExitAnimator.cancel();
}
reset();
+ String accessibilityAnnouncement;
boolean isSensitive = clipData != null && clipData.getDescription().getExtras() != null
&& clipData.getDescription().getExtras()
@@ -310,6 +311,7 @@ public class ClipboardOverlayController {
showTextPreview(
mContext.getResources().getString(R.string.clipboard_overlay_text_copied),
mTextPreview);
+ accessibilityAnnouncement = mContext.getString(R.string.clipboard_content_copied);
} else if (!TextUtils.isEmpty(clipData.getItemAt(0).getText())) {
ClipData.Item item = clipData.getItemAt(0);
if (item.getTextLinks() != null) {
@@ -321,13 +323,18 @@ public class ClipboardOverlayController {
} else {
showEditableText(item.getText(), false);
}
+ accessibilityAnnouncement = mContext.getString(R.string.clipboard_text_copied);
} else if (clipData.getItemAt(0).getUri() != null) {
- // How to handle non-image URIs?
- showEditableImage(clipData.getItemAt(0).getUri(), isSensitive);
+ if (tryShowEditableImage(clipData.getItemAt(0).getUri(), isSensitive)) {
+ accessibilityAnnouncement = mContext.getString(R.string.clipboard_image_copied);
+ } else {
+ accessibilityAnnouncement = mContext.getString(R.string.clipboard_content_copied);
+ }
} else {
showTextPreview(
mContext.getResources().getString(R.string.clipboard_overlay_text_copied),
mTextPreview);
+ accessibilityAnnouncement = mContext.getString(R.string.clipboard_content_copied);
}
Intent remoteCopyIntent = getRemoteCopyIntent(clipData);
// Only show remote copy if it's available.
@@ -344,7 +351,12 @@ public class ClipboardOverlayController {
} else {
mRemoteCopyChip.setVisibility(View.GONE);
}
- withWindowAttached(() -> mView.post(this::animateIn));
+ withWindowAttached(() -> {
+ updateInsets(
+ mWindowManager.getCurrentWindowMetrics().getWindowInsets());
+ mView.post(this::animateIn);
+ mView.announceForAccessibility(accessibilityAnnouncement);
+ });
mTimeoutHandler.resetTimeout();
}
@@ -476,33 +488,46 @@ public class ClipboardOverlayController {
textView.setOnClickListener(listener);
}
- private void showEditableImage(Uri uri, boolean isSensitive) {
- mEditChip.setAlpha(1f);
- mActionContainerBackground.setVisibility(View.VISIBLE);
+ private boolean tryShowEditableImage(Uri uri, boolean isSensitive) {
View.OnClickListener listener = v -> editImage(uri);
+ ContentResolver resolver = mContext.getContentResolver();
+ String mimeType = resolver.getType(uri);
+ boolean isEditableImage = mimeType != null && mimeType.startsWith("image");
if (isSensitive) {
showSinglePreview(mHiddenImagePreview);
- mHiddenImagePreview.setOnClickListener(listener);
- } else {
- showSinglePreview(mImagePreview);
- ContentResolver resolver = mContext.getContentResolver();
+ if (isEditableImage) {
+ mHiddenImagePreview.setOnClickListener(listener);
+ }
+ } else if (isEditableImage) { // if the MIMEtype is image, try to load
try {
int size = mContext.getResources().getDimensionPixelSize(R.dimen.overlay_x_scale);
// The width of the view is capped, height maintains aspect ratio, so allow it to be
// taller if needed.
Bitmap thumbnail = resolver.loadThumbnail(uri, new Size(size, size * 4), null);
+ showSinglePreview(mImagePreview);
mImagePreview.setImageBitmap(thumbnail);
+ mImagePreview.setOnClickListener(listener);
} catch (IOException e) {
Log.e(TAG, "Thumbnail loading failed", e);
showTextPreview(
mContext.getResources().getString(R.string.clipboard_overlay_text_copied),
mTextPreview);
+ isEditableImage = false;
}
- mImagePreview.setOnClickListener(listener);
+ } else {
+ showTextPreview(
+ mContext.getResources().getString(R.string.clipboard_overlay_text_copied),
+ mTextPreview);
}
- mEditChip.setOnClickListener(listener);
- mEditChip.setContentDescription(
- mContext.getString(R.string.clipboard_edit_image_description));
+ if (isEditableImage) {
+ mEditChip.setVisibility(View.VISIBLE);
+ mEditChip.setAlpha(1f);
+ mActionContainerBackground.setVisibility(View.VISIBLE);
+ mEditChip.setOnClickListener(listener);
+ mEditChip.setContentDescription(
+ mContext.getString(R.string.clipboard_edit_image_description));
+ }
+ return isEditableImage;
}
private Intent getRemoteCopyIntent(ClipData clipData) {
@@ -526,6 +551,9 @@ public class ClipboardOverlayController {
}
private void animateOut() {
+ if (mExitAnimator != null && mExitAnimator.isRunning()) {
+ return;
+ }
Animator anim = getExitAnimation();
anim.addListener(new AnimatorListenerAdapter() {
private boolean mCancelled;
diff --git a/packages/SystemUI/src/com/android/systemui/controls/ui/ControlViewHolder.kt b/packages/SystemUI/src/com/android/systemui/controls/ui/ControlViewHolder.kt
index a4f9f3a9bc08..6a9aaf865251 100644
--- a/packages/SystemUI/src/com/android/systemui/controls/ui/ControlViewHolder.kt
+++ b/packages/SystemUI/src/com/android/systemui/controls/ui/ControlViewHolder.kt
@@ -472,7 +472,6 @@ class ControlViewHolder(
updateContentDescription()
status.setTextColor(color)
- chevronIcon.imageTintList = color
control?.getCustomIcon()?.let {
icon.setImageIcon(it)
@@ -495,10 +494,13 @@ class ControlViewHolder(
icon.imageTintList = color
}
}
+
+ chevronIcon.imageTintList = icon.imageTintList
}
private fun setEnabled(enabled: Boolean) {
- status.setEnabled(enabled)
- icon.setEnabled(enabled)
+ status.isEnabled = enabled
+ icon.isEnabled = enabled
+ chevronIcon.isEnabled = enabled
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/dagger/SysUIComponent.java b/packages/SystemUI/src/com/android/systemui/dagger/SysUIComponent.java
index 6cbd8b132a80..3a1b12955647 100644
--- a/packages/SystemUI/src/com/android/systemui/dagger/SysUIComponent.java
+++ b/packages/SystemUI/src/com/android/systemui/dagger/SysUIComponent.java
@@ -39,7 +39,6 @@ import com.android.systemui.unfold.UnfoldLatencyTracker;
import com.android.systemui.unfold.util.NaturalRotationUnfoldProgressProvider;
import com.android.wm.shell.ShellCommandHandler;
import com.android.wm.shell.TaskViewFactory;
-import com.android.wm.shell.apppairs.AppPairs;
import com.android.wm.shell.back.BackAnimation;
import com.android.wm.shell.bubbles.Bubbles;
import com.android.wm.shell.compatui.CompatUI;
@@ -88,9 +87,6 @@ public interface SysUIComponent {
Builder setSplitScreen(Optional<SplitScreen> s);
@BindsInstance
- Builder setAppPairs(Optional<AppPairs> s);
-
- @BindsInstance
Builder setOneHanded(Optional<OneHanded> o);
@BindsInstance
diff --git a/packages/SystemUI/src/com/android/systemui/dagger/WMComponent.java b/packages/SystemUI/src/com/android/systemui/dagger/WMComponent.java
index 6dfa7e56c09e..1570a7ebc0c4 100644
--- a/packages/SystemUI/src/com/android/systemui/dagger/WMComponent.java
+++ b/packages/SystemUI/src/com/android/systemui/dagger/WMComponent.java
@@ -26,7 +26,6 @@ import com.android.systemui.tv.TvWMComponent;
import com.android.wm.shell.ShellCommandHandler;
import com.android.wm.shell.ShellInit;
import com.android.wm.shell.TaskViewFactory;
-import com.android.wm.shell.apppairs.AppPairs;
import com.android.wm.shell.back.BackAnimation;
import com.android.wm.shell.bubbles.Bubbles;
import com.android.wm.shell.common.annotations.ShellMainThread;
@@ -98,9 +97,6 @@ public interface WMComponent {
Optional<SplitScreen> getSplitScreen();
@WMSingleton
- Optional<AppPairs> getAppPairs();
-
- @WMSingleton
Optional<Bubbles> getBubbles();
@WMSingleton
diff --git a/packages/SystemUI/src/com/android/systemui/decor/OverlayWindow.kt b/packages/SystemUI/src/com/android/systemui/decor/OverlayWindow.kt
index d775ad39a5c3..3c0748e02552 100644
--- a/packages/SystemUI/src/com/android/systemui/decor/OverlayWindow.kt
+++ b/packages/SystemUI/src/com/android/systemui/decor/OverlayWindow.kt
@@ -16,11 +16,13 @@
package com.android.systemui.decor
import android.annotation.IdRes
+import android.annotation.NonNull
import android.content.Context
import android.view.Surface
import android.view.View
import android.view.ViewGroup
import com.android.systemui.RegionInterceptingFrameLayout
+import java.io.PrintWriter
class OverlayWindow(private val context: Context) {
@@ -100,4 +102,13 @@ class OverlayWindow(private val context: Context) {
}
}
}
+
+ fun dump(@NonNull pw: PrintWriter, name: String) {
+ pw.println(" $name=")
+ pw.println(" rootView=$rootView")
+ for (i in 0 until rootView.childCount) {
+ val child = rootView.getChildAt(i)
+ pw.println(" child[$i]=$child")
+ }
+ }
} \ No newline at end of file
diff --git a/packages/SystemUI/src/com/android/systemui/flags/Flags.java b/packages/SystemUI/src/com/android/systemui/flags/Flags.java
index c62c0bf06e3f..55bbcb654cf5 100644
--- a/packages/SystemUI/src/com/android/systemui/flags/Flags.java
+++ b/packages/SystemUI/src/com/android/systemui/flags/Flags.java
@@ -151,7 +151,7 @@ public class Flags {
/***************************************/
// 900 - media
public static final BooleanFlag MEDIA_TAP_TO_TRANSFER = new BooleanFlag(900, true);
- public static final BooleanFlag MEDIA_SESSION_ACTIONS = new BooleanFlag(901, true);
+ public static final BooleanFlag MEDIA_SESSION_ACTIONS = new BooleanFlag(901, false);
public static final BooleanFlag MEDIA_NEARBY_DEVICES = new BooleanFlag(903, true);
public static final BooleanFlag MEDIA_MUTE_AWAIT = new BooleanFlag(904, true);
@@ -166,6 +166,13 @@ public class Flags {
public static final SysPropBooleanFlag WM_ENABLE_SHELL_TRANSITIONS =
new SysPropBooleanFlag(1100, "persist.wm.debug.shell_transit", false);
+ /**
+ * b/170163464: animate bubbles expanded view collapse with home gesture
+ */
+ @Keep
+ public static final SysPropBooleanFlag BUBBLES_HOME_GESTURE =
+ new SysPropBooleanFlag(1101, "persist.wm.debug.bubbles_home_gesture", false);
+
// 1200 - predictive back
@Keep
public static final SysPropBooleanFlag WM_ENABLE_PREDICTIVE_BACK = new SysPropBooleanFlag(
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardUnlockAnimationController.kt b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardUnlockAnimationController.kt
index 404e5311961b..6dfc5e192abb 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardUnlockAnimationController.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardUnlockAnimationController.kt
@@ -44,6 +44,7 @@ import com.android.systemui.shared.system.QuickStepContract
import com.android.systemui.shared.system.smartspace.ILauncherUnlockAnimationController
import com.android.systemui.shared.system.smartspace.ISysuiUnlockAnimationController
import com.android.systemui.shared.system.smartspace.SmartspaceState
+import com.android.systemui.statusbar.NotificationShadeWindowController
import com.android.systemui.statusbar.SysuiStatusBarStateController
import com.android.systemui.statusbar.phone.BiometricUnlockController
import com.android.systemui.statusbar.policy.KeyguardStateController
@@ -142,7 +143,8 @@ class KeyguardUnlockAnimationController @Inject constructor(
private val keyguardViewController: KeyguardViewController,
private val featureFlags: FeatureFlags,
private val biometricUnlockControllerLazy: Lazy<BiometricUnlockController>,
- private val statusBarStateController: SysuiStatusBarStateController
+ private val statusBarStateController: SysuiStatusBarStateController,
+ private val notificationShadeWindowController: NotificationShadeWindowController
) : KeyguardStateController.Callback, ISysuiUnlockAnimationController.Stub() {
interface KeyguardUnlockAnimationListener {
@@ -362,6 +364,9 @@ class KeyguardUnlockAnimationController @Inject constructor(
*/
fun canPerformInWindowLauncherAnimations(): Boolean {
return isNexusLauncherUnderneath() &&
+ // If the launcher is underneath, but we're about to launch an activity, don't do
+ // the animations since they won't be visible.
+ !notificationShadeWindowController.isLaunchingActivity &&
launcherUnlockController != null &&
!keyguardStateController.isDismissingFromSwipe &&
// Temporarily disable for foldables since foldable launcher has two first pages,
@@ -413,7 +418,6 @@ class KeyguardUnlockAnimationController @Inject constructor(
(lockscreenSmartspace as BcSmartspaceDataPlugin.SmartspaceView?)?.selectedPage ?: -1
try {
-
// Let the launcher know to prepare for this animation.
launcherUnlockController?.prepareForUnlock(
willUnlockWithSmartspaceTransition, /* willAnimateSmartspace */
diff --git a/packages/SystemUI/src/com/android/systemui/log/LogBuffer.kt b/packages/SystemUI/src/com/android/systemui/log/LogBuffer.kt
index 25effec42f1a..db446c39767a 100644
--- a/packages/SystemUI/src/com/android/systemui/log/LogBuffer.kt
+++ b/packages/SystemUI/src/com/android/systemui/log/LogBuffer.kt
@@ -19,13 +19,14 @@ package com.android.systemui.log
import android.os.Trace
import android.util.Log
import com.android.systemui.log.dagger.LogModule
+import com.android.systemui.util.collection.RingBuffer
import java.io.PrintWriter
import java.text.SimpleDateFormat
-import java.util.ArrayDeque
import java.util.Locale
import java.util.concurrent.ArrayBlockingQueue
import java.util.concurrent.BlockingQueue
import kotlin.concurrent.thread
+import kotlin.math.max
/**
* A simple ring buffer of recyclable log messages
@@ -63,29 +64,22 @@ import kotlin.concurrent.thread
*
* Buffers are provided by [LogModule]. Instances should be created using a [LogBufferFactory].
*
- * @param name The name of this buffer
- * @param maxLogs The maximum number of messages to keep in memory at any one time, including the
- * unused pool. Must be >= [poolSize].
- * @param poolSize The maximum amount that the size of the buffer is allowed to flex in response to
- * sequential calls to [document] that aren't immediately followed by a matching call to [push].
+ * @param name The name of this buffer, printed when the buffer is dumped and in some other
+ * situations.
+ * @param maxSize The maximum number of messages to keep in memory at any one time. Buffers start
+ * out empty and grow up to [maxSize] as new messages are logged. Once the buffer's size reaches
+ * the maximum, it behaves like a ring buffer.
*/
class LogBuffer @JvmOverloads constructor(
private val name: String,
- private val maxLogs: Int,
- private val poolSize: Int,
+ private val maxSize: Int,
private val logcatEchoTracker: LogcatEchoTracker,
private val systrace: Boolean = true
) {
- init {
- if (maxLogs < poolSize) {
- throw IllegalArgumentException("maxLogs must be greater than or equal to poolSize, " +
- "but maxLogs=$maxLogs < $poolSize=poolSize")
- }
- }
+ private val buffer = RingBuffer(maxSize) { LogMessageImpl.create() }
- private val buffer: ArrayDeque<LogMessageImpl> = ArrayDeque()
- private val echoMessageQueue: BlockingQueue<LogMessageImpl>? =
- if (logcatEchoTracker.logInBackgroundThread) ArrayBlockingQueue(poolSize) else null
+ private val echoMessageQueue: BlockingQueue<LogMessage>? =
+ if (logcatEchoTracker.logInBackgroundThread) ArrayBlockingQueue(10) else null
init {
if (logcatEchoTracker.logInBackgroundThread && echoMessageQueue != null) {
@@ -104,6 +98,9 @@ class LogBuffer @JvmOverloads constructor(
var frozen = false
private set
+ private val mutable
+ get() = !frozen && maxSize > 0
+
/**
* Logs a message to the log buffer
*
@@ -138,34 +135,19 @@ class LogBuffer @JvmOverloads constructor(
initializer: LogMessage.() -> Unit,
noinline printer: LogMessage.() -> String
) {
- if (!frozen) {
- val message = obtain(tag, level, printer)
- initializer(message)
- push(message)
- }
- }
-
- /**
- * Same as [log], but doesn't push the message to the buffer. Useful if you need to supply a
- * "reason" for doing something (the thing you supply the reason to will presumably call [push]
- * on that message at some point).
- */
- inline fun document(
- tag: String,
- level: LogLevel,
- initializer: LogMessage.() -> Unit,
- noinline printer: LogMessage.() -> String
- ): LogMessage {
val message = obtain(tag, level, printer)
initializer(message)
- return message
+ commit(message)
}
/**
- * Obtains an instance of [LogMessageImpl], usually from the object pool. If the pool has been
- * exhausted, creates a new instance.
+ * You should call [log] instead of this method.
*
- * In general, you should call [log] or [document] instead of this method.
+ * Obtains the next [LogMessage] from the ring buffer. If the buffer is not yet at max size,
+ * grows the buffer by one.
+ *
+ * After calling [obtain], the message will now be at the end of the buffer. The caller must
+ * store any relevant data on the message and then call [commit].
*/
@Synchronized
fun obtain(
@@ -173,28 +155,26 @@ class LogBuffer @JvmOverloads constructor(
level: LogLevel,
printer: (LogMessage) -> String
): LogMessageImpl {
- val message = when {
- frozen -> LogMessageImpl.create()
- buffer.size > maxLogs - poolSize -> buffer.removeFirst()
- else -> LogMessageImpl.create()
+ if (!mutable) {
+ return FROZEN_MESSAGE
}
+ val message = buffer.advance()
message.reset(tag, level, System.currentTimeMillis(), printer)
return message
}
/**
- * Pushes a message into buffer, possibly evicting an older message if the buffer is full.
+ * You should call [log] instead of this method.
+ *
+ * After acquiring a message via [obtain], call this method to signal to the buffer that you
+ * have finished filling in its data fields. The message will be echoed to logcat if
+ * necessary.
*/
@Synchronized
- fun push(message: LogMessage) {
- if (frozen) {
+ fun commit(message: LogMessage) {
+ if (!mutable) {
return
}
- if (buffer.size == maxLogs) {
- Log.e(TAG, "LogBuffer $name has exceeded its pool size")
- buffer.removeFirst()
- }
- buffer.add(message as LogMessageImpl)
// Log in the background thread only if echoMessageQueue exists and has capacity (checking
// capacity avoids the possibility of blocking this thread)
if (echoMessageQueue != null && echoMessageQueue.remainingCapacity() > 0) {
@@ -210,7 +190,7 @@ class LogBuffer @JvmOverloads constructor(
}
/** Sends message to echo after determining whether to use Logcat and/or systrace. */
- private fun echoToDesiredEndpoints(message: LogMessageImpl) {
+ private fun echoToDesiredEndpoints(message: LogMessage) {
val includeInLogcat = logcatEchoTracker.isBufferLoggable(name, message.level) ||
logcatEchoTracker.isTagLoggable(message.tag, message.level)
echo(message, toLogcat = includeInLogcat, toSystrace = systrace)
@@ -219,19 +199,17 @@ class LogBuffer @JvmOverloads constructor(
/** Converts the entire buffer to a newline-delimited string */
@Synchronized
fun dump(pw: PrintWriter, tailLength: Int) {
- val start = if (tailLength <= 0) { 0 } else { buffer.size - tailLength }
+ val iterationStart = if (tailLength <= 0) { 0 } else { max(0, buffer.size - tailLength) }
- for ((i, message) in buffer.withIndex()) {
- if (i >= start) {
- dumpMessage(message, pw)
- }
+ for (i in iterationStart until buffer.size) {
+ dumpMessage(buffer[i], pw)
}
}
/**
- * "Freezes" the contents of the buffer, making them immutable until [unfreeze] is called.
- * Calls to [log], [document], [obtain], and [push] will not affect the buffer and will return
- * dummy values if necessary.
+ * "Freezes" the contents of the buffer, making it immutable until [unfreeze] is called.
+ * Calls to [log], [obtain], and [commit] will not affect the buffer and will return dummy
+ * values if necessary.
*/
@Synchronized
fun freeze() {
@@ -293,3 +271,4 @@ class LogBuffer @JvmOverloads constructor(
private const val TAG = "LogBuffer"
private val DATE_FORMAT = SimpleDateFormat("MM-dd HH:mm:ss.SSS", Locale.US)
+private val FROZEN_MESSAGE = LogMessageImpl.create() \ No newline at end of file
diff --git a/packages/SystemUI/src/com/android/systemui/log/LogBufferFactory.kt b/packages/SystemUI/src/com/android/systemui/log/LogBufferFactory.kt
index cbfca25e0c60..5651399cb891 100644
--- a/packages/SystemUI/src/com/android/systemui/log/LogBufferFactory.kt
+++ b/packages/SystemUI/src/com/android/systemui/log/LogBufferFactory.kt
@@ -27,22 +27,21 @@ class LogBufferFactory @Inject constructor(
private val logcatEchoTracker: LogcatEchoTracker
) {
/* limit the size of maxPoolSize for low ram (Go) devices */
- private fun poolLimit(maxPoolSize_requested: Int): Int {
- if (ActivityManager.isLowRamDeviceStatic()) {
- return minOf(maxPoolSize_requested, 20) /* low ram max log size*/
+ private fun adjustMaxSize(requestedMaxSize: Int): Int {
+ return if (ActivityManager.isLowRamDeviceStatic()) {
+ minOf(requestedMaxSize, 20) /* low ram max log size*/
} else {
- return maxPoolSize_requested
+ requestedMaxSize
}
}
@JvmOverloads
fun create(
name: String,
- maxPoolSize: Int,
- flexSize: Int = 10,
+ maxSize: Int,
systrace: Boolean = true
): LogBuffer {
- val buffer = LogBuffer(name, poolLimit(maxPoolSize), flexSize, logcatEchoTracker, systrace)
+ val buffer = LogBuffer(name, adjustMaxSize(maxSize), logcatEchoTracker, systrace)
dumpManager.registerBuffer(name, buffer)
return buffer
}
diff --git a/packages/SystemUI/src/com/android/systemui/log/LogcatEchoTrackerDebug.kt b/packages/SystemUI/src/com/android/systemui/log/LogcatEchoTrackerDebug.kt
index 91734cc361b0..40b0cdc173d8 100644
--- a/packages/SystemUI/src/com/android/systemui/log/LogcatEchoTrackerDebug.kt
+++ b/packages/SystemUI/src/com/android/systemui/log/LogcatEchoTrackerDebug.kt
@@ -60,7 +60,7 @@ class LogcatEchoTrackerDebug private constructor(
Settings.Global.getUriFor(BUFFER_PATH),
true,
object : ContentObserver(Handler(mainLooper)) {
- override fun onChange(selfChange: Boolean, uri: Uri) {
+ override fun onChange(selfChange: Boolean, uri: Uri?) {
super.onChange(selfChange, uri)
cachedBufferLevels.clear()
}
@@ -70,7 +70,7 @@ class LogcatEchoTrackerDebug private constructor(
Settings.Global.getUriFor(TAG_PATH),
true,
object : ContentObserver(Handler(mainLooper)) {
- override fun onChange(selfChange: Boolean, uri: Uri) {
+ override fun onChange(selfChange: Boolean, uri: Uri?) {
super.onChange(selfChange, uri)
cachedTagLevels.clear()
}
@@ -110,7 +110,7 @@ class LogcatEchoTrackerDebug private constructor(
}
private fun parseProp(propValue: String?): LogLevel {
- return when (propValue?.toLowerCase()) {
+ return when (propValue?.lowercase()) {
"verbose" -> LogLevel.VERBOSE
"v" -> LogLevel.VERBOSE
"debug" -> LogLevel.DEBUG
diff --git a/packages/SystemUI/src/com/android/systemui/log/dagger/LogModule.java b/packages/SystemUI/src/com/android/systemui/log/dagger/LogModule.java
index f72f1bb47468..eff025f771a5 100644
--- a/packages/SystemUI/src/com/android/systemui/log/dagger/LogModule.java
+++ b/packages/SystemUI/src/com/android/systemui/log/dagger/LogModule.java
@@ -49,8 +49,7 @@ public class LogModule {
@SysUISingleton
@NotificationLog
public static LogBuffer provideNotificationsLogBuffer(LogBufferFactory factory) {
- return factory.create("NotifLog", 1000 /* maxPoolSize */,
- 10 /* flexSize */, false /* systrace */);
+ return factory.create("NotifLog", 1000 /* maxSize */, false /* systrace */);
}
/** Provides a logging buffer for all logs related to the data layer of notifications. */
@@ -74,8 +73,7 @@ public class LogModule {
@SysUISingleton
@NotificationSectionLog
public static LogBuffer provideNotificationSectionLogBuffer(LogBufferFactory factory) {
- return factory.create("NotifSectionLog", 1000 /* maxPoolSize */,
- 10 /* flexSize */, false /* systrace */);
+ return factory.create("NotifSectionLog", 1000 /* maxSize */, false /* systrace */);
}
/** Provides a logging buffer for all logs related to the data layer of notifications. */
@@ -91,8 +89,7 @@ public class LogModule {
@SysUISingleton
@QSLog
public static LogBuffer provideQuickSettingsLogBuffer(LogBufferFactory factory) {
- return factory.create("QSLog", 500 /* maxPoolSize */,
- 10 /* flexSize */, false /* systrace */);
+ return factory.create("QSLog", 500 /* maxSize */, false /* systrace */);
}
/** Provides a logging buffer for {@link com.android.systemui.broadcast.BroadcastDispatcher} */
@@ -100,8 +97,8 @@ public class LogModule {
@SysUISingleton
@BroadcastDispatcherLog
public static LogBuffer provideBroadcastDispatcherLogBuffer(LogBufferFactory factory) {
- return factory.create("BroadcastDispatcherLog", 500 /* maxPoolSize */,
- 10 /* flexSize */, false /* systrace */);
+ return factory.create("BroadcastDispatcherLog", 500 /* maxSize */,
+ false /* systrace */);
}
/** Provides a logging buffer for all logs related to Toasts shown by SystemUI. */
@@ -139,8 +136,8 @@ public class LogModule {
@SysUISingleton
@QSFragmentDisableLog
public static LogBuffer provideQSFragmentDisableLogBuffer(LogBufferFactory factory) {
- return factory.create("QSFragmentDisableFlagsLog", 10 /* maxPoolSize */,
- 10 /* flexSize */, false /* systrace */);
+ return factory.create("QSFragmentDisableFlagsLog", 10 /* maxSize */,
+ false /* systrace */);
}
/**
@@ -230,6 +227,18 @@ public class LogModule {
return factory.create("MediaBrowser", 100);
}
+ /**
+ * Provides a buffer for updates to the media carousel.
+ *
+ * See {@link com.android.systemui.media.MediaCarouselController}.
+ */
+ @Provides
+ @SysUISingleton
+ @MediaCarouselControllerLog
+ public static LogBuffer provideMediaCarouselControllerBuffer(LogBufferFactory factory) {
+ return factory.create("MediaCarouselCtlrLog", 20);
+ }
+
/** Allows logging buffers to be tweaked via adb on debug builds but not on prod builds. */
@Provides
@SysUISingleton
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotifActivityLaunchEventsModule.java b/packages/SystemUI/src/com/android/systemui/log/dagger/MediaCarouselControllerLog.java
index 84ff538677b0..b03655a543f7 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotifActivityLaunchEventsModule.java
+++ b/packages/SystemUI/src/com/android/systemui/log/dagger/MediaCarouselControllerLog.java
@@ -14,17 +14,22 @@
* limitations under the License.
*/
-package com.android.systemui.statusbar.phone;
+package com.android.systemui.log.dagger;
-import com.android.systemui.dagger.SysUISingleton;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
-import dagger.Binds;
-import dagger.Module;
+import com.android.systemui.log.LogBuffer;
-/** Provides a {@link NotifActivityLaunchEvents} in {@link SysUISingleton} scope. */
-@Module
-public abstract class NotifActivityLaunchEventsModule {
- @Binds
- abstract NotifActivityLaunchEvents bindLaunchEvents(
- StatusBarNotificationActivityStarter.LaunchEventsEmitter impl);
+import java.lang.annotation.Documented;
+import java.lang.annotation.Retention;
+
+import javax.inject.Qualifier;
+
+/**
+ * A {@link LogBuffer} for {@link com.android.systemui.media.MediaCarouselController}
+ */
+@Qualifier
+@Documented
+@Retention(RUNTIME)
+public @interface MediaCarouselControllerLog {
}
diff --git a/packages/SystemUI/src/com/android/systemui/media/MediaCarouselController.kt b/packages/SystemUI/src/com/android/systemui/media/MediaCarouselController.kt
index 3483bc39b943..8a104c42068e 100644
--- a/packages/SystemUI/src/com/android/systemui/media/MediaCarouselController.kt
+++ b/packages/SystemUI/src/com/android/systemui/media/MediaCarouselController.kt
@@ -59,7 +59,8 @@ class MediaCarouselController @Inject constructor(
falsingCollector: FalsingCollector,
falsingManager: FalsingManager,
dumpManager: DumpManager,
- private val logger: MediaUiEventLogger
+ private val logger: MediaUiEventLogger,
+ private val debugLogger: MediaCarouselControllerLogger
) : Dumpable {
/**
* The current width of the carousel
@@ -439,12 +440,16 @@ class MediaCarouselController @Inject constructor(
newPlayer.mediaViewHolder?.player?.setLayoutParams(lp)
newPlayer.bindPlayer(data, key)
newPlayer.setListening(currentlyExpanded)
- MediaPlayerData.addMediaPlayer(key, data, newPlayer, systemClock, isSsReactivated)
+ MediaPlayerData.addMediaPlayer(
+ key, data, newPlayer, systemClock, isSsReactivated, debugLogger
+ )
updatePlayerToState(newPlayer, noAnimation = true)
reorderAllPlayers(curVisibleMediaKey)
} else {
existingPlayer.bindPlayer(data, key)
- MediaPlayerData.addMediaPlayer(key, data, existingPlayer, systemClock, isSsReactivated)
+ MediaPlayerData.addMediaPlayer(
+ key, data, existingPlayer, systemClock, isSsReactivated, debugLogger
+ )
if (isReorderingAllowed || shouldScrollToActivePlayer) {
reorderAllPlayers(curVisibleMediaKey)
} else {
@@ -475,7 +480,8 @@ class MediaCarouselController @Inject constructor(
val existingSmartspaceMediaKey = MediaPlayerData.smartspaceMediaKey()
existingSmartspaceMediaKey?.let {
- MediaPlayerData.removeMediaPlayer(existingSmartspaceMediaKey)
+ val removedPlayer = MediaPlayerData.removeMediaPlayer(existingSmartspaceMediaKey)
+ removedPlayer?.run { debugLogger.logPotentialMemoryLeak(existingSmartspaceMediaKey) }
}
val newRecs = mediaControlPanelFactory.get()
@@ -488,7 +494,9 @@ class MediaCarouselController @Inject constructor(
newRecs.bindRecommendation(data)
val curVisibleMediaKey = MediaPlayerData.playerKeys()
.elementAtOrNull(mediaCarouselScrollHandler.visibleMediaIndex)
- MediaPlayerData.addMediaRecommendation(key, data, newRecs, shouldPrioritize, systemClock)
+ MediaPlayerData.addMediaRecommendation(
+ key, data, newRecs, shouldPrioritize, systemClock, debugLogger
+ )
updatePlayerToState(newRecs, noAnimation = true)
reorderAllPlayers(curVisibleMediaKey)
updatePageIndicator()
@@ -845,7 +853,8 @@ class MediaCarouselController @Inject constructor(
uid,
interactedSubcardRank,
interactedSubcardCardinality,
- receivedLatencyMillis
+ receivedLatencyMillis,
+ null // Media cards cannot have subcards.
)
/* ktlint-disable max-line-length */
if (DEBUG) {
@@ -882,7 +891,8 @@ class MediaCarouselController @Inject constructor(
override fun dump(pw: PrintWriter, args: Array<out String>) {
pw.apply {
println("keysNeedRemoval: $keysNeedRemoval")
- println("playerKeys: ${MediaPlayerData.playerKeys()}")
+ println("dataKeys: ${MediaPlayerData.dataKeys()}")
+ println("playerSortKeys: ${MediaPlayerData.playerKeys()}")
println("smartspaceMediaData: ${MediaPlayerData.smartspaceMediaData}")
println("shouldPrioritizeSs: ${MediaPlayerData.shouldPrioritizeSs}")
println("current size: $currentCarouselWidth x $currentCarouselHeight")
@@ -945,9 +955,13 @@ internal object MediaPlayerData {
data: MediaData,
player: MediaControlPanel,
clock: SystemClock,
- isSsReactivated: Boolean
+ isSsReactivated: Boolean,
+ debugLogger: MediaCarouselControllerLogger? = null
) {
- removeMediaPlayer(key)
+ val removedPlayer = removeMediaPlayer(key)
+ if (removedPlayer != null && removedPlayer != player) {
+ debugLogger?.logPotentialMemoryLeak(key)
+ }
val sortKey = MediaSortKey(isSsMediaRec = false,
data, clock.currentTimeMillis(), isSsReactivated = isSsReactivated)
mediaData.put(key, sortKey)
@@ -959,10 +973,14 @@ internal object MediaPlayerData {
data: SmartspaceMediaData,
player: MediaControlPanel,
shouldPrioritize: Boolean,
- clock: SystemClock
+ clock: SystemClock,
+ debugLogger: MediaCarouselControllerLogger? = null
) {
shouldPrioritizeSs = shouldPrioritize
- removeMediaPlayer(key)
+ val removedPlayer = removeMediaPlayer(key)
+ if (removedPlayer != null && removedPlayer != player) {
+ debugLogger?.logPotentialMemoryLeak(key)
+ }
val sortKey = MediaSortKey(isSsMediaRec = true,
EMPTY.copy(isPlaying = false), clock.currentTimeMillis(), isSsReactivated = true)
mediaData.put(key, sortKey)
@@ -970,13 +988,18 @@ internal object MediaPlayerData {
smartspaceMediaData = data
}
- fun moveIfExists(oldKey: String?, newKey: String) {
+ fun moveIfExists(
+ oldKey: String?,
+ newKey: String,
+ debugLogger: MediaCarouselControllerLogger? = null
+ ) {
if (oldKey == null || oldKey == newKey) {
return
}
mediaData.remove(oldKey)?.let {
- removeMediaPlayer(newKey)
+ val removedPlayer = removeMediaPlayer(newKey)
+ removedPlayer?.run { debugLogger?.logPotentialMemoryLeak(newKey) }
mediaData.put(newKey, it)
}
}
@@ -1004,6 +1027,8 @@ internal object MediaPlayerData {
fun mediaData() = mediaData.entries.map { e -> Triple(e.key, e.value.data, e.value.isSsMediaRec) }
+ fun dataKeys() = mediaData.keys
+
fun players() = mediaPlayers.values
fun playerKeys() = mediaPlayers.keys
diff --git a/packages/SystemUI/src/com/android/systemui/media/MediaCarouselControllerLogger.kt b/packages/SystemUI/src/com/android/systemui/media/MediaCarouselControllerLogger.kt
new file mode 100644
index 000000000000..04ebd5a71137
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/media/MediaCarouselControllerLogger.kt
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.media
+
+import com.android.systemui.dagger.SysUISingleton
+import com.android.systemui.log.LogBuffer
+import com.android.systemui.log.LogLevel
+import com.android.systemui.log.dagger.MediaCarouselControllerLog
+import javax.inject.Inject
+
+/** A debug logger for [MediaCarouselController]. */
+@SysUISingleton
+class MediaCarouselControllerLogger @Inject constructor(
+ @MediaCarouselControllerLog private val buffer: LogBuffer
+) {
+ /**
+ * Log that there might be a potential memory leak for the [MediaControlPanel] and/or
+ * [MediaViewController] related to [key].
+ */
+ fun logPotentialMemoryLeak(key: String) = buffer.log(
+ TAG,
+ LogLevel.DEBUG,
+ { str1 = key },
+ {
+ "Potential memory leak: " +
+ "Removing control panel for $str1 from map without calling #onDestroy"
+ }
+ )
+}
+
+private const val TAG = "MediaCarouselCtlrLog"
diff --git a/packages/SystemUI/src/com/android/systemui/media/MediaControlPanel.java b/packages/SystemUI/src/com/android/systemui/media/MediaControlPanel.java
index b9601420bb26..6ef25046d328 100644
--- a/packages/SystemUI/src/com/android/systemui/media/MediaControlPanel.java
+++ b/packages/SystemUI/src/com/android/systemui/media/MediaControlPanel.java
@@ -75,6 +75,7 @@ import com.android.systemui.dagger.qualifiers.Background;
import com.android.systemui.dagger.qualifiers.Main;
import com.android.systemui.media.dialog.MediaOutputDialogFactory;
import com.android.systemui.monet.ColorScheme;
+import com.android.systemui.monet.Style;
import com.android.systemui.plugins.ActivityStarter;
import com.android.systemui.plugins.FalsingManager;
import com.android.systemui.shared.system.SysUiStatsLog;
@@ -627,7 +628,7 @@ public class MediaControlPanel {
if (artworkIcon != null) {
WallpaperColors wallpaperColors = WallpaperColors
.fromBitmap(artworkIcon.getBitmap());
- mutableColorScheme = new ColorScheme(wallpaperColors, true);
+ mutableColorScheme = new ColorScheme(wallpaperColors, true, Style.CONTENT);
artwork = getScaledBackground(artworkIcon, width, height);
isArtworkBound = true;
} else {
@@ -637,7 +638,8 @@ public class MediaControlPanel {
try {
Drawable icon = mContext.getPackageManager()
.getApplicationIcon(data.getPackageName());
- mutableColorScheme = new ColorScheme(WallpaperColors.fromDrawable(icon), true);
+ mutableColorScheme = new ColorScheme(WallpaperColors.fromDrawable(icon), true,
+ Style.CONTENT);
} catch (PackageManager.NameNotFoundException e) {
Log.w(TAG, "Cannot find icon for package " + data.getPackageName(), e);
}
diff --git a/packages/SystemUI/src/com/android/systemui/media/MediaDataUtils.java b/packages/SystemUI/src/com/android/systemui/media/MediaDataUtils.java
new file mode 100644
index 000000000000..b8185b9de7e8
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/media/MediaDataUtils.java
@@ -0,0 +1,43 @@
+/**
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.media;
+
+import android.content.Context;
+import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageManager;
+import android.text.TextUtils;
+
+public class MediaDataUtils {
+
+ public static String getAppLabel(Context context, String packageName, String unknownName) {
+ if (TextUtils.isEmpty(packageName)) {
+ return null;
+ }
+ final PackageManager packageManager = context.getPackageManager();
+ ApplicationInfo applicationInfo;
+ try {
+ applicationInfo = packageManager.getApplicationInfo(packageName, 0);
+ } catch (PackageManager.NameNotFoundException e) {
+ applicationInfo = null;
+ }
+ final String applicationName =
+ (String) (applicationInfo != null
+ ? packageManager.getApplicationLabel(applicationInfo)
+ : unknownName);
+ return applicationName;
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/media/MediaTimeoutListener.kt b/packages/SystemUI/src/com/android/systemui/media/MediaTimeoutListener.kt
index fc8d38d59d59..d4c4f2165339 100644
--- a/packages/SystemUI/src/com/android/systemui/media/MediaTimeoutListener.kt
+++ b/packages/SystemUI/src/com/android/systemui/media/MediaTimeoutListener.kt
@@ -22,8 +22,11 @@ import android.os.SystemProperties
import com.android.internal.annotations.VisibleForTesting
import com.android.systemui.dagger.SysUISingleton
import com.android.systemui.dagger.qualifiers.Main
+import com.android.systemui.plugins.statusbar.StatusBarStateController
import com.android.systemui.statusbar.NotificationMediaManager.isPlayingState
+import com.android.systemui.statusbar.SysuiStatusBarStateController
import com.android.systemui.util.concurrency.DelayableExecutor
+import com.android.systemui.util.time.SystemClock
import java.util.concurrent.TimeUnit
import javax.inject.Inject
@@ -42,7 +45,9 @@ val RESUME_MEDIA_TIMEOUT = SystemProperties
class MediaTimeoutListener @Inject constructor(
private val mediaControllerFactory: MediaControllerFactory,
@Main private val mainExecutor: DelayableExecutor,
- private val logger: MediaTimeoutLogger
+ private val logger: MediaTimeoutLogger,
+ statusBarStateController: SysuiStatusBarStateController,
+ private val systemClock: SystemClock
) : MediaDataManager.Listener {
private val mediaListeners: MutableMap<String, PlaybackStateListener> = mutableMapOf()
@@ -62,6 +67,24 @@ class MediaTimeoutListener @Inject constructor(
*/
lateinit var stateCallback: (String, PlaybackState) -> Unit
+ init {
+ statusBarStateController.addCallback(object : StatusBarStateController.StateListener {
+ override fun onDozingChanged(isDozing: Boolean) {
+ if (!isDozing) {
+ // Check whether any timeouts should have expired
+ mediaListeners.forEach { (key, listener) ->
+ if (listener.cancellation != null &&
+ listener.expiration <= systemClock.elapsedRealtime()) {
+ // We dozed too long - timeout now, and cancel the pending one
+ listener.expireMediaTimeout(key, "timeout happened while dozing")
+ listener.doTimeout()
+ }
+ }
+ }
+ }
+ })
+ }
+
override fun onMediaDataLoaded(
key: String,
oldKey: String?,
@@ -131,6 +154,7 @@ class MediaTimeoutListener @Inject constructor(
var lastState: PlaybackState? = null
var resumption: Boolean? = null
var destroyed = false
+ var expiration = Long.MAX_VALUE
var mediaData: MediaData = data
set(value) {
@@ -150,7 +174,8 @@ class MediaTimeoutListener @Inject constructor(
// Resume controls may have null token
private var mediaController: MediaController? = null
- private var cancellation: Runnable? = null
+ var cancellation: Runnable? = null
+ private set
fun Int.isPlaying() = isPlayingState(this)
fun isPlaying() = lastState?.state?.isPlaying() ?: false
@@ -216,12 +241,9 @@ class MediaTimeoutListener @Inject constructor(
} else {
PAUSED_MEDIA_TIMEOUT
}
+ expiration = systemClock.elapsedRealtime() + timeout
cancellation = mainExecutor.executeDelayed({
- cancellation = null
- logger.logTimeout(key)
- timedOut = true
- // this event is async, so it's safe even when `dispatchEvents` is false
- timeoutCallback(key, timedOut)
+ doTimeout()
}, timeout)
} else {
expireMediaTimeout(key, "playback started - $state, $key")
@@ -232,11 +254,21 @@ class MediaTimeoutListener @Inject constructor(
}
}
- private fun expireMediaTimeout(mediaKey: String, reason: String) {
+ fun doTimeout() {
+ cancellation = null
+ logger.logTimeout(key)
+ timedOut = true
+ expiration = Long.MAX_VALUE
+ // this event is async, so it's safe even when `dispatchEvents` is false
+ timeoutCallback(key, timedOut)
+ }
+
+ fun expireMediaTimeout(mediaKey: String, reason: String) {
cancellation?.apply {
logger.logTimeoutCancelled(mediaKey, reason)
run()
}
+ expiration = Long.MAX_VALUE
cancellation = null
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputBaseDialog.java b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputBaseDialog.java
index 5bb6557c3fe7..e9c00ef01e2a 100644
--- a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputBaseDialog.java
+++ b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputBaseDialog.java
@@ -76,6 +76,7 @@ public abstract class MediaOutputBaseDialog extends SystemUIDialog implements
private static final String PREF_NAME = "MediaOutputDialog";
private static final String PREF_IS_LE_BROADCAST_FIRST_LAUNCH = "PrefIsLeBroadcastFirstLaunch";
private static final boolean DEBUG = true;
+ private static final int HANDLE_BROADCAST_FAILED_DELAY = 3000;
private final Handler mMainThreadHandler = new Handler(Looper.getMainLooper());
private final RecyclerView.LayoutManager mLayoutManager;
@@ -119,7 +120,7 @@ public abstract class MediaOutputBaseDialog extends SystemUIDialog implements
Log.d(TAG, "onBroadcastStarted(), reason = " + reason
+ ", broadcastId = " + broadcastId);
}
- mMainThreadHandler.post(() -> startLeBroadcastDialog());
+ mMainThreadHandler.post(() -> handleLeBroadcastStarted());
}
@Override
@@ -127,7 +128,8 @@ public abstract class MediaOutputBaseDialog extends SystemUIDialog implements
if (DEBUG) {
Log.d(TAG, "onBroadcastStartFailed(), reason = " + reason);
}
- handleLeBroadcastStartFailed();
+ mMainThreadHandler.postDelayed(() -> handleLeBroadcastStartFailed(),
+ HANDLE_BROADCAST_FAILED_DELAY);
}
@Override
@@ -137,7 +139,7 @@ public abstract class MediaOutputBaseDialog extends SystemUIDialog implements
Log.d(TAG, "onBroadcastMetadataChanged(), broadcastId = " + broadcastId
+ ", metadata = " + metadata);
}
- mMainThreadHandler.post(() -> refresh());
+ mMainThreadHandler.post(() -> handleLeBroadcastMetadataChanged());
}
@Override
@@ -146,7 +148,7 @@ public abstract class MediaOutputBaseDialog extends SystemUIDialog implements
Log.d(TAG, "onBroadcastStopped(), reason = " + reason
+ ", broadcastId = " + broadcastId);
}
- mMainThreadHandler.post(() -> refresh());
+ mMainThreadHandler.post(() -> handleLeBroadcastStopped());
}
@Override
@@ -154,7 +156,7 @@ public abstract class MediaOutputBaseDialog extends SystemUIDialog implements
if (DEBUG) {
Log.d(TAG, "onBroadcastStopFailed(), reason = " + reason);
}
- mMainThreadHandler.post(() -> refresh());
+ mMainThreadHandler.post(() -> handleLeBroadcastStopFailed());
}
@Override
@@ -163,7 +165,7 @@ public abstract class MediaOutputBaseDialog extends SystemUIDialog implements
Log.d(TAG, "onBroadcastUpdated(), reason = " + reason
+ ", broadcastId = " + broadcastId);
}
- mMainThreadHandler.post(() -> refresh());
+ mMainThreadHandler.post(() -> handleLeBroadcastUpdated());
}
@Override
@@ -172,7 +174,7 @@ public abstract class MediaOutputBaseDialog extends SystemUIDialog implements
Log.d(TAG, "onBroadcastUpdateFailed(), reason = " + reason
+ ", broadcastId = " + broadcastId);
}
- mMainThreadHandler.post(() -> refresh());
+ mMainThreadHandler.post(() -> handleLeBroadcastUpdateFailed());
}
@Override
@@ -225,9 +227,7 @@ public abstract class MediaOutputBaseDialog extends SystemUIDialog implements
lp.setFitInsetsIgnoringVisibility(true);
window.setAttributes(lp);
window.setContentView(mDialogView);
- // Sets window to a blank string to avoid talkback announce app label first when pop up,
- // which doesn't make sense.
- window.setTitle(EMPTY_TITLE);
+ window.setTitle(mContext.getString(R.string.media_output_dialog_accessibility_title));
mHeaderTitle = mDialogView.requireViewById(R.id.header_title);
mHeaderSubtitle = mDialogView.requireViewById(R.id.header_subtitle);
@@ -384,10 +384,34 @@ public abstract class MediaOutputBaseDialog extends SystemUIDialog implements
Bitmap.createScaledBitmap(bitmap, size, size, false));
}
- protected void handleLeBroadcastStartFailed() {
+ public void handleLeBroadcastStarted() {
+ startLeBroadcastDialog();
+ }
+
+ public void handleLeBroadcastStartFailed() {
mStopButton.setText(R.string.media_output_broadcast_start_failed);
mStopButton.setEnabled(false);
- mMainThreadHandler.postDelayed(() -> refresh(), 3000);
+ refresh();
+ }
+
+ public void handleLeBroadcastMetadataChanged() {
+ refresh();
+ }
+
+ public void handleLeBroadcastStopped() {
+ refresh();
+ }
+
+ public void handleLeBroadcastStopFailed() {
+ refresh();
+ }
+
+ public void handleLeBroadcastUpdated() {
+ refresh();
+ }
+
+ public void handleLeBroadcastUpdateFailed() {
+ refresh();
}
protected void startLeBroadcast() {
diff --git a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputBroadcastDialog.java b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputBroadcastDialog.java
index dd4f1d6c9015..8f065461c22d 100644
--- a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputBroadcastDialog.java
+++ b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputBroadcastDialog.java
@@ -61,6 +61,10 @@ public class MediaOutputBroadcastDialog extends MediaOutputBaseDialog {
private ImageView mBroadcastCodeEdit;
private AlertDialog mAlertDialog;
private TextView mBroadcastErrorMessage;
+ private int mRetryCount = 0;
+ private String mCurrentBroadcastName;
+ private String mCurrentBroadcastCode;
+ private boolean mIsStopbyUpdateBroadcastCode = false;
static final int METADATA_BROADCAST_NAME = 0;
static final int METADATA_BROADCAST_CODE = 1;
@@ -144,8 +148,6 @@ public class MediaOutputBroadcastDialog extends MediaOutputBaseDialog {
//init UI component
mBroadcastQrCodeView = getDialogView().requireViewById(R.id.qrcode_view);
- //Set the QR code view
- setQrCodeView();
mBroadcastNotify = getDialogView().requireViewById(R.id.broadcast_info);
mBroadcastNotify.setOnClickListener(v -> {
@@ -171,8 +173,16 @@ public class MediaOutputBroadcastDialog extends MediaOutputBaseDialog {
launchBroadcastUpdatedDialog(true, mBroadcastCode.getText().toString());
});
- mBroadcastName.setText(getBroadcastMetadataInfo(METADATA_BROADCAST_NAME));
- mBroadcastCode.setText(getBroadcastMetadataInfo(METADATA_BROADCAST_CODE));
+ refreshUi();
+ }
+
+ private void refreshUi() {
+ setQrCodeView();
+
+ mCurrentBroadcastName = getBroadcastMetadataInfo(METADATA_BROADCAST_NAME);
+ mCurrentBroadcastCode = getBroadcastMetadataInfo(METADATA_BROADCAST_CODE);
+ mBroadcastName.setText(mCurrentBroadcastName);
+ mBroadcastCode.setText(mCurrentBroadcastCode);
}
private void inflateBroadcastInfoArea() {
@@ -239,52 +249,99 @@ public class MediaOutputBroadcastDialog extends MediaOutputBaseDialog {
}
if (isBroadcastCode) {
- handleBroadcastCodeUpdated(updatedString);
+ /* If the user wants to update the Broadcast Code, the Broadcast session should be
+ * stopped then used the new Broadcast code to start the Broadcast.
+ */
+ mIsStopbyUpdateBroadcastCode = true;
+ mMediaOutputController.setBroadcastCode(updatedString);
+ if (!mMediaOutputController.stopBluetoothLeBroadcast()) {
+ handleLeBroadcastStopFailed();
+ return;
+ }
} else {
- handleBroadcastNameUpdated(updatedString);
+ /* If the user wants to update the Broadcast Name, we don't need to stop the Broadcast
+ * session. Only use the new Broadcast name to update the broadcast session.
+ */
+ mMediaOutputController.setBroadcastName(updatedString);
+ if (!mMediaOutputController.updateBluetoothLeBroadcast()) {
+ handleLeBroadcastUpdateFailed();
+ }
}
}
- private void handleBroadcastNameUpdated(String name) {
- // TODO(b/230473995) Add the retry mechanism and error handling when update fails
- String currentName = mMediaOutputController.getBroadcastName();
- int retryCount = MAX_BROADCAST_INFO_UPDATE;
- mMediaOutputController.setBroadcastName(name);
- if (!mMediaOutputController.updateBluetoothLeBroadcast()) {
- mMediaOutputController.setBroadcastName(currentName);
- handleLeUpdateBroadcastFailed(retryCount);
+ @Override
+ public void handleLeBroadcastStarted() {
+ mRetryCount = 0;
+ if (mAlertDialog != null) {
+ mAlertDialog.dismiss();
}
+ refreshUi();
}
- private void handleBroadcastCodeUpdated(String newPassword) {
- // TODO(b/230473995) Add the retry mechanism and error handling when update fails
- String currentPassword = mMediaOutputController.getBroadcastCode();
- int retryCount = MAX_BROADCAST_INFO_UPDATE;
- if (!mMediaOutputController.stopBluetoothLeBroadcast()) {
- mMediaOutputController.setBroadcastCode(currentPassword);
- handleLeUpdateBroadcastFailed(retryCount);
- return;
+ @Override
+ public void handleLeBroadcastStartFailed() {
+ mMediaOutputController.setBroadcastCode(mCurrentBroadcastCode);
+ mRetryCount++;
+
+ handleUpdateFailedUi();
+ }
+
+ @Override
+ public void handleLeBroadcastMetadataChanged() {
+ refreshUi();
+ }
+
+ @Override
+ public void handleLeBroadcastUpdated() {
+ mRetryCount = 0;
+ if (mAlertDialog != null) {
+ mAlertDialog.dismiss();
}
+ refreshUi();
+ }
- mMediaOutputController.setBroadcastCode(newPassword);
- if (!mMediaOutputController.startBluetoothLeBroadcast()) {
- mMediaOutputController.setBroadcastCode(currentPassword);
- handleLeUpdateBroadcastFailed(retryCount);
- return;
+ @Override
+ public void handleLeBroadcastUpdateFailed() {
+ //Change the value in shared preferences back to it original value
+ mMediaOutputController.setBroadcastName(mCurrentBroadcastName);
+ mRetryCount++;
+
+ handleUpdateFailedUi();
+ }
+
+ @Override
+ public void handleLeBroadcastStopped() {
+ if (mIsStopbyUpdateBroadcastCode) {
+ mIsStopbyUpdateBroadcastCode = false;
+ mRetryCount = 0;
+ if (!mMediaOutputController.startBluetoothLeBroadcast()) {
+ handleLeBroadcastStartFailed();
+ return;
+ }
+ } else {
+ dismiss();
}
+ }
+
+ @Override
+ public void handleLeBroadcastStopFailed() {
+ //Change the value in shared preferences back to it original value
+ mMediaOutputController.setBroadcastCode(mCurrentBroadcastCode);
+ mRetryCount++;
- mAlertDialog.dismiss();
+ handleUpdateFailedUi();
}
- private void handleLeUpdateBroadcastFailed(int retryCount) {
+ private void handleUpdateFailedUi() {
final Button positiveBtn = mAlertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
mBroadcastErrorMessage.setVisibility(View.VISIBLE);
- if (retryCount < MAX_BROADCAST_INFO_UPDATE) {
+ if (mRetryCount < MAX_BROADCAST_INFO_UPDATE) {
if (positiveBtn != null) {
positiveBtn.setEnabled(true);
}
mBroadcastErrorMessage.setText(R.string.media_output_broadcast_update_error);
} else {
+ mRetryCount = 0;
mBroadcastErrorMessage.setText(R.string.media_output_broadcast_last_update_error);
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputController.java b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputController.java
index 58b6ad3e51e8..9329b1bfc2a3 100644
--- a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputController.java
+++ b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputController.java
@@ -573,6 +573,7 @@ public class MediaOutputController implements LocalMediaManager.DeviceCallback,
}
boolean addDeviceToPlayMedia(MediaDevice device) {
+ mMetricLogger.logInteractionExpansion(device);
return mLocalMediaManager.addDeviceToPlayMedia(device);
}
@@ -613,6 +614,7 @@ public class MediaOutputController implements LocalMediaManager.DeviceCallback,
}
void releaseSession() {
+ mMetricLogger.logInteractionStopCasting();
mLocalMediaManager.releaseSession();
}
@@ -627,6 +629,7 @@ public class MediaOutputController implements LocalMediaManager.DeviceCallback,
}
void adjustVolume(MediaDevice device, int volume) {
+ mMetricLogger.logInteractionAdjustVolume(device);
ThreadUtils.postOnBackgroundThread(() -> {
device.requestSetVolume(volume);
});
diff --git a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputMetricLogger.java b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputMetricLogger.java
index ac0295ed6d14..5d7af522176a 100644
--- a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputMetricLogger.java
+++ b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputMetricLogger.java
@@ -96,6 +96,49 @@ public class MediaOutputMetricLogger {
}
/**
+ * Do the metric logging of volume adjustment.
+ * @param source the device been adjusted
+ */
+ public void logInteractionAdjustVolume(MediaDevice source) {
+ if (DEBUG) {
+ Log.d(TAG, "logInteraction - AdjustVolume");
+ }
+
+ SysUiStatsLog.write(
+ SysUiStatsLog.MEDIAOUTPUT_OP_INTERACTION_REPORT,
+ SysUiStatsLog.MEDIA_OUTPUT_OP_INTERACTION_REPORTED__INTERACTION_TYPE__ADJUST_VOLUME,
+ getInteractionDeviceType(source));
+ }
+
+ /**
+ * Do the metric logging of stop casting.
+ */
+ public void logInteractionStopCasting() {
+ if (DEBUG) {
+ Log.d(TAG, "logInteraction - Stop casting");
+ }
+
+ SysUiStatsLog.write(
+ SysUiStatsLog.MEDIAOUTPUT_OP_INTERACTION_REPORT,
+ SysUiStatsLog.MEDIA_OUTPUT_OP_INTERACTION_REPORTED__INTERACTION_TYPE__STOP_CASTING,
+ SysUiStatsLog.MEDIA_OUTPUT_OP_INTERACTION_REPORTED__TARGET__UNKNOWN_TYPE);
+ }
+
+ /**
+ * Do the metric logging of device expansion.
+ */
+ public void logInteractionExpansion(MediaDevice source) {
+ if (DEBUG) {
+ Log.d(TAG, "logInteraction - Expansion");
+ }
+
+ SysUiStatsLog.write(
+ SysUiStatsLog.MEDIAOUTPUT_OP_INTERACTION_REPORT,
+ SysUiStatsLog.MEDIA_OUTPUT_OP_INTERACTION_REPORTED__INTERACTION_TYPE__EXPANSION,
+ getInteractionDeviceType(source));
+ }
+
+ /**
* Do the metric logging of content switching failure.
* @param deviceList media device list for device count updating
* @param reason the reason of content switching failure
@@ -185,6 +228,27 @@ public class MediaOutputMetricLogger {
}
}
+ private int getInteractionDeviceType(MediaDevice device) {
+ switch (device.getDeviceType()) {
+ case MediaDevice.MediaDeviceType.TYPE_PHONE_DEVICE:
+ return SysUiStatsLog.MEDIA_OUTPUT_OP_INTERACTION_REPORTED__TARGET__BUILTIN_SPEAKER;
+ case MediaDevice.MediaDeviceType.TYPE_3POINT5_MM_AUDIO_DEVICE:
+ return SysUiStatsLog
+ .MEDIA_OUTPUT_OP_INTERACTION_REPORTED__TARGET__WIRED_3POINT5_MM_AUDIO;
+ case MediaDevice.MediaDeviceType.TYPE_USB_C_AUDIO_DEVICE:
+ return SysUiStatsLog.MEDIA_OUTPUT_OP_INTERACTION_REPORTED__TARGET__USB_C_AUDIO;
+ case MediaDevice.MediaDeviceType.TYPE_BLUETOOTH_DEVICE:
+ return SysUiStatsLog.MEDIA_OUTPUT_OP_INTERACTION_REPORTED__TARGET__BLUETOOTH;
+ case MediaDevice.MediaDeviceType.TYPE_CAST_DEVICE:
+ return SysUiStatsLog.MEDIA_OUTPUT_OP_INTERACTION_REPORTED__TARGET__REMOTE_SINGLE;
+ case MediaDevice.MediaDeviceType.TYPE_CAST_GROUP_DEVICE:
+ return SysUiStatsLog.MEDIA_OUTPUT_OP_INTERACTION_REPORTED__TARGET__REMOTE_GROUP;
+ default:
+ return SysUiStatsLog.MEDIA_OUTPUT_OP_INTERACTION_REPORTED__TARGET__UNKNOWN_TYPE;
+ }
+ }
+
+
private int getLoggingSwitchOpSubResult(int reason) {
switch (reason) {
case REASON_REJECTED:
diff --git a/packages/SystemUI/src/com/android/systemui/navigationbar/buttons/KeyButtonView.java b/packages/SystemUI/src/com/android/systemui/navigationbar/buttons/KeyButtonView.java
index d27b71673ce5..622f5a279a5f 100644
--- a/packages/SystemUI/src/com/android/systemui/navigationbar/buttons/KeyButtonView.java
+++ b/packages/SystemUI/src/com/android/systemui/navigationbar/buttons/KeyButtonView.java
@@ -273,9 +273,8 @@ public class KeyButtonView extends ImageView implements ButtonInterface {
mLongClicked = false;
setPressed(true);
- // Use raw X and Y to detect gestures in case a parent changes the x and y values
- mTouchDownX = (int) ev.getRawX();
- mTouchDownY = (int) ev.getRawY();
+ mTouchDownX = (int) ev.getX();
+ mTouchDownY = (int) ev.getY();
if (mCode != KEYCODE_UNKNOWN) {
sendEvent(KeyEvent.ACTION_DOWN, 0, mDownTime);
} else {
@@ -289,8 +288,8 @@ public class KeyButtonView extends ImageView implements ButtonInterface {
postDelayed(mCheckLongPress, ViewConfiguration.getLongPressTimeout());
break;
case MotionEvent.ACTION_MOVE:
- x = (int)ev.getRawX();
- y = (int)ev.getRawY();
+ x = (int) ev.getX();
+ y = (int) ev.getY();
float slop = QuickStepContract.getQuickStepTouchSlopPx(getContext());
if (Math.abs(x - mTouchDownX) > slop || Math.abs(y - mTouchDownY) > slop) {
diff --git a/packages/SystemUI/src/com/android/systemui/navigationbar/gestural/NavigationHandle.java b/packages/SystemUI/src/com/android/systemui/navigationbar/gestural/NavigationHandle.java
index 33e6aa46724b..913b65289e12 100644
--- a/packages/SystemUI/src/com/android/systemui/navigationbar/gestural/NavigationHandle.java
+++ b/packages/SystemUI/src/com/android/systemui/navigationbar/gestural/NavigationHandle.java
@@ -36,8 +36,8 @@ public class NavigationHandle extends View implements ButtonInterface {
protected final Paint mPaint = new Paint();
private @ColorInt final int mLightColor;
private @ColorInt final int mDarkColor;
- protected final int mRadius;
- protected final int mBottom;
+ protected final float mRadius;
+ protected final float mBottom;
private boolean mRequiresInvalidate;
public NavigationHandle(Context context) {
@@ -47,8 +47,8 @@ public class NavigationHandle extends View implements ButtonInterface {
public NavigationHandle(Context context, AttributeSet attr) {
super(context, attr);
final Resources res = context.getResources();
- mRadius = res.getDimensionPixelSize(R.dimen.navigation_handle_radius);
- mBottom = res.getDimensionPixelSize(R.dimen.navigation_handle_bottom);
+ mRadius = res.getDimension(R.dimen.navigation_handle_radius);
+ mBottom = res.getDimension(R.dimen.navigation_handle_bottom);
final int dualToneDarkTheme = Utils.getThemeAttr(context, R.attr.darkIconTheme);
final int dualToneLightTheme = Utils.getThemeAttr(context, R.attr.lightIconTheme);
@@ -75,9 +75,9 @@ public class NavigationHandle extends View implements ButtonInterface {
// Draw that bar
int navHeight = getHeight();
- int height = mRadius * 2;
+ float height = mRadius * 2;
int width = getWidth();
- int y = (navHeight - mBottom - height);
+ float y = (navHeight - mBottom - height);
canvas.drawRoundRect(0, y, width, y + height, mRadius, mRadius, mPaint);
}
diff --git a/packages/SystemUI/src/com/android/systemui/navigationbar/gestural/QuickswitchOrientedNavHandle.java b/packages/SystemUI/src/com/android/systemui/navigationbar/gestural/QuickswitchOrientedNavHandle.java
index 71c8a2c1e6ca..88622aadd543 100644
--- a/packages/SystemUI/src/com/android/systemui/navigationbar/gestural/QuickswitchOrientedNavHandle.java
+++ b/packages/SystemUI/src/com/android/systemui/navigationbar/gestural/QuickswitchOrientedNavHandle.java
@@ -44,33 +44,33 @@ public class QuickswitchOrientedNavHandle extends NavigationHandle {
}
public RectF computeHomeHandleBounds() {
- int left;
- int top;
- int bottom;
- int right;
- int radiusOffset = mRadius * 2;
+ float left;
+ float top;
+ float bottom;
+ float right;
+ float radiusOffset = mRadius * 2;
int topStart = getLocationOnScreen()[1];
switch (mDeltaRotation) {
default:
case Surface.ROTATION_0:
case Surface.ROTATION_180:
- int height = mRadius * 2;
- left = getWidth() / 2 - mWidth / 2;
+ float height = mRadius * 2;
+ left = getWidth() / 2f - mWidth / 2f;
top = (getHeight() - mBottom - height);
- right = getWidth() / 2 + mWidth / 2;
+ right = getWidth() / 2f + mWidth / 2f;
bottom = top + height;
break;
case Surface.ROTATION_90:
left = mBottom;
right = left + radiusOffset;
- top = getHeight() / 2 - (mWidth / 2) - (topStart / 2);
+ top = getHeight() / 2f - (mWidth / 2f) - (topStart / 2f);
bottom = top + mWidth;
break;
case Surface.ROTATION_270:
right = getWidth() - mBottom;
left = right - radiusOffset;
- top = getHeight() / 2 - (mWidth / 2) - (topStart / 2);
+ top = getHeight() / 2f - (mWidth / 2f) - (topStart / 2f);
bottom = top + mWidth;
break;
}
diff --git a/packages/SystemUI/src/com/android/systemui/privacy/PrivacyItemController.kt b/packages/SystemUI/src/com/android/systemui/privacy/PrivacyItemController.kt
index dbdb9d268aab..cd6eb99e259e 100644
--- a/packages/SystemUI/src/com/android/systemui/privacy/PrivacyItemController.kt
+++ b/packages/SystemUI/src/com/android/systemui/privacy/PrivacyItemController.kt
@@ -58,7 +58,8 @@ class PrivacyItemController @Inject constructor(
internal companion object {
val OPS_MIC_CAMERA = intArrayOf(AppOpsManager.OP_CAMERA,
AppOpsManager.OP_PHONE_CALL_CAMERA, AppOpsManager.OP_RECORD_AUDIO,
- AppOpsManager.OP_PHONE_CALL_MICROPHONE)
+ AppOpsManager.OP_PHONE_CALL_MICROPHONE,
+ AppOpsManager.OP_RECEIVE_AMBIENT_TRIGGER_AUDIO)
val OPS_LOCATION = intArrayOf(
AppOpsManager.OP_COARSE_LOCATION,
AppOpsManager.OP_FINE_LOCATION)
@@ -315,6 +316,7 @@ class PrivacyItemController @Inject constructor(
AppOpsManager.OP_COARSE_LOCATION,
AppOpsManager.OP_FINE_LOCATION -> PrivacyType.TYPE_LOCATION
AppOpsManager.OP_PHONE_CALL_MICROPHONE,
+ AppOpsManager.OP_RECEIVE_AMBIENT_TRIGGER_AUDIO,
AppOpsManager.OP_RECORD_AUDIO -> PrivacyType.TYPE_MICROPHONE
else -> return null
}
diff --git a/packages/SystemUI/src/com/android/systemui/qrcodescanner/controller/QRCodeScannerController.java b/packages/SystemUI/src/com/android/systemui/qrcodescanner/controller/QRCodeScannerController.java
index 8000bdccfa68..2c20feb19342 100644
--- a/packages/SystemUI/src/com/android/systemui/qrcodescanner/controller/QRCodeScannerController.java
+++ b/packages/SystemUI/src/com/android/systemui/qrcodescanner/controller/QRCodeScannerController.java
@@ -29,7 +29,6 @@ import android.provider.Settings;
import android.util.Log;
import com.android.internal.config.sysui.SystemUiDeviceConfigFlags;
-import com.android.systemui.R;
import com.android.systemui.dagger.SysUISingleton;
import com.android.systemui.dagger.qualifiers.Background;
import com.android.systemui.settings.UserTracker;
@@ -119,7 +118,6 @@ public class QRCodeScannerController implements
mSecureSettings = secureSettings;
mDeviceConfigProxy = proxy;
mUserTracker = userTracker;
-
mConfigEnableLockScreenButton = mContext.getResources().getBoolean(
android.R.bool.config_enableQrCodeScannerOnLockScreen);
}
@@ -258,16 +256,20 @@ public class QRCodeScannerController implements
}
}
+ private String getDefaultScannerActivity() {
+ return mContext.getResources().getString(
+ com.android.internal.R.string.config_defaultQrCodeComponent);
+ }
+
private void updateQRCodeScannerActivityDetails() {
String qrCodeScannerActivity = mDeviceConfigProxy.getString(
DeviceConfig.NAMESPACE_SYSTEMUI,
SystemUiDeviceConfigFlags.DEFAULT_QR_CODE_SCANNER, "");
// "" means either the flags is not available or is set to "", and in both the cases we
- // want to use R.string.def_qr_code_component
+ // want to use R.string.config_defaultQrCodeComponent
if (Objects.equals(qrCodeScannerActivity, "")) {
- qrCodeScannerActivity =
- mContext.getResources().getString(R.string.def_qr_code_component);
+ qrCodeScannerActivity = getDefaultScannerActivity();
}
String prevQrCodeScannerActivity = mQRCodeScannerActivity;
diff --git a/packages/SystemUI/src/com/android/systemui/qs/FgsManagerController.kt b/packages/SystemUI/src/com/android/systemui/qs/FgsManagerController.kt
index 3e8cdf3a3592..e5d7b4003297 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/FgsManagerController.kt
+++ b/packages/SystemUI/src/com/android/systemui/qs/FgsManagerController.kt
@@ -23,10 +23,12 @@ import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
+import android.content.pm.UserInfo
import android.graphics.drawable.Drawable
import android.os.IBinder
import android.os.PowerExemptionManager
import android.os.RemoteException
+import android.os.UserHandle
import android.provider.DeviceConfig.NAMESPACE_SYSTEMUI
import android.text.format.DateUtils
import android.util.ArrayMap
@@ -51,6 +53,7 @@ import com.android.systemui.dagger.qualifiers.Background
import com.android.systemui.dagger.qualifiers.Main
import com.android.systemui.dump.DumpManager
import com.android.systemui.shared.system.SysUiStatsLog
+import com.android.systemui.settings.UserTracker
import com.android.systemui.statusbar.phone.SystemUIDialog
import com.android.systemui.util.DeviceConfigProxy
import com.android.systemui.util.indentIfPossible
@@ -69,6 +72,7 @@ class FgsManagerController @Inject constructor(
private val systemClock: SystemClock,
private val activityManager: IActivityManager,
private val packageManager: PackageManager,
+ private val userTracker: UserTracker,
private val deviceConfigProxy: DeviceConfigProxy,
private val dialogLaunchAnimator: DialogLaunchAnimator,
private val broadcastDispatcher: BroadcastDispatcher,
@@ -82,7 +86,8 @@ class FgsManagerController @Inject constructor(
var changesSinceDialog = false
private set
- private var isAvailable = false
+ var isAvailable = false
+ private set
private val lock = Any()
@@ -90,6 +95,12 @@ class FgsManagerController @Inject constructor(
var initialized = false
@GuardedBy("lock")
+ private var lastNumberOfVisiblePackages = 0
+
+ @GuardedBy("lock")
+ private var currentProfileIds = mutableSetOf<Int>()
+
+ @GuardedBy("lock")
private val runningServiceTokens = mutableMapOf<UserPackage, StartTimeAndTokens>()
@GuardedBy("lock")
@@ -101,6 +112,19 @@ class FgsManagerController @Inject constructor(
@GuardedBy("lock")
private var runningApps: ArrayMap<UserPackage, RunningApp> = ArrayMap()
+ private val userTrackerCallback = object : UserTracker.Callback {
+ override fun onUserChanged(newUser: Int, userContext: Context) {}
+
+ override fun onProfilesChanged(profiles: List<UserInfo>) {
+ synchronized(lock) {
+ currentProfileIds.clear()
+ currentProfileIds.addAll(profiles.map { it.id })
+ lastNumberOfVisiblePackages = 0
+ updateNumberOfVisibleRunningPackagesLocked()
+ }
+ }
+ }
+
interface OnNumberOfPackagesChangedListener {
fun onNumberOfPackagesChanged(numPackages: Int)
}
@@ -120,6 +144,10 @@ class FgsManagerController @Inject constructor(
e.rethrowFromSystemServer()
}
+ userTracker.addCallback(userTrackerCallback, backgroundExecutor)
+
+ currentProfileIds.addAll(userTracker.userProfiles.map { it.id })
+
deviceConfigProxy.addOnPropertiesChangedListener(NAMESPACE_SYSTEMUI,
backgroundExecutor) {
isAvailable = it.getBoolean(TASK_MANAGER_ENABLED, isAvailable)
@@ -153,10 +181,9 @@ class FgsManagerController @Inject constructor(
isForeground: Boolean
) {
synchronized(lock) {
- val numPackagesBefore = getNumRunningPackagesLocked()
val userPackageKey = UserPackage(userId, packageName)
if (isForeground) {
- runningServiceTokens.getOrPut(userPackageKey, { StartTimeAndTokens(systemClock) })
+ runningServiceTokens.getOrPut(userPackageKey) { StartTimeAndTokens(systemClock) }
.addToken(token)
} else {
if (runningServiceTokens[userPackageKey]?.also {
@@ -165,14 +192,7 @@ class FgsManagerController @Inject constructor(
}
}
- val numPackagesAfter = getNumRunningPackagesLocked()
-
- if (numPackagesAfter != numPackagesBefore) {
- changesSinceDialog = true
- onNumberOfPackagesChangedListeners.forEach {
- backgroundExecutor.execute { it.onNumberOfPackagesChanged(numPackagesAfter) }
- }
- }
+ updateNumberOfVisibleRunningPackagesLocked()
updateAppItemsLocked()
}
@@ -209,18 +229,30 @@ class FgsManagerController @Inject constructor(
}
}
- fun isAvailable(): Boolean {
- return isAvailable
- }
-
fun getNumRunningPackages(): Int {
synchronized(lock) {
- return getNumRunningPackagesLocked()
+ return getNumVisiblePackagesLocked()
}
}
- private fun getNumRunningPackagesLocked() =
- runningServiceTokens.keys.count { it.uiControl != UIControl.HIDE_ENTRY }
+ private fun getNumVisiblePackagesLocked(): Int {
+ return runningServiceTokens.keys.count {
+ it.uiControl != UIControl.HIDE_ENTRY && currentProfileIds.contains(it.userId)
+ }
+ }
+
+ private fun updateNumberOfVisibleRunningPackagesLocked() {
+ val num = getNumVisiblePackagesLocked()
+ if (num != lastNumberOfVisiblePackages) {
+ lastNumberOfVisiblePackages = num
+ changesSinceDialog = true
+ onNumberOfPackagesChangedListeners.forEach {
+ backgroundExecutor.execute {
+ it.onNumberOfPackagesChanged(num)
+ }
+ }
+ }
+ }
fun shouldUpdateFooterVisibility() = dialog == null
@@ -289,7 +321,9 @@ class FgsManagerController @Inject constructor(
val ai = packageManager.getApplicationInfoAsUser(it.packageName, 0, it.userId)
runningApps[it] = RunningApp(it.userId, it.packageName,
runningServiceTokens[it]!!.startTime, it.uiControl,
- ai.loadLabel(packageManager), ai.loadIcon(packageManager))
+ packageManager.getApplicationLabel(ai),
+ packageManager.getUserBadgedIcon(
+ packageManager.getApplicationIcon(ai), UserHandle.of(it.userId)))
logEvent(stopped = false, it.packageName, it.userId, runningApps[it]!!.timeStarted)
}
@@ -404,6 +438,7 @@ class FgsManagerController @Inject constructor(
val packageName: String
) {
val uid by lazy { packageManager.getPackageUidAsUser(packageName, userId) }
+ var backgroundRestrictionExemptionReason = PowerExemptionManager.REASON_DENIED
private var uiControlInitialized = false
var uiControl: UIControl = UIControl.NORMAL
@@ -416,7 +451,9 @@ class FgsManagerController @Inject constructor(
private set
fun updateUiControl() {
- uiControl = when (activityManager.getBackgroundRestrictionExemptionReason(uid)) {
+ backgroundRestrictionExemptionReason =
+ activityManager.getBackgroundRestrictionExemptionReason(uid)
+ uiControl = when (backgroundRestrictionExemptionReason) {
PowerExemptionManager.REASON_SYSTEM_UID,
PowerExemptionManager.REASON_DEVICE_DEMO_MODE -> UIControl.HIDE_ENTRY
@@ -448,7 +485,7 @@ class FgsManagerController @Inject constructor(
pw.indentIfPossible {
pw.println("userId=$userId")
pw.println("packageName=$packageName")
- pw.println("uiControl=$uiControl")
+ pw.println("uiControl=$uiControl (reason=$backgroundRestrictionExemptionReason)")
}
pw.println("]")
}
@@ -525,7 +562,7 @@ class FgsManagerController @Inject constructor(
pw.println("userId=$userId")
pw.println("packageName=$packageName")
pw.println("timeStarted=$timeStarted (time since start =" +
- " ${systemClock.elapsedRealtime() - timeStarted}ms)\"")
+ " ${systemClock.elapsedRealtime() - timeStarted}ms)")
pw.println("uiControl=$uiControl")
pw.println("appLabel=$appLabel")
pw.println("icon=$icon")
@@ -542,6 +579,7 @@ class FgsManagerController @Inject constructor(
override fun dump(printwriter: PrintWriter, args: Array<out String>) {
val pw = IndentingPrintWriter(printwriter)
synchronized(lock) {
+ pw.println("current user profiles = $currentProfileIds")
pw.println("changesSinceDialog=$changesSinceDialog")
pw.println("Running service tokens: [")
pw.indentIfPossible {
@@ -560,8 +598,10 @@ class FgsManagerController @Inject constructor(
pw.indentIfPossible {
runningApps.forEach { (userPackage, runningApp) ->
pw.println("{")
- userPackage.dump(pw)
- runningApp.dump(pw, systemClock)
+ pw.indentIfPossible {
+ userPackage.dump(pw)
+ runningApp.dump(pw, systemClock)
+ }
pw.println("}")
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QSSecurityFooter.java b/packages/SystemUI/src/com/android/systemui/qs/QSSecurityFooter.java
index dd99db49c1d2..584de6e8c28f 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/QSSecurityFooter.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/QSSecurityFooter.java
@@ -22,6 +22,9 @@ import static android.app.admin.DevicePolicyResources.Strings.SystemUi.QS_DIALOG
import static android.app.admin.DevicePolicyResources.Strings.SystemUi.QS_DIALOG_MANAGEMENT_NETWORK;
import static android.app.admin.DevicePolicyResources.Strings.SystemUi.QS_DIALOG_MANAGEMENT_TITLE;
import static android.app.admin.DevicePolicyResources.Strings.SystemUi.QS_DIALOG_MANAGEMENT_TWO_NAMED_VPN;
+import static android.app.admin.DevicePolicyResources.Strings.SystemUi.QS_DIALOG_MONITORING_CA_CERT_SUBTITLE;
+import static android.app.admin.DevicePolicyResources.Strings.SystemUi.QS_DIALOG_MONITORING_NETWORK_SUBTITLE;
+import static android.app.admin.DevicePolicyResources.Strings.SystemUi.QS_DIALOG_MONITORING_VPN_SUBTITLE;
import static android.app.admin.DevicePolicyResources.Strings.SystemUi.QS_DIALOG_NAMED_MANAGEMENT;
import static android.app.admin.DevicePolicyResources.Strings.SystemUi.QS_DIALOG_PERSONAL_PROFILE_NAMED_VPN;
import static android.app.admin.DevicePolicyResources.Strings.SystemUi.QS_DIALOG_VIEW_POLICIES;
@@ -92,6 +95,7 @@ import com.android.systemui.statusbar.policy.SecurityController;
import com.android.systemui.util.ViewController;
import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Supplier;
import javax.inject.Inject;
import javax.inject.Named;
@@ -106,7 +110,7 @@ class QSSecurityFooter extends ViewController<View>
private final TextView mFooterText;
private final ImageView mPrimaryFooterIcon;
- private final Context mContext;
+ private Context mContext;
private final DevicePolicyManager mDpm;
private final Callback mCallback = new Callback();
private final SecurityController mSecurityController;
@@ -141,6 +145,63 @@ class QSSecurityFooter extends ViewController<View>
}
};
+ private Supplier<String> mManagementTitleSupplier = () ->
+ mContext == null ? null : mContext.getString(R.string.monitoring_title_device_owned);
+
+ private Supplier<String> mManagementMessageSupplier = () ->
+ mContext == null ? null : mContext.getString(
+ R.string.quick_settings_disclosure_management);
+
+ private Supplier<String> mManagementMonitoringStringSupplier = () ->
+ mContext == null ? null : mContext.getString(
+ R.string.quick_settings_disclosure_management_monitoring);
+
+ private Supplier<String> mManagementMultipleVpnStringSupplier = () ->
+ mContext == null ? null : mContext.getString(
+ R.string.quick_settings_disclosure_management_vpns);
+
+ private Supplier<String> mWorkProfileMonitoringStringSupplier = () ->
+ mContext == null ? null : mContext.getString(
+ R.string.quick_settings_disclosure_managed_profile_monitoring);
+
+ private Supplier<String> mWorkProfileNetworkStringSupplier = () ->
+ mContext == null ? null : mContext.getString(
+ R.string.quick_settings_disclosure_managed_profile_network_activity);
+
+ private Supplier<String> mMonitoringSubtitleCaCertStringSupplier = () ->
+ mContext == null ? null : mContext.getString(
+ R.string.monitoring_subtitle_ca_certificate);
+
+ private Supplier<String> mMonitoringSubtitleNetworkStringSupplier = () ->
+ mContext == null ? null : mContext.getString(
+ R.string.monitoring_subtitle_network_logging);
+
+ private Supplier<String> mMonitoringSubtitleVpnStringSupplier = () ->
+ mContext == null ? null : mContext.getString(R.string.monitoring_subtitle_vpn);
+
+ private Supplier<String> mViewPoliciesButtonStringSupplier = () ->
+ mContext == null ? null : mContext.getString(R.string.monitoring_button_view_policies);
+
+ private Supplier<String> mManagementDialogStringSupplier = () ->
+ mContext == null ? null : mContext.getString(
+ R.string.monitoring_description_management);
+
+ private Supplier<String> mManagementDialogCaCertStringSupplier = () ->
+ mContext == null ? null : mContext.getString(
+ R.string.monitoring_description_management_ca_certificate);
+
+ private Supplier<String> mWorkProfileDialogCaCertStringSupplier = () ->
+ mContext == null ? null : mContext.getString(
+ R.string.monitoring_description_managed_profile_ca_certificate);
+
+ private Supplier<String> mManagementDialogNetworkStringSupplier = () ->
+ mContext == null ? null : mContext.getString(
+ R.string.monitoring_description_management_network_logging);
+
+ private Supplier<String> mWorkProfileDialogNetworkStringSupplier = () ->
+ mContext == null ? null : mContext.getString(
+ R.string.monitoring_description_managed_profile_network_logging);
+
@Inject
QSSecurityFooter(@Named(QS_SECURITY_FOOTER_VIEW) View rootView,
UserTracker userTracker, @Main Handler mainHandler,
@@ -337,9 +398,7 @@ class QSSecurityFooter extends ViewController<View>
private String getManagedDeviceMonitoringText(CharSequence organizationName) {
if (organizationName == null) {
return mDpm.getResources().getString(
- QS_MSG_MANAGEMENT_MONITORING,
- () -> mContext.getString(
- R.string.quick_settings_disclosure_management_monitoring));
+ QS_MSG_MANAGEMENT_MONITORING, mManagementMonitoringStringSupplier);
}
return mDpm.getResources().getString(
QS_MSG_NAMED_MANAGEMENT_MONITORING,
@@ -354,9 +413,7 @@ class QSSecurityFooter extends ViewController<View>
if (vpnName != null && vpnNameWorkProfile != null) {
if (organizationName == null) {
return mDpm.getResources().getString(
- QS_MSG_MANAGEMENT_MULTIPLE_VPNS,
- () -> mContext.getString(
- R.string.quick_settings_disclosure_management_vpns));
+ QS_MSG_MANAGEMENT_MULTIPLE_VPNS, mManagementMultipleVpnStringSupplier);
}
return mDpm.getResources().getString(
QS_MSG_NAMED_MANAGEMENT_MULTIPLE_VPNS,
@@ -386,10 +443,7 @@ class QSSecurityFooter extends ViewController<View>
private String getMangedDeviceGeneralText(CharSequence organizationName) {
if (organizationName == null) {
- return mDpm.getResources().getString(
- QS_MSG_MANAGEMENT,
- () -> mContext.getString(
- R.string.quick_settings_disclosure_management));
+ return mDpm.getResources().getString(QS_MSG_MANAGEMENT, mManagementMessageSupplier);
}
if (isFinancedDevice()) {
return mContext.getString(
@@ -431,9 +485,7 @@ class QSSecurityFooter extends ViewController<View>
if (hasCACertsInWorkProfile && isWorkProfileOn) {
if (workProfileOrganizationName == null) {
return mDpm.getResources().getString(
- QS_MSG_WORK_PROFILE_MONITORING,
- () -> mContext.getString(
- R.string.quick_settings_disclosure_managed_profile_monitoring));
+ QS_MSG_WORK_PROFILE_MONITORING, mWorkProfileMonitoringStringSupplier);
}
return mDpm.getResources().getString(
QS_MSG_NAMED_WORK_PROFILE_MONITORING,
@@ -478,10 +530,9 @@ class QSSecurityFooter extends ViewController<View>
private String getManagedProfileNetworkActivityText() {
return mDpm.getResources().getString(
- QS_MSG_WORK_PROFILE_NETWORK,
- () -> mContext.getString(
- R.string.quick_settings_disclosure_managed_profile_network_activity));
+ QS_MSG_WORK_PROFILE_NETWORK, mWorkProfileNetworkStringSupplier);
}
+
@Override
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_NEGATIVE) {
@@ -569,6 +620,12 @@ class QSSecurityFooter extends ViewController<View>
caCertsWarning.setText(caCertsMessage);
// Make "Open trusted credentials"-link clickable
caCertsWarning.setMovementMethod(new LinkMovementMethod());
+
+ TextView caCertsSubtitle = (TextView) dialogView.findViewById(R.id.ca_certs_subtitle);
+ String caCertsSubtitleMessage = mDpm.getResources().getString(
+ QS_DIALOG_MONITORING_CA_CERT_SUBTITLE, mMonitoringSubtitleCaCertStringSupplier);
+ caCertsSubtitle.setText(caCertsSubtitleMessage);
+
}
// network logging section
@@ -581,6 +638,13 @@ class QSSecurityFooter extends ViewController<View>
TextView networkLoggingWarning =
(TextView) dialogView.findViewById(R.id.network_logging_warning);
networkLoggingWarning.setText(networkLoggingMessage);
+
+ TextView networkLoggingSubtitle = (TextView) dialogView.findViewById(
+ R.id.network_logging_subtitle);
+ String networkLoggingSubtitleMessage = mDpm.getResources().getString(
+ QS_DIALOG_MONITORING_NETWORK_SUBTITLE,
+ mMonitoringSubtitleNetworkStringSupplier);
+ networkLoggingSubtitle.setText(networkLoggingSubtitleMessage);
}
// vpn section
@@ -594,6 +658,11 @@ class QSSecurityFooter extends ViewController<View>
vpnWarning.setText(vpnMessage);
// Make "Open VPN Settings"-link clickable
vpnWarning.setMovementMethod(new LinkMovementMethod());
+
+ TextView vpnSubtitle = (TextView) dialogView.findViewById(R.id.vpn_subtitle);
+ String vpnSubtitleMessage = mDpm.getResources().getString(
+ QS_DIALOG_MONITORING_VPN_SUBTITLE, mMonitoringSubtitleVpnStringSupplier);
+ vpnSubtitle.setText(vpnSubtitleMessage);
}
// Note: if a new section is added, should update configSubtitleVisibility to include
@@ -657,8 +726,7 @@ class QSSecurityFooter extends ViewController<View>
@VisibleForTesting
String getSettingsButton() {
return mDpm.getResources().getString(
- QS_DIALOG_VIEW_POLICIES,
- () -> mContext.getString(R.string.monitoring_button_view_policies));
+ QS_DIALOG_VIEW_POLICIES, mViewPoliciesButtonStringSupplier);
}
private String getPositiveButton() {
@@ -692,9 +760,7 @@ class QSSecurityFooter extends ViewController<View>
organizationName);
}
}
- return mDpm.getResources().getString(
- QS_DIALOG_MANAGEMENT,
- () -> mContext.getString(R.string.monitoring_description_management));
+ return mDpm.getResources().getString(QS_DIALOG_MANAGEMENT, mManagementDialogStringSupplier);
}
@Nullable
@@ -703,15 +769,11 @@ class QSSecurityFooter extends ViewController<View>
if (!(hasCACerts || hasCACertsInWorkProfile)) return null;
if (isDeviceManaged) {
return mDpm.getResources().getString(
- QS_DIALOG_MANAGEMENT_CA_CERT,
- () -> mContext.getString(
- R.string.monitoring_description_management_ca_certificate));
+ QS_DIALOG_MANAGEMENT_CA_CERT, mManagementDialogCaCertStringSupplier);
}
if (hasCACertsInWorkProfile) {
return mDpm.getResources().getString(
- QS_DIALOG_WORK_PROFILE_CA_CERT,
- () -> mContext.getString(
- R.string.monitoring_description_managed_profile_ca_certificate));
+ QS_DIALOG_WORK_PROFILE_CA_CERT, mWorkProfileDialogCaCertStringSupplier);
}
return mContext.getString(R.string.monitoring_description_ca_certificate);
}
@@ -722,14 +784,10 @@ class QSSecurityFooter extends ViewController<View>
if (!isNetworkLoggingEnabled) return null;
if (isDeviceManaged) {
return mDpm.getResources().getString(
- QS_DIALOG_MANAGEMENT_NETWORK,
- () -> mContext.getString(
- R.string.monitoring_description_management_network_logging));
+ QS_DIALOG_MANAGEMENT_NETWORK, mManagementDialogNetworkStringSupplier);
} else {
return mDpm.getResources().getString(
- QS_DIALOG_WORK_PROFILE_NETWORK,
- () -> mContext.getString(
- R.string.monitoring_description_managed_profile_network_logging));
+ QS_DIALOG_WORK_PROFILE_NETWORK, mWorkProfileDialogNetworkStringSupplier);
}
}
@@ -799,7 +857,7 @@ class QSSecurityFooter extends ViewController<View>
} else {
return mDpm.getResources().getString(
QS_DIALOG_MANAGEMENT_TITLE,
- () -> mContext.getString(R.string.monitoring_title_device_owned));
+ mManagementTitleSupplier);
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/DreamTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/DreamTile.java
index 8cb7185a18b3..22e725b41a64 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/DreamTile.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/DreamTile.java
@@ -27,7 +27,6 @@ import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.RemoteException;
-import android.os.UserManager;
import android.provider.Settings;
import android.service.dreams.IDreamManager;
import android.service.quicksettings.Tile;
@@ -52,6 +51,7 @@ import com.android.systemui.qs.QSHost;
import com.android.systemui.qs.SettingObserver;
import com.android.systemui.qs.logging.QSLogger;
import com.android.systemui.qs.tileimpl.QSTileImpl;
+import com.android.systemui.settings.UserTracker;
import com.android.systemui.util.settings.SecureSettings;
import javax.inject.Inject;
@@ -61,11 +61,12 @@ import javax.inject.Named;
public class DreamTile extends QSTileImpl<QSTile.BooleanState> {
private static final String LOG_TAG = "QSDream";
+ private final Icon mIcon = ResourceIcon.get(R.drawable.ic_qs_screen_saver);
private final IDreamManager mDreamManager;
private final BroadcastDispatcher mBroadcastDispatcher;
private final SettingObserver mEnabledSettingObserver;
private final SettingObserver mDreamSettingObserver;
- private final UserManager mUserManager;
+ private final UserTracker mUserTracker;
private final boolean mDreamSupported;
private final boolean mDreamOnlyEnabledForSystemUser;
@@ -89,7 +90,7 @@ public class DreamTile extends QSTileImpl<QSTile.BooleanState> {
IDreamManager dreamManager,
SecureSettings secureSettings,
BroadcastDispatcher broadcastDispatcher,
- UserManager userManager,
+ UserTracker userTracker,
@Named(DreamModule.DREAM_SUPPORTED) boolean dreamSupported,
@Named(DreamModule.DREAM_ONLY_ENABLED_FOR_SYSTEM_USER)
boolean dreamOnlyEnabledForSystemUser
@@ -112,7 +113,7 @@ public class DreamTile extends QSTileImpl<QSTile.BooleanState> {
refreshState();
}
};
- mUserManager = userManager;
+ mUserTracker = userTracker;
mDreamSupported = dreamSupported;
mDreamOnlyEnabledForSystemUser = dreamOnlyEnabledForSystemUser;
}
@@ -167,6 +168,7 @@ public class DreamTile extends QSTileImpl<QSTile.BooleanState> {
state.label = getTileLabel();
state.secondaryLabel = getActiveDreamName();
state.contentDescription = getContentDescription(state.secondaryLabel);
+ state.icon = mIcon;
if (getActiveDream() == null || !isScreensaverEnabled()) {
state.state = Tile.STATE_UNAVAILABLE;
@@ -192,7 +194,7 @@ public class DreamTile extends QSTileImpl<QSTile.BooleanState> {
// For now, restrict to debug users.
return Build.isDebuggable()
&& mDreamSupported
- && (!mDreamOnlyEnabledForSystemUser || mUserManager.isSystemUser());
+ && (!mDreamOnlyEnabledForSystemUser || mUserTracker.getUserHandle().isSystem());
}
@VisibleForTesting
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/HotspotTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/HotspotTile.java
index d7aa8b21a150..7c8e77b5d993 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/HotspotTile.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/HotspotTile.java
@@ -30,6 +30,7 @@ import androidx.annotation.Nullable;
import com.android.internal.logging.MetricsLogger;
import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
+import com.android.settingslib.wifi.WifiEnterpriseRestrictionUtils;
import com.android.systemui.R;
import com.android.systemui.dagger.qualifiers.Background;
import com.android.systemui.dagger.qualifiers.Main;
@@ -158,7 +159,9 @@ public class HotspotTile extends QSTileImpl<BooleanState> {
state.expandedAccessibilityClassName = Switch.class.getName();
state.contentDescription = state.label;
- final boolean isTileUnavailable = isDataSaverEnabled;
+ final boolean isWifiTetheringAllowed =
+ WifiEnterpriseRestrictionUtils.isWifiTetheringAllowed(mHost.getUserContext());
+ final boolean isTileUnavailable = isDataSaverEnabled || !isWifiTetheringAllowed;
final boolean isTileActive = (state.value || state.isTransient);
if (isTileUnavailable) {
@@ -167,15 +170,17 @@ public class HotspotTile extends QSTileImpl<BooleanState> {
state.state = isTileActive ? Tile.STATE_ACTIVE : Tile.STATE_INACTIVE;
}
- state.secondaryLabel = getSecondaryLabel(
- isTileActive, isTransient, isDataSaverEnabled, numConnectedDevices);
+ state.secondaryLabel = getSecondaryLabel(isTileActive, isTransient, isDataSaverEnabled,
+ numConnectedDevices, isWifiTetheringAllowed);
state.stateDescription = state.secondaryLabel;
}
@Nullable
private String getSecondaryLabel(boolean isActive, boolean isTransient,
- boolean isDataSaverEnabled, int numConnectedDevices) {
- if (isTransient) {
+ boolean isDataSaverEnabled, int numConnectedDevices, boolean isWifiTetheringAllowed) {
+ if (!isWifiTetheringAllowed) {
+ return mContext.getString(R.string.wifitrackerlib_admin_restricted_network);
+ } else if (isTransient) {
return mContext.getString(R.string.quick_settings_hotspot_secondary_label_transient);
} else if (isDataSaverEnabled) {
return mContext.getString(
diff --git a/packages/SystemUI/src/com/android/systemui/screenshot/ScreenshotController.java b/packages/SystemUI/src/com/android/systemui/screenshot/ScreenshotController.java
index 4728c678f96c..489f881c36cf 100644
--- a/packages/SystemUI/src/com/android/systemui/screenshot/ScreenshotController.java
+++ b/packages/SystemUI/src/com/android/systemui/screenshot/ScreenshotController.java
@@ -78,7 +78,6 @@ import android.view.ViewTreeObserver;
import android.view.WindowInsets;
import android.view.WindowManager;
import android.view.WindowManagerGlobal;
-import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityManager;
import android.widget.Toast;
import android.window.WindowContext;
@@ -484,6 +483,7 @@ public class ScreenshotController {
setWindowFocusable(false);
}
});
+ mScreenshotView.setDefaultTimeoutMillis(mScreenshotHandler.getDefaultTimeoutMillis());
mScreenshotView.setOnKeyListener((v, keyCode, event) -> {
if (keyCode == KeyEvent.KEYCODE_BACK) {
@@ -558,14 +558,9 @@ public class ScreenshotController {
private void saveScreenshot(Bitmap screenshot, Consumer<Uri> finisher, Rect screenRect,
Insets screenInsets, ComponentName topComponent, boolean showFlash) {
- if (mAccessibilityManager.isEnabled()) {
- AccessibilityEvent event =
- new AccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
- event.setContentDescription(
- mContext.getResources().getString(R.string.screenshot_saving_title));
- mAccessibilityManager.sendAccessibilityEvent(event);
- }
-
+ withWindowAttached(() ->
+ mScreenshotView.announceForAccessibility(
+ mContext.getResources().getString(R.string.screenshot_saving_title)));
if (mScreenshotView.isAttachedToWindow()) {
// if we didn't already dismiss for another reason
@@ -632,6 +627,7 @@ public class ScreenshotController {
}
}
}
+
@Override
public void requestCompatCameraControl(boolean showControl,
boolean transformationApplied,
@@ -717,6 +713,7 @@ public class ScreenshotController {
Log.e(TAG, "requestScrollCapture failed", e);
}
}
+
ListenableFuture<ScrollCaptureController.LongScreenshot> mLongScreenshotFuture;
private void runBatchScrollCapture(ScrollCaptureResponse response) {
diff --git a/packages/SystemUI/src/com/android/systemui/screenshot/ScreenshotView.java b/packages/SystemUI/src/com/android/systemui/screenshot/ScreenshotView.java
index ccfcaa692e22..79939c87173b 100644
--- a/packages/SystemUI/src/com/android/systemui/screenshot/ScreenshotView.java
+++ b/packages/SystemUI/src/com/android/systemui/screenshot/ScreenshotView.java
@@ -18,6 +18,7 @@ package com.android.systemui.screenshot;
import static android.content.res.Configuration.ORIENTATION_PORTRAIT;
+import static com.android.internal.jank.InteractionJankMonitor.CUJ_TAKE_SCREENSHOT;
import static com.android.systemui.screenshot.LogConfig.DEBUG_ANIM;
import static com.android.systemui.screenshot.LogConfig.DEBUG_DISMISS;
import static com.android.systemui.screenshot.LogConfig.DEBUG_INPUT;
@@ -83,6 +84,7 @@ import android.widget.LinearLayout;
import androidx.constraintlayout.widget.ConstraintLayout;
+import com.android.internal.jank.InteractionJankMonitor;
import com.android.internal.logging.UiEventLogger;
import com.android.systemui.R;
import com.android.systemui.screenshot.ScreenshotController.SavedImageData.ActionTransition;
@@ -166,6 +168,9 @@ public class ScreenshotView extends FrameLayout implements
private final ArrayList<OverlayActionChip> mSmartChips = new ArrayList<>();
private PendingInteraction mPendingInteraction;
+ private final InteractionJankMonitor mInteractionJankMonitor;
+ private long mDefaultTimeoutOfTimeoutHandler;
+
private enum PendingInteraction {
PREVIEW,
EDIT,
@@ -189,6 +194,7 @@ public class ScreenshotView extends FrameLayout implements
Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
mResources = mContext.getResources();
+ mInteractionJankMonitor = getInteractionJankMonitorInstance();
mFixedSize = mResources.getDimensionPixelSize(R.dimen.overlay_x_scale);
@@ -229,6 +235,14 @@ public class ScreenshotView extends FrameLayout implements
});
}
+ private InteractionJankMonitor getInteractionJankMonitorInstance() {
+ return InteractionJankMonitor.getInstance();
+ }
+
+ void setDefaultTimeoutMillis(long timeout) {
+ mDefaultTimeoutOfTimeoutHandler = timeout;
+ }
+
public void hideScrollChip() {
mScrollChip.setVisibility(View.GONE);
}
@@ -395,6 +409,9 @@ public class ScreenshotView extends FrameLayout implements
@Override
public void onDismissComplete() {
+ if (mInteractionJankMonitor.isInstrumenting(CUJ_TAKE_SCREENSHOT)) {
+ mInteractionJankMonitor.end(CUJ_TAKE_SCREENSHOT);
+ }
mCallbacks.onDismiss();
}
});
@@ -595,6 +612,20 @@ public class ScreenshotView extends FrameLayout implements
dropInAnimation.addListener(new AnimatorListenerAdapter() {
@Override
+ public void onAnimationCancel(Animator animation) {
+ mInteractionJankMonitor.cancel(CUJ_TAKE_SCREENSHOT);
+ }
+
+ @Override
+ public void onAnimationStart(Animator animation) {
+ InteractionJankMonitor.Configuration.Builder builder =
+ InteractionJankMonitor.Configuration.Builder.withView(
+ CUJ_TAKE_SCREENSHOT, mScreenshotPreview)
+ .setTag("DropIn");
+ mInteractionJankMonitor.begin(builder);
+ }
+
+ @Override
public void onAnimationEnd(Animator animation) {
if (DEBUG_ANIM) {
Log.d(TAG, "drop-in animation ended");
@@ -620,7 +651,7 @@ public class ScreenshotView extends FrameLayout implements
mScreenshotPreview.setX(finalPos.x - mScreenshotPreview.getWidth() / 2f);
mScreenshotPreview.setY(finalPos.y - mScreenshotPreview.getHeight() / 2f);
requestLayout();
-
+ mInteractionJankMonitor.end(CUJ_TAKE_SCREENSHOT);
createScreenshotActionsShadeAnimation().start();
}
});
@@ -691,6 +722,28 @@ public class ScreenshotView extends FrameLayout implements
mActionsContainer.setVisibility(View.VISIBLE);
mActionsContainerBackground.setVisibility(View.VISIBLE);
+ animator.addListener(new AnimatorListenerAdapter() {
+ @Override
+ public void onAnimationCancel(Animator animation) {
+ mInteractionJankMonitor.cancel(CUJ_TAKE_SCREENSHOT);
+ }
+
+ @Override
+ public void onAnimationEnd(Animator animation) {
+ mInteractionJankMonitor.end(CUJ_TAKE_SCREENSHOT);
+ }
+
+ @Override
+ public void onAnimationStart(Animator animation) {
+ InteractionJankMonitor.Configuration.Builder builder =
+ InteractionJankMonitor.Configuration.Builder.withView(
+ CUJ_TAKE_SCREENSHOT, mScreenshotStatic)
+ .setTag("Actions")
+ .setTimeout(mDefaultTimeoutOfTimeoutHandler);
+ mInteractionJankMonitor.begin(builder);
+ }
+ });
+
animator.addUpdateListener(animation -> {
float t = animation.getAnimatedFraction();
float containerAlpha = t < alphaFraction ? t / alphaFraction : 1;
@@ -767,7 +820,7 @@ public class ScreenshotView extends FrameLayout implements
animateDismissal();
});
actionChip.setAlpha(1);
- mActionsView.addView(actionChip);
+ mActionsView.addView(actionChip, mActionsView.getChildCount() - 1);
mSmartChips.add(actionChip);
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/screenshot/TakeScreenshotService.java b/packages/SystemUI/src/com/android/systemui/screenshot/TakeScreenshotService.java
index 7f3758e208db..2621f6da7afa 100644
--- a/packages/SystemUI/src/com/android/systemui/screenshot/TakeScreenshotService.java
+++ b/packages/SystemUI/src/com/android/systemui/screenshot/TakeScreenshotService.java
@@ -16,6 +16,7 @@
package com.android.systemui.screenshot;
+import static android.app.admin.DevicePolicyResources.Strings.SystemUi.SCREENSHOT_BLOCKED_BY_ADMIN;
import static android.content.Intent.ACTION_CLOSE_SYSTEM_DIALOGS;
import static com.android.internal.util.ScreenshotHelper.SCREENSHOT_MSG_PROCESS_COMPLETE;
@@ -54,7 +55,9 @@ import androidx.annotation.NonNull;
import com.android.internal.logging.UiEventLogger;
import com.android.internal.util.ScreenshotHelper;
import com.android.systemui.R;
+import com.android.systemui.dagger.qualifiers.Background;
+import java.util.concurrent.Executor;
import java.util.function.Consumer;
import javax.inject.Inject;
@@ -70,6 +73,7 @@ public class TakeScreenshotService extends Service {
private final ScreenshotNotificationsController mNotificationsController;
private final Handler mHandler;
private final Context mContext;
+ private final @Background Executor mBgExecutor;
private final BroadcastReceiver mCloseSystemDialogs = new BroadcastReceiver() {
@Override
@@ -97,7 +101,8 @@ public class TakeScreenshotService extends Service {
@Inject
public TakeScreenshotService(ScreenshotController screenshotController, UserManager userManager,
DevicePolicyManager devicePolicyManager, UiEventLogger uiEventLogger,
- ScreenshotNotificationsController notificationsController, Context context) {
+ ScreenshotNotificationsController notificationsController, Context context,
+ @Background Executor bgExecutor) {
if (DEBUG_SERVICE) {
Log.d(TAG, "new " + this);
}
@@ -108,6 +113,7 @@ public class TakeScreenshotService extends Service {
mUiEventLogger = uiEventLogger;
mNotificationsController = notificationsController;
mContext = context;
+ mBgExecutor = bgExecutor;
}
@Override
@@ -189,12 +195,18 @@ public class TakeScreenshotService extends Service {
requestCallback.reportError();
return true;
}
- if(mDevicePolicyManager.getScreenCaptureDisabled(null, UserHandle.USER_ALL)) {
- Log.w(TAG, "Skipping screenshot because an IT admin has disabled "
- + "screenshots on the device");
- Toast.makeText(mContext, R.string.screenshot_blocked_by_admin,
- Toast.LENGTH_SHORT).show();
- requestCallback.reportError();
+
+ if (mDevicePolicyManager.getScreenCaptureDisabled(null, UserHandle.USER_ALL)) {
+ mBgExecutor.execute(() -> {
+ Log.w(TAG, "Skipping screenshot because an IT admin has disabled "
+ + "screenshots on the device");
+ String blockedByAdminText = mDevicePolicyManager.getResources().getString(
+ SCREENSHOT_BLOCKED_BY_ADMIN,
+ () -> mContext.getString(R.string.screenshot_blocked_by_admin));
+ mHandler.post(() ->
+ Toast.makeText(mContext, blockedByAdminText, Toast.LENGTH_SHORT).show());
+ requestCallback.reportError();
+ });
return true;
}
diff --git a/packages/SystemUI/src/com/android/systemui/screenshot/TimeoutHandler.java b/packages/SystemUI/src/com/android/systemui/screenshot/TimeoutHandler.java
index 9156601e6638..71c2cb4a5cb9 100644
--- a/packages/SystemUI/src/com/android/systemui/screenshot/TimeoutHandler.java
+++ b/packages/SystemUI/src/com/android/systemui/screenshot/TimeoutHandler.java
@@ -72,6 +72,10 @@ public class TimeoutHandler extends Handler {
mDefaultTimeout = timeout;
}
+ int getDefaultTimeoutMillis() {
+ return mDefaultTimeout;
+ }
+
/**
* Cancel the current timeout, if any. To reset the delayed runnable use resetTimeout instead.
*/
diff --git a/packages/SystemUI/src/com/android/systemui/scrim/ScrimView.java b/packages/SystemUI/src/com/android/systemui/scrim/ScrimView.java
index 7530681c82b2..f68e0429ef7c 100644
--- a/packages/SystemUI/src/com/android/systemui/scrim/ScrimView.java
+++ b/packages/SystemUI/src/com/android/systemui/scrim/ScrimView.java
@@ -58,6 +58,7 @@ public class ScrimView extends View {
private Drawable mDrawable;
private PorterDuffColorFilter mColorFilter;
private int mTintColor;
+ private boolean mBlendWithMainColor = true;
private Runnable mChangeRunnable;
private Executor mChangeRunnableExecutor;
private Executor mExecutor;
@@ -192,6 +193,19 @@ public class ScrimView extends View {
}
/**
+ * The call to {@link #setTint} will blend with the main color, with the amount
+ * determined by the alpha of the tint. Set to false to avoid this blend.
+ */
+ public void setBlendWithMainColor(boolean blend) {
+ mBlendWithMainColor = blend;
+ }
+
+ /** @return true if blending tint color with main color */
+ public boolean shouldBlendWithMainColor() {
+ return mBlendWithMainColor;
+ }
+
+ /**
* Tints this view, optionally animating it.
* @param color The color.
* @param animated If we should animate.
@@ -211,8 +225,11 @@ public class ScrimView extends View {
// Optimization to blend colors and avoid a color filter
ScrimDrawable drawable = (ScrimDrawable) mDrawable;
float tintAmount = Color.alpha(mTintColor) / 255f;
- int mainTinted = ColorUtils.blendARGB(mColors.getMainColor(), mTintColor,
- tintAmount);
+
+ int mainTinted = mTintColor;
+ if (mBlendWithMainColor) {
+ mainTinted = ColorUtils.blendARGB(mColors.getMainColor(), mTintColor, tintAmount);
+ }
drawable.setColor(mainTinted, animated);
} else {
boolean hasAlpha = Color.alpha(mTintColor) != 0;
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/HeadsUpStatusBarView.java b/packages/SystemUI/src/com/android/systemui/statusbar/HeadsUpStatusBarView.java
index 4d933d9ad21e..e44d334c776d 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/HeadsUpStatusBarView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/HeadsUpStatusBarView.java
@@ -29,7 +29,6 @@ import com.android.keyguard.AlphaOptimizedLinearLayout;
import com.android.systemui.R;
import com.android.systemui.plugins.DarkIconDispatcher;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
-import com.android.systemui.statusbar.notification.collection.NotificationEntry.OnSensitivityChangedListener;
import java.util.ArrayList;
@@ -49,6 +48,7 @@ public class HeadsUpStatusBarView extends AlphaOptimizedLinearLayout {
private TextView mTextView;
private NotificationEntry mShowingEntry;
private Runnable mOnDrawingRectChangedListener;
+ private boolean mRedactSensitiveContent;
public HeadsUpStatusBarView(Context context) {
this(context, null);
@@ -111,29 +111,28 @@ public class HeadsUpStatusBarView extends AlphaOptimizedLinearLayout {
}
public void setEntry(NotificationEntry entry) {
- if (mShowingEntry != null) {
- mShowingEntry.removeOnSensitivityChangedListener(mOnSensitivityChangedListener);
- }
mShowingEntry = entry;
-
if (mShowingEntry != null) {
CharSequence text = entry.headsUpStatusBarText;
- if (entry.isSensitive()) {
+ if (mRedactSensitiveContent && entry.hasSensitiveContents()) {
text = entry.headsUpStatusBarTextPublic;
}
mTextView.setText(text);
- mShowingEntry.addOnSensitivityChangedListener(mOnSensitivityChangedListener);
}
}
- private final OnSensitivityChangedListener mOnSensitivityChangedListener = entry -> {
- if (entry != mShowingEntry) {
- throw new IllegalStateException("Got a sensitivity change for " + entry
- + " but mShowingEntry is " + mShowingEntry);
+ public void setRedactSensitiveContent(boolean redactSensitiveContent) {
+ if (mRedactSensitiveContent == redactSensitiveContent) {
+ return;
+ }
+ mRedactSensitiveContent = redactSensitiveContent;
+ if (mShowingEntry != null && mShowingEntry.hasSensitiveContents()) {
+ mTextView.setText(
+ mRedactSensitiveContent
+ ? mShowingEntry.headsUpStatusBarTextPublic
+ : mShowingEntry.headsUpStatusBarText);
}
- // Update the text
- setEntry(entry);
- };
+ }
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/LockscreenShadeTransitionController.kt b/packages/SystemUI/src/com/android/systemui/statusbar/LockscreenShadeTransitionController.kt
index c1ea6bf7cec8..cbe722b6f82f 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/LockscreenShadeTransitionController.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/LockscreenShadeTransitionController.kt
@@ -386,7 +386,7 @@ class LockscreenShadeTransitionController @Inject constructor(
}
if (view is ExpandableNotificationRow) {
// Only drag down on sensitive views, otherwise the ExpandHelper will take this
- return view.entry.isSensitive
+ return lockScreenUserManager.notifNeedsRedactionInPublic(view.entry)
}
}
return false
@@ -552,7 +552,8 @@ class LockscreenShadeTransitionController @Inject constructor(
logger.logShadeDisabledOnGoToLockedShade()
return
}
- var userId: Int = lockScreenUserManager.getCurrentUserId()
+ val currentUser = lockScreenUserManager.currentUserId
+ var userId: Int = currentUser
var entry: NotificationEntry? = null
if (expandView is ExpandableNotificationRow) {
entry = expandView.entry
@@ -562,12 +563,18 @@ class LockscreenShadeTransitionController @Inject constructor(
entry.setGroupExpansionChanging(true)
userId = entry.sbn.userId
}
- var fullShadeNeedsBouncer = (!lockScreenUserManager.userAllowsPrivateNotificationsInPublic(
- lockScreenUserManager.getCurrentUserId()) ||
- !lockScreenUserManager.shouldShowLockscreenNotifications() ||
- falsingCollector.shouldEnforceBouncer())
- if (keyguardBypassController.bypassEnabled) {
- fullShadeNeedsBouncer = false
+ val fullShadeNeedsBouncer = when {
+ // No bouncer necessary if we're bypassing
+ keyguardBypassController.bypassEnabled -> false
+ // Redacted notificationss are present, bouncer should be shown before un-redacting in
+ // the full shade
+ lockScreenUserManager.sensitiveNotifsNeedRedactionInPublic(currentUser) -> true
+ // Notifications are hidden in public, bouncer should be shown before showing them in
+ // the full shade
+ !lockScreenUserManager.shouldShowLockscreenNotifications() -> true
+ // Bouncer is being enforced, so we need to show it
+ falsingCollector.shouldEnforceBouncer() -> true
+ else -> false
}
if (lockScreenUserManager.isLockscreenPublicMode(userId) && fullShadeNeedsBouncer) {
statusBarStateController.setLeaveOpenOnKeyguardHide(true)
@@ -911,4 +918,4 @@ class DragDownHelper(
host.getLocationOnScreen(temp2)
return expandCallback.getChildAtRawPosition(x + temp2[0], y + temp2[1])
}
-} \ No newline at end of file
+}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationLockscreenUserManager.java b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationLockscreenUserManager.java
index 9a1a144924e2..5fd9671bda01 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationLockscreenUserManager.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationLockscreenUserManager.java
@@ -71,17 +71,22 @@ public interface NotificationLockscreenUserManager {
boolean shouldHideNotifications(String key);
boolean shouldShowOnKeyguard(NotificationEntry entry);
+ void addOnNeedsRedactionInPublicChangedListener(Runnable listener);
+
+ void removeOnNeedsRedactionInPublicChangedListener(Runnable listener);
+
boolean isAnyProfilePublicMode();
void updatePublicMode();
- boolean needsRedaction(NotificationEntry entry);
+ /** Does this notification require redaction if it is displayed when the device is public? */
+ boolean notifNeedsRedactionInPublic(NotificationEntry entry);
/**
- * Has the given user chosen to allow their private (full) notifications to be shown even
- * when the lockscreen is in "public" (secure & locked) mode?
+ * Do all sensitive notifications belonging to the given user require redaction when they are
+ * displayed in public?
*/
- boolean userAllowsPrivateNotificationsInPublic(int currentUserId);
+ boolean sensitiveNotifsNeedRedactionInPublic(int userId);
/**
* Has the given user chosen to allow notifications to be shown even when the lockscreen is in
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationLockscreenUserManagerImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationLockscreenUserManagerImpl.java
index 56e09f03aa6b..334cfe5f4c41 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationLockscreenUserManagerImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationLockscreenUserManagerImpl.java
@@ -24,7 +24,6 @@ import static com.android.systemui.statusbar.notification.stack.NotificationPrio
import android.app.ActivityManager;
import android.app.KeyguardManager;
-import android.app.Notification;
import android.app.NotificationManager;
import android.app.admin.DevicePolicyManager;
import android.content.BroadcastReceiver;
@@ -45,7 +44,6 @@ import android.util.SparseBooleanArray;
import com.android.internal.statusbar.NotificationVisibility;
import com.android.internal.widget.LockPatternUtils;
import com.android.keyguard.KeyguardUpdateMonitor;
-import com.android.systemui.Dependency;
import com.android.systemui.Dumpable;
import com.android.systemui.broadcast.BroadcastDispatcher;
import com.android.systemui.dagger.SysUISingleton;
@@ -60,6 +58,7 @@ import com.android.systemui.statusbar.notification.collection.notifcollection.Co
import com.android.systemui.statusbar.notification.collection.render.NotificationVisibilityProvider;
import com.android.systemui.statusbar.policy.DeviceProvisionedController;
import com.android.systemui.statusbar.policy.KeyguardStateController;
+import com.android.systemui.util.ListenerSet;
import com.android.systemui.util.settings.SecureSettings;
import java.io.PrintWriter;
@@ -85,13 +84,12 @@ public class NotificationLockscreenUserManagerImpl implements
private final DeviceProvisionedController mDeviceProvisionedController;
private final KeyguardStateController mKeyguardStateController;
private final SecureSettings mSecureSettings;
+ private final KeyguardUpdateMonitor mKeyguardUpdateMonitor;
+ private final Lazy<OverviewProxyService> mOverviewProxyService;
private final Object mLock = new Object();
-
- // Lazy
- private NotificationEntryManager mEntryManager;
-
private final Lazy<NotificationVisibilityProvider> mVisibilityProviderLazy;
private final Lazy<CommonNotifCollection> mCommonNotifCollectionLazy;
+ private final Lazy<NotificationEntryManager> mEntryManagerLazy;
private final DevicePolicyManager mDevicePolicyManager;
private final SparseBooleanArray mLockscreenPublicMode = new SparseBooleanArray();
private final SparseBooleanArray mUsersWithSeparateWorkChallenge = new SparseBooleanArray();
@@ -103,13 +101,14 @@ public class NotificationLockscreenUserManagerImpl implements
private final List<UserChangedListener> mListeners = new ArrayList<>();
private final BroadcastDispatcher mBroadcastDispatcher;
private final NotificationClickNotifier mClickNotifier;
-
- private boolean mShowLockscreenNotifications;
- private boolean mAllowLockscreenRemoteInput;
- private LockPatternUtils mLockPatternUtils;
- protected KeyguardManager mKeyguardManager;
- private int mState = StatusBarState.SHADE;
- private List<KeyguardNotificationSuppressor> mKeyguardSuppressors = new ArrayList<>();
+ private final LockPatternUtils mLockPatternUtils;
+ private final List<KeyguardNotificationSuppressor> mKeyguardSuppressors = new ArrayList<>();
+ protected final Context mContext;
+ private final Handler mMainHandler;
+ protected final SparseArray<UserInfo> mCurrentProfiles = new SparseArray<>();
+ protected final SparseArray<UserInfo> mCurrentManagedProfiles = new SparseArray<>();
+ private final ListenerSet<Runnable> mOnSensitiveContentRedactionChangeListeners =
+ new ListenerSet<>();
protected final BroadcastReceiver mAllUsersReceiver = new BroadcastReceiver() {
@Override
@@ -120,7 +119,11 @@ public class NotificationLockscreenUserManagerImpl implements
isCurrentProfile(getSendingUserId())) {
mUsersAllowingPrivateNotifications.clear();
updateLockscreenNotificationSetting();
- getEntryManager().updateNotifications("ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED");
+ for (Runnable listener : mOnSensitiveContentRedactionChangeListeners) {
+ listener.run();
+ }
+ mEntryManagerLazy.get()
+ .updateNotifications("ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED");
}
}
};
@@ -142,7 +145,7 @@ public class NotificationLockscreenUserManagerImpl implements
// The filtering needs to happen before the update call below in order to
// make sure
// the presenter has the updated notifications from the new user
- getEntryManager().reapplyFilterAndSort("user switched");
+ mEntryManagerLazy.get().reapplyFilterAndSort("user switched");
mPresenter.onUserSwitched(mCurrentUserId);
for (UserChangedListener listener : mListeners) {
@@ -156,7 +159,7 @@ public class NotificationLockscreenUserManagerImpl implements
break;
case Intent.ACTION_USER_UNLOCKED:
// Start the overview connection to the launcher service
- Dependency.get(OverviewProxyService.class).startConnectionToCurrentUser();
+ mOverviewProxyService.get().startConnectionToCurrentUser();
break;
case NOTIFICATION_UNLOCKED_BY_WORK_CHALLENGE_ACTION:
final IntentSender intentSender = intent.getParcelableExtra(
@@ -179,28 +182,26 @@ public class NotificationLockscreenUserManagerImpl implements
}
};
- protected final Context mContext;
- private final Handler mMainHandler;
- protected final SparseArray<UserInfo> mCurrentProfiles = new SparseArray<>();
- protected final SparseArray<UserInfo> mCurrentManagedProfiles = new SparseArray<>();
-
- protected int mCurrentUserId = 0;
+ // Late-init
protected NotificationPresenter mPresenter;
protected ContentObserver mLockscreenSettingsObserver;
protected ContentObserver mSettingsObserver;
- private boolean mHideSilentNotificationsOnLockscreen;
+ protected KeyguardManager mKeyguardManager;
- private NotificationEntryManager getEntryManager() {
- if (mEntryManager == null) {
- mEntryManager = Dependency.get(NotificationEntryManager.class);
- }
- return mEntryManager;
- }
+ protected int mCurrentUserId = 0;
+ private int mState = StatusBarState.SHADE;
+ private boolean mHideSilentNotificationsOnLockscreen;
+ private boolean mShowLockscreenNotifications;
+ private boolean mAllowLockscreenRemoteInput;
@Inject
- public NotificationLockscreenUserManagerImpl(Context context,
+ public NotificationLockscreenUserManagerImpl(
+ Context context,
BroadcastDispatcher broadcastDispatcher,
DevicePolicyManager devicePolicyManager,
+ KeyguardUpdateMonitor keyguardUpdateMonitor,
+ Lazy<NotificationEntryManager> notificationEntryManagerLazy,
+ Lazy<OverviewProxyService> overviewProxyServiceLazy,
UserManager userManager,
Lazy<NotificationVisibilityProvider> visibilityProviderLazy,
Lazy<CommonNotifCollection> commonNotifCollectionLazy,
@@ -216,9 +217,11 @@ public class NotificationLockscreenUserManagerImpl implements
mMainHandler = mainHandler;
mDevicePolicyManager = devicePolicyManager;
mUserManager = userManager;
+ mOverviewProxyService = overviewProxyServiceLazy;
mCurrentUserId = ActivityManager.getCurrentUser();
mVisibilityProviderLazy = visibilityProviderLazy;
mCommonNotifCollectionLazy = commonNotifCollectionLazy;
+ mEntryManagerLazy = notificationEntryManagerLazy;
mClickNotifier = clickNotifier;
statusBarStateController.addCallback(this);
mLockPatternUtils = new LockPatternUtils(context);
@@ -227,10 +230,12 @@ public class NotificationLockscreenUserManagerImpl implements
mDeviceProvisionedController = deviceProvisionedController;
mSecureSettings = secureSettings;
mKeyguardStateController = keyguardStateController;
+ mKeyguardUpdateMonitor = keyguardUpdateMonitor;
dumpManager.registerDumpable(this);
}
+ @Override
public void setUpWithPresenter(NotificationPresenter presenter) {
mPresenter = presenter;
@@ -243,7 +248,10 @@ public class NotificationLockscreenUserManagerImpl implements
mUsersAllowingNotifications.clear();
// ... and refresh all the notifications
updateLockscreenNotificationSetting();
- getEntryManager().updateNotifications("LOCK_SCREEN_SHOW_NOTIFICATIONS,"
+ for (Runnable listener : mOnSensitiveContentRedactionChangeListeners) {
+ listener.run();
+ }
+ mEntryManagerLazy.get().updateNotifications("LOCK_SCREEN_SHOW_NOTIFICATIONS,"
+ " or LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS change");
}
};
@@ -253,7 +261,7 @@ public class NotificationLockscreenUserManagerImpl implements
public void onChange(boolean selfChange) {
updateLockscreenNotificationSetting();
if (mDeviceProvisionedController.isDeviceProvisioned()) {
- getEntryManager().updateNotifications("LOCK_SCREEN_ALLOW_REMOTE_INPUT"
+ mEntryManagerLazy.get().updateNotifications("LOCK_SCREEN_ALLOW_REMOTE_INPUT"
+ " or ZEN_MODE change");
}
}
@@ -312,14 +320,17 @@ public class NotificationLockscreenUserManagerImpl implements
mSettingsObserver.onChange(false); // set up
}
+ @Override
public boolean shouldShowLockscreenNotifications() {
return mShowLockscreenNotifications;
}
+ @Override
public boolean shouldAllowLockscreenRemoteInput() {
return mAllowLockscreenRemoteInput;
}
+ @Override
public boolean isCurrentProfile(int userId) {
synchronized (mLock) {
return userId == UserHandle.USER_ALL || mCurrentProfiles.get(userId) != null;
@@ -334,7 +345,7 @@ public class NotificationLockscreenUserManagerImpl implements
if (userId == UserHandle.USER_ALL) {
userId = mCurrentUserId;
}
- boolean inLockdown = Dependency.get(KeyguardUpdateMonitor.class).isUserInLockdown(userId);
+ boolean inLockdown = mKeyguardUpdateMonitor.isUserInLockdown(userId);
mUsersInLockdownLatestResult.put(userId, inLockdown);
return inLockdown;
}
@@ -343,6 +354,7 @@ public class NotificationLockscreenUserManagerImpl implements
* Returns true if we're on a secure lockscreen and the user wants to hide notification data.
* If so, notifications should be hidden.
*/
+ @Override
public boolean shouldHideNotifications(int userId) {
boolean hide = isLockscreenPublicMode(userId) && !userAllowsNotificationsInPublic(userId)
|| (userId != mCurrentUserId && shouldHideNotifications(mCurrentUserId))
@@ -355,6 +367,7 @@ public class NotificationLockscreenUserManagerImpl implements
* Returns true if we're on a secure lockscreen and the user wants to hide notifications via
* package-specific override.
*/
+ @Override
public boolean shouldHideNotifications(String key) {
if (mCommonNotifCollectionLazy.get() == null) {
Log.wtf(TAG, "mCommonNotifCollectionLazy was null!", new Throwable());
@@ -365,6 +378,7 @@ public class NotificationLockscreenUserManagerImpl implements
&& visibleEntry.getRanking().getLockscreenVisibilityOverride() == VISIBILITY_SECRET;
}
+ @Override
public boolean shouldShowOnKeyguard(NotificationEntry entry) {
if (mCommonNotifCollectionLazy.get() == null) {
Log.wtf(TAG, "mCommonNotifCollectionLazy was null!", new Throwable());
@@ -387,14 +401,6 @@ public class NotificationLockscreenUserManagerImpl implements
return mShowLockscreenNotifications && exceedsPriorityThreshold;
}
- private void setShowLockscreenNotifications(boolean show) {
- mShowLockscreenNotifications = show;
- }
-
- private void setLockscreenAllowRemoteInput(boolean allowLockscreenRemoteInput) {
- mAllowLockscreenRemoteInput = allowLockscreenRemoteInput;
- }
-
protected void updateLockscreenNotificationSetting() {
final boolean show = mSecureSettings.getIntForUser(
Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
@@ -408,7 +414,7 @@ public class NotificationLockscreenUserManagerImpl implements
mHideSilentNotificationsOnLockscreen = mSecureSettings.getIntForUser(
Settings.Secure.LOCK_SCREEN_SHOW_SILENT_NOTIFICATIONS, 1, mCurrentUserId) == 0;
- setShowLockscreenNotifications(show && allowedByDpm);
+ mShowLockscreenNotifications = show && allowedByDpm;
if (ENABLE_LOCK_SCREEN_ALLOW_REMOTE_INPUT) {
final boolean remoteInput = mSecureSettings.getIntForUser(
@@ -418,9 +424,9 @@ public class NotificationLockscreenUserManagerImpl implements
final boolean remoteInputDpm =
(dpmFlags & DevicePolicyManager.KEYGUARD_DISABLE_REMOTE_INPUT) == 0;
- setLockscreenAllowRemoteInput(remoteInput && remoteInputDpm);
+ mAllowLockscreenRemoteInput = remoteInput && remoteInputDpm;
} else {
- setLockscreenAllowRemoteInput(false);
+ mAllowLockscreenRemoteInput = false;
}
}
@@ -428,7 +434,7 @@ public class NotificationLockscreenUserManagerImpl implements
* Has the given user chosen to allow their private (full) notifications to be shown even
* when the lockscreen is in "public" (secure & locked) mode?
*/
- public boolean userAllowsPrivateNotificationsInPublic(int userHandle) {
+ protected boolean userAllowsPrivateNotificationsInPublic(int userHandle) {
if (userHandle == UserHandle.USER_ALL) {
return true;
}
@@ -473,10 +479,12 @@ public class NotificationLockscreenUserManagerImpl implements
/**
* Save the current "public" (locked and secure) state of the lockscreen.
*/
+ @Override
public void setLockscreenPublicMode(boolean publicMode, int userId) {
mLockscreenPublicMode.put(userId, publicMode);
}
+ @Override
public boolean isLockscreenPublicMode(int userId) {
if (userId == UserHandle.USER_ALL) {
return mLockscreenPublicMode.get(mCurrentUserId, false);
@@ -493,6 +501,7 @@ public class NotificationLockscreenUserManagerImpl implements
* Has the given user chosen to allow notifications to be shown even when the lockscreen is in
* "public" (secure & locked) mode?
*/
+ @Override
public boolean userAllowsNotificationsInPublic(int userHandle) {
if (isCurrentProfile(userHandle) && userHandle != mCurrentUserId) {
return true;
@@ -513,36 +522,37 @@ public class NotificationLockscreenUserManagerImpl implements
}
/** @return true if the entry needs redaction when on the lockscreen. */
- public boolean needsRedaction(NotificationEntry ent) {
+ @Override
+ public boolean notifNeedsRedactionInPublic(NotificationEntry ent) {
int userId = ent.getSbn().getUserId();
+ return ent.hasSensitiveContents() && sensitiveNotifsNeedRedactionInPublic(userId);
+ }
+ @Override
+ public boolean sensitiveNotifsNeedRedactionInPublic(int userId) {
boolean isCurrentUserRedactingNotifs =
!userAllowsPrivateNotificationsInPublic(mCurrentUserId);
+ if (userId == mCurrentUserId) {
+ return isCurrentUserRedactingNotifs;
+ }
+
boolean isNotifForManagedProfile = mCurrentManagedProfiles.contains(userId);
boolean isNotifUserRedacted = !userAllowsPrivateNotificationsInPublic(userId);
// redact notifications if the current user is redacting notifications; however if the
// notification is associated with a managed profile, we rely on the managed profile
// setting to determine whether to redact it
- boolean isNotifRedacted = (!isNotifForManagedProfile && isCurrentUserRedactingNotifs)
- || isNotifUserRedacted;
-
- boolean notificationRequestsRedaction =
- ent.getSbn().getNotification().visibility == Notification.VISIBILITY_PRIVATE;
- boolean userForcesRedaction = packageHasVisibilityOverride(ent.getSbn().getKey());
+ return (!isNotifForManagedProfile && isCurrentUserRedactingNotifs) || isNotifUserRedacted;
+ }
- return userForcesRedaction || notificationRequestsRedaction && isNotifRedacted;
+ @Override
+ public void addOnNeedsRedactionInPublicChangedListener(Runnable listener) {
+ mOnSensitiveContentRedactionChangeListeners.addIfAbsent(listener);
}
- private boolean packageHasVisibilityOverride(String key) {
- if (mCommonNotifCollectionLazy.get() == null) {
- Log.wtf(TAG, "mEntryManager was null!", new Throwable());
- return true;
- }
- NotificationEntry entry = mCommonNotifCollectionLazy.get().getEntry(key);
- return entry != null
- && entry.getRanking().getLockscreenVisibilityOverride()
- == Notification.VISIBILITY_PRIVATE;
+ @Override
+ public void removeOnNeedsRedactionInPublicChangedListener(Runnable listener) {
+ mOnSensitiveContentRedactionChangeListeners.remove(listener);
}
private void updateCurrentProfilesCache() {
@@ -562,12 +572,16 @@ public class NotificationLockscreenUserManagerImpl implements
for (UserChangedListener listener : mListeners) {
listener.onCurrentProfilesChanged(mCurrentProfiles);
}
+ for (Runnable listener : mOnSensitiveContentRedactionChangeListeners) {
+ listener.run();
+ }
});
}
/**
* If any of the profiles are in public mode.
*/
+ @Override
public boolean isAnyProfilePublicMode() {
synchronized (mLock) {
for (int i = mCurrentProfiles.size() - 1; i >= 0; i--) {
@@ -596,10 +610,12 @@ public class NotificationLockscreenUserManagerImpl implements
/**
* Returns the current user id. This can change if the user is switched.
*/
+ @Override
public int getCurrentUserId() {
return mCurrentUserId;
}
+ @Override
public SparseArray<UserInfo> getCurrentProfiles() {
return mCurrentProfiles;
}
@@ -640,7 +656,8 @@ public class NotificationLockscreenUserManagerImpl implements
setLockscreenPublicMode(isProfilePublic, userId);
mUsersWithSeparateWorkChallenge.put(userId, needsSeparateChallenge);
}
- getEntryManager().updateNotifications("NotificationLockscreenUserManager.updatePublicMode");
+ mEntryManagerLazy.get()
+ .updateNotifications("NotificationLockscreenUserManager.updatePublicMode");
}
@Override
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShelf.java b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShelf.java
index 734bc48093b2..0d604014e8f1 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShelf.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShelf.java
@@ -326,9 +326,9 @@ public class NotificationShelf extends ActivatableNotificationView implements
|| child.isPinned();
boolean isLastChild = child == lastChild;
final float viewStart = child.getTranslationY();
-
- final float inShelfAmount = updateShelfTransformation(i, child, scrollingFast,
- expandingAnimated, isLastChild);
+ final float shelfClipStart = getTranslationY() - mPaddingBetweenElements;
+ final float inShelfAmount = getAmountInShelf(i, child, scrollingFast,
+ expandingAnimated, isLastChild, shelfClipStart);
// TODO(b/172289889) scale mPaddingBetweenElements with expansion amount
if ((isLastChild && !child.isInShelf()) || aboveShelf || backgroundForceHidden) {
@@ -609,10 +609,18 @@ public class NotificationShelf extends ActivatableNotificationView implements
}
/**
- * @return the amount how much this notification is in the shelf
+ * @param i Index of the view in the host layout.
+ * @param view The current ExpandableView.
+ * @param scrollingFast Whether we are scrolling fast.
+ * @param expandingAnimated Whether we are expanding a notification.
+ * @param isLastChild Whether this is the last view.
+ * @param shelfClipStart The point at which notifications start getting clipped by the shelf.
+ * @return The amount how much this notification is in the shelf.
+ * 0f is not in shelf. 1f is completely in shelf.
*/
- private float updateShelfTransformation(int i, ExpandableView view, boolean scrollingFast,
- boolean expandingAnimated, boolean isLastChild) {
+ @VisibleForTesting
+ public float getAmountInShelf(int i, ExpandableView view, boolean scrollingFast,
+ boolean expandingAnimated, boolean isLastChild, float shelfClipStart) {
// Let's calculate how much the view is in the shelf
float viewStart = view.getTranslationY();
@@ -635,29 +643,33 @@ public class NotificationShelf extends ActivatableNotificationView implements
float viewEnd = viewStart + fullHeight;
float fullTransitionAmount = 0.0f;
float iconTransitionAmount = 0.0f;
- float shelfStart = getTranslationY() - mPaddingBetweenElements;
+
+ // Don't animate shelf icons during shade expansion.
if (mAmbientState.isExpansionChanging() && !mAmbientState.isOnKeyguard()) {
// TODO(b/172289889) handle icon placement for notification that is clipped by the shelf
if (mIndexOfFirstViewInShelf != -1 && i >= mIndexOfFirstViewInShelf) {
fullTransitionAmount = 1f;
iconTransitionAmount = 1f;
}
- } else if (viewEnd >= shelfStart
+
+ } else if (viewEnd >= shelfClipStart
&& (!mAmbientState.isUnlockHintRunning() || view.isInShelf())
&& (mAmbientState.isShadeExpanded()
|| (!view.isPinned() && !view.isHeadsUpAnimatingAway()))) {
- if (viewStart < shelfStart) {
- float fullAmount = (shelfStart - viewStart) / fullHeight;
+ if (viewStart < shelfClipStart && Math.abs(viewStart - shelfClipStart) > 0.001f) {
+ // Partially clipped by shelf.
+ float fullAmount = (shelfClipStart - viewStart) / fullHeight;
fullAmount = Math.min(1.0f, fullAmount);
fullTransitionAmount = 1.0f - fullAmount;
if (isLastChild) {
// Reduce icon transform distance to completely fade in shelf icon
// by the time the notification icon fades out, and vice versa
- iconTransitionAmount = (shelfStart - viewStart)
+ iconTransitionAmount = (shelfClipStart - viewStart)
/ (iconTransformStart - viewStart);
} else {
- iconTransitionAmount = (shelfStart - iconTransformStart) / transformDistance;
+ iconTransitionAmount = (shelfClipStart - iconTransformStart)
+ / transformDistance;
}
iconTransitionAmount = MathUtils.constrain(iconTransitionAmount, 0.0f, 1.0f);
iconTransitionAmount = 1.0f - iconTransitionAmount;
@@ -772,6 +784,9 @@ public class NotificationShelf extends ActivatableNotificationView implements
}
private NotificationIconContainer.IconState getIconState(StatusBarIconView icon) {
+ if (mShelfIcons == null) {
+ return null;
+ }
return mShelfIcons.getIconState(icon);
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationViewHierarchyManager.java b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationViewHierarchyManager.java
index 054543c7d2b1..30cb09d56f17 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationViewHierarchyManager.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationViewHierarchyManager.java
@@ -53,6 +53,7 @@ import com.android.wm.shell.bubbles.Bubbles;
import java.util.ArrayList;
import java.util.HashMap;
+import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Stack;
@@ -207,12 +208,9 @@ public class NotificationViewHierarchyManager implements DynamicPrivacyControlle
|| !mLockscreenUserManager.needsSeparateWorkChallenge(userId))) {
userPublic = false;
}
- boolean needsRedaction = mLockscreenUserManager.needsRedaction(ent);
+ boolean needsRedaction = mLockscreenUserManager.notifNeedsRedactionInPublic(ent);
boolean sensitive = userPublic && needsRedaction;
- boolean deviceSensitive = devicePublic
- && !mLockscreenUserManager.userAllowsPrivateNotificationsInPublic(
- currentUserId);
- ent.setSensitive(sensitive, deviceSensitive);
+ ent.getRow().setSensitive(sensitive);
ent.getRow().setNeedsRedaction(needsRedaction);
mLowPriorityInflationHelper.recheckLowPriorityViewAndInflate(ent, ent.getRow());
boolean isChildInGroup = mGroupManager.isChildInGroup(ent);
@@ -365,6 +363,8 @@ public class NotificationViewHierarchyManager implements DynamicPrivacyControlle
boolean hasClearableAlertingNotifs = false;
boolean hasNonClearableSilentNotifs = false;
boolean hasClearableSilentNotifs = false;
+ HashSet<Integer> clearableAlertingSensitiveNotifUsers = new HashSet<>();
+ HashSet<Integer> clearableSilentSensitiveNotifUsers = new HashSet<>();
final int childCount = mListContainer.getContainerChildCount();
int visibleTopLevelEntries = 0;
for (int i = 0; i < childCount; i++) {
@@ -376,10 +376,11 @@ public class NotificationViewHierarchyManager implements DynamicPrivacyControlle
continue;
}
final ExpandableNotificationRow row = (ExpandableNotificationRow) child;
- boolean isSilent = row.getEntry().getBucket() == BUCKET_SILENT;
+ NotificationEntry entry = row.getEntry();
+ boolean isSilent = entry.getBucket() == BUCKET_SILENT;
// NOTE: NotificationEntry.isClearable() will internally check group children to ensure
// the group itself definitively clearable.
- boolean isClearable = row.getEntry().isClearable();
+ boolean isClearable = entry.isClearable();
visibleTopLevelEntries++;
if (isSilent) {
if (isClearable) {
@@ -394,13 +395,24 @@ public class NotificationViewHierarchyManager implements DynamicPrivacyControlle
hasNonClearableAlertingNotifs = true;
}
}
+ if (isClearable && entry.hasSensitiveContents()) {
+ int userId = entry.getSbn().getUserId();
+ if (isSilent) {
+ clearableSilentSensitiveNotifUsers.add(userId);
+ } else {
+ clearableAlertingSensitiveNotifUsers.add(userId);
+ }
+ }
}
mStackController.setNotifStats(new NotifStats(
visibleTopLevelEntries /* numActiveNotifs */,
hasNonClearableAlertingNotifs /* hasNonClearableAlertingNotifs */,
hasClearableAlertingNotifs /* hasClearableAlertingNotifs */,
hasNonClearableSilentNotifs /* hasNonClearableSilentNotifs */,
- hasClearableSilentNotifs /* hasClearableSilentNotifs */
+ hasClearableSilentNotifs /* hasClearableSilentNotifs */,
+ clearableAlertingSensitiveNotifUsers /* clearableAlertingSensitiveNotifUsers */,
+ clearableSilentSensitiveNotifUsers /* clearableSilentSensitiveNotifUsers */
+
));
Trace.endSection();
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/DynamicPrivacyController.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/DynamicPrivacyController.java
index a0ccd5726c75..d16e9e5d7faf 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/DynamicPrivacyController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/DynamicPrivacyController.java
@@ -80,7 +80,7 @@ public class DynamicPrivacyController implements KeyguardStateController.Callbac
@VisibleForTesting
boolean isDynamicPrivacyEnabled() {
- return !mLockscreenUserManager.userAllowsPrivateNotificationsInPublic(
+ return mLockscreenUserManager.sensitiveNotifsNeedRedactionInPublic(
mLockscreenUserManager.getCurrentUserId());
}
@@ -95,6 +95,10 @@ public class DynamicPrivacyController implements KeyguardStateController.Callbac
mListeners.add(listener);
}
+ public void removeListener(Listener listener) {
+ mListeners.remove(listener);
+ }
+
/**
* Is the notification shade currently in a locked down mode where it's fully showing but the
* contents aren't revealed yet?
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/InstantAppNotifier.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/InstantAppNotifier.java
index df412ed93f55..8cb18a06057e 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/InstantAppNotifier.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/InstantAppNotifier.java
@@ -260,7 +260,7 @@ public class InstantAppNotifier extends CoreStartable
Intent browserIntent = getTaskIntent(taskId, userId);
Notification.Builder builder =
- new Notification.Builder(mContext, NotificationChannels.GENERAL);
+ new Notification.Builder(mContext, NotificationChannels.INSTANT);
if (browserIntent != null && browserIntent.isWebIntent()) {
// Make sure that this doesn't resolve back to an instant app
browserIntent
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationActivityStarter.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationActivityStarter.java
index 129fa5a7cc17..0c341cc92f83 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationActivityStarter.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationActivityStarter.java
@@ -17,7 +17,6 @@
package com.android.systemui.statusbar.notification;
import android.content.Intent;
-import android.service.notification.StatusBarNotification;
import android.view.View;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
@@ -29,7 +28,7 @@ import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow
*/
public interface NotificationActivityStarter {
/** Called when the user clicks on the surface of a notification. */
- void onNotificationClicked(StatusBarNotification sbn, ExpandableNotificationRow row);
+ void onNotificationClicked(NotificationEntry entry, ExpandableNotificationRow row);
/** Called when the user clicks on a button in the notification guts which fires an intent. */
void startNotificationGutsIntent(Intent intent, int appUid,
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationClicker.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationClicker.java
index 392145ad306a..c3ce593b54fd 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationClicker.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationClicker.java
@@ -104,7 +104,7 @@ public final class NotificationClicker implements View.OnClickListener {
mBubblesOptional.get().collapseStack();
}
- mNotificationActivityStarter.onNotificationClicked(entry.getSbn(), row);
+ mNotificationActivityStarter.onNotificationClicked(entry, row);
}
private boolean isMenuVisible(ExpandableNotificationRow row) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationClickerLogger.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationClickerLogger.kt
index fbf033bd2291..ad3dfedcdb96 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationClickerLogger.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationClickerLogger.kt
@@ -27,7 +27,7 @@ class NotificationClickerLogger @Inject constructor(
) {
fun logOnClick(entry: NotificationEntry) {
buffer.log(TAG, LogLevel.DEBUG, {
- str1 = entry.key
+ str1 = entry.logKey
str2 = entry.ranking.channel.id
}, {
"CLICK $str1 (channel=$str2)"
@@ -36,7 +36,7 @@ class NotificationClickerLogger @Inject constructor(
fun logMenuVisible(entry: NotificationEntry) {
buffer.log(TAG, LogLevel.DEBUG, {
- str1 = entry.key
+ str1 = entry.logKey
}, {
"Ignoring click on $str1; menu is visible"
})
@@ -44,7 +44,7 @@ class NotificationClickerLogger @Inject constructor(
fun logParentMenuVisible(entry: NotificationEntry) {
buffer.log(TAG, LogLevel.DEBUG, {
- str1 = entry.key
+ str1 = entry.logKey
}, {
"Ignoring click on $str1; parent menu is visible"
})
@@ -52,7 +52,7 @@ class NotificationClickerLogger @Inject constructor(
fun logChildrenExpanded(entry: NotificationEntry) {
buffer.log(TAG, LogLevel.DEBUG, {
- str1 = entry.key
+ str1 = entry.logKey
}, {
"Ignoring click on $str1; children are expanded"
})
@@ -60,7 +60,7 @@ class NotificationClickerLogger @Inject constructor(
fun logGutsExposed(entry: NotificationEntry) {
buffer.log(TAG, LogLevel.DEBUG, {
- str1 = entry.key
+ str1 = entry.logKey
}, {
"Ignoring click on $str1; guts are exposed"
})
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationUtils.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationUtils.java
index c3cc97bc14a3..7cfb1571ccf0 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationUtils.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationUtils.java
@@ -24,7 +24,8 @@ import android.widget.ImageView;
import com.android.internal.util.ContrastColorUtil;
import com.android.systemui.R;
-import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.collection.ListEntry;
+import com.android.systemui.util.Compile;
/**
* A util class for various reusable functions
@@ -74,12 +75,18 @@ public class NotificationUtils {
return (int) (dimensionPixelSize * factor);
}
+ private static final boolean INCLUDE_HASH_CODE_IN_LIST_ENTRY_LOG_KEY = false;
+
/** Get the notification key, reformatted for logging, for the (optional) entry */
- public static String logKey(NotificationEntry entry) {
+ public static String logKey(ListEntry entry) {
if (entry == null) {
return "null";
}
- return logKey(entry.getKey());
+ if (Compile.IS_DEBUG && INCLUDE_HASH_CODE_IN_LIST_ENTRY_LOG_KEY) {
+ return logKey(entry.getKey()) + "@" + Integer.toHexString(entry.hashCode());
+ } else {
+ return logKey(entry.getKey());
+ }
}
/** Removes newlines from the notification key to prettify apps that have these in the tag */
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationUtils.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationUtils.kt
new file mode 100644
index 000000000000..432bac49fa9b
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationUtils.kt
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+
+package com.android.systemui.statusbar.notification
+
+import android.service.notification.StatusBarNotification
+import com.android.systemui.statusbar.notification.collection.ListEntry
+
+/** Get the notification key, reformatted for logging, for the (optional) entry */
+val ListEntry?.logKey: String?
+ get() = this?.let { NotificationUtils.logKey(it) }
+
+/** Get the notification key, reformatted for logging, for the (optional) sbn */
+val StatusBarNotification?.logKey: String?
+ get() = this?.key?.let { NotificationUtils.logKey(it) }
+
+/** Removes newlines from the notification key to prettify apps that have these in the tag */
+fun logKey(key: String?): String? = NotificationUtils.logKey(key) \ No newline at end of file
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotifCollection.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotifCollection.java
index bcd8e594ffbd..6085096ee124 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotifCollection.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotifCollection.java
@@ -18,9 +18,12 @@ package com.android.systemui.statusbar.notification.collection;
import static android.service.notification.NotificationListenerService.REASON_APP_CANCEL;
import static android.service.notification.NotificationListenerService.REASON_APP_CANCEL_ALL;
+import static android.service.notification.NotificationListenerService.REASON_ASSISTANT_CANCEL;
import static android.service.notification.NotificationListenerService.REASON_CANCEL;
import static android.service.notification.NotificationListenerService.REASON_CANCEL_ALL;
import static android.service.notification.NotificationListenerService.REASON_CHANNEL_BANNED;
+import static android.service.notification.NotificationListenerService.REASON_CHANNEL_REMOVED;
+import static android.service.notification.NotificationListenerService.REASON_CLEAR_DATA;
import static android.service.notification.NotificationListenerService.REASON_CLICK;
import static android.service.notification.NotificationListenerService.REASON_ERROR;
import static android.service.notification.NotificationListenerService.REASON_GROUP_OPTIMIZATION;
@@ -36,9 +39,11 @@ import static android.service.notification.NotificationListenerService.REASON_TI
import static android.service.notification.NotificationListenerService.REASON_UNAUTOBUNDLED;
import static android.service.notification.NotificationListenerService.REASON_USER_STOPPED;
+import static com.android.systemui.statusbar.notification.NotificationUtils.logKey;
import static com.android.systemui.statusbar.notification.collection.NotificationEntry.DismissState.DISMISSED;
import static com.android.systemui.statusbar.notification.collection.NotificationEntry.DismissState.NOT_DISMISSED;
import static com.android.systemui.statusbar.notification.collection.NotificationEntry.DismissState.PARENT_DISMISSED;
+import static com.android.systemui.statusbar.notification.collection.notifcollection.NotifCollectionLoggerKt.cancellationReasonDebugString;
import static java.util.Objects.requireNonNull;
@@ -99,6 +104,7 @@ import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
+import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@@ -143,6 +149,7 @@ public class NotifCollection implements Dumpable {
private final Map<String, NotificationEntry> mNotificationSet = new ArrayMap<>();
private final Collection<NotificationEntry> mReadOnlyNotificationSet =
Collections.unmodifiableCollection(mNotificationSet.values());
+ private final HashMap<String, FutureDismissal> mFutureDismissals = new HashMap<>();
@Nullable private CollectionReadyForBuildListener mBuildListener;
private final List<NotifCollectionListener> mNotifCollectionListeners = new ArrayList<>();
@@ -511,6 +518,7 @@ public class NotifCollection implements Dumpable {
cancelDismissInterception(entry);
mEventQueue.add(new EntryRemovedEvent(entry, entry.mCancellationReason));
mEventQueue.add(new CleanUpEntryEvent(entry));
+ handleFutureDismissal(entry);
return true;
} else {
return false;
@@ -519,31 +527,32 @@ public class NotifCollection implements Dumpable {
/**
* Get the group summary entry
- * @param group
+ * @param groupKey
* @return
*/
@Nullable
- public NotificationEntry getGroupSummary(String group) {
+ public NotificationEntry getGroupSummary(String groupKey) {
return mNotificationSet
.values()
.stream()
- .filter(it -> Objects.equals(it.getSbn().getGroup(), group))
+ .filter(it -> Objects.equals(it.getSbn().getGroupKey(), groupKey))
.filter(it -> it.getSbn().getNotification().isGroupSummary())
.findFirst().orElse(null);
}
/**
- * Checks if the entry is the only child in the logical group
- * @param entry
- * @return
+ * Checks if the entry is the only child in the logical group;
+ * it need not have a summary to qualify
+ *
+ * @param entry the entry to check
*/
public boolean isOnlyChildInGroup(NotificationEntry entry) {
- String group = entry.getSbn().getGroup();
+ String groupKey = entry.getSbn().getGroupKey();
return mNotificationSet.get(entry.getKey()) == entry
&& mNotificationSet
.values()
.stream()
- .filter(it -> Objects.equals(it.getSbn().getGroup(), group))
+ .filter(it -> Objects.equals(it.getSbn().getGroupKey(), groupKey))
.filter(it -> !it.getSbn().getNotification().isGroupSummary())
.count() == 1;
}
@@ -916,10 +925,139 @@ public class NotifCollection implements Dumpable {
dispatchEventsAndRebuildList();
}
+ /**
+ * A method to alert the collection that an async operation is happening, at the end of which a
+ * dismissal request will be made. This method has the additional guarantee that if a parent
+ * notification exists for a single child, then that notification will also be dismissed.
+ *
+ * The runnable returned must be run at the end of the async operation to enact the cancellation
+ *
+ * @param entry the notification we want to dismiss
+ * @param cancellationReason the reason for the cancellation
+ * @param statsCreator the callback for generating the stats for an entry
+ * @return the runnable to be run when the dismissal is ready to happen
+ */
+ public Runnable registerFutureDismissal(NotificationEntry entry, int cancellationReason,
+ DismissedByUserStatsCreator statsCreator) {
+ FutureDismissal dismissal = mFutureDismissals.get(entry.getKey());
+ if (dismissal != null) {
+ mLogger.logFutureDismissalReused(dismissal);
+ return dismissal;
+ }
+ dismissal = new FutureDismissal(entry, cancellationReason, statsCreator);
+ mFutureDismissals.put(entry.getKey(), dismissal);
+ mLogger.logFutureDismissalRegistered(dismissal);
+ return dismissal;
+ }
+
+ private void handleFutureDismissal(NotificationEntry entry) {
+ final FutureDismissal futureDismissal = mFutureDismissals.remove(entry.getKey());
+ if (futureDismissal != null) {
+ futureDismissal.onSystemServerCancel(entry.mCancellationReason);
+ }
+ }
+
+ /** A single method interface that callers can pass in when registering future dismissals */
+ public interface DismissedByUserStatsCreator {
+ DismissedByUserStats createDismissedByUserStats(NotificationEntry entry);
+ }
+
+ /** A class which tracks the double dismissal events coming in from both the system server and
+ * the ui */
+ public class FutureDismissal implements Runnable {
+ private final NotificationEntry mEntry;
+ private final DismissedByUserStatsCreator mStatsCreator;
+ @Nullable
+ private final NotificationEntry mSummaryToDismiss;
+ private final String mLabel;
+
+ private boolean mDidRun;
+ private boolean mDidSystemServerCancel;
+
+ private FutureDismissal(NotificationEntry entry, @CancellationReason int cancellationReason,
+ DismissedByUserStatsCreator statsCreator) {
+ mEntry = entry;
+ mStatsCreator = statsCreator;
+ mSummaryToDismiss = fetchSummaryToDismiss(entry);
+ mLabel = "<FutureDismissal@" + Integer.toHexString(hashCode())
+ + " entry=" + logKey(mEntry)
+ + " reason=" + cancellationReasonDebugString(cancellationReason)
+ + " summary=" + logKey(mSummaryToDismiss)
+ + ">";
+ }
+
+ @Nullable
+ private NotificationEntry fetchSummaryToDismiss(NotificationEntry entry) {
+ if (isOnlyChildInGroup(entry)) {
+ String group = entry.getSbn().getGroupKey();
+ NotificationEntry summary = getGroupSummary(group);
+ if (summary != null && summary.isDismissable()) return summary;
+ }
+ return null;
+ }
+
+ /** called when the entry has been removed from the collection */
+ public void onSystemServerCancel(@CancellationReason int cancellationReason) {
+ Assert.isMainThread();
+ if (mDidSystemServerCancel) {
+ mLogger.logFutureDismissalDoubleCancelledByServer(this);
+ return;
+ }
+ mLogger.logFutureDismissalGotSystemServerCancel(this, cancellationReason);
+ mDidSystemServerCancel = true;
+ // TODO: Internally dismiss the summary now instead of waiting for onUiCancel
+ }
+
+ private void onUiCancel() {
+ mFutureDismissals.remove(mEntry.getKey());
+ final NotificationEntry currentEntry = getEntry(mEntry.getKey());
+ // generate stats for the entry before dismissing summary, which could affect state
+ final DismissedByUserStats stats = mStatsCreator.createDismissedByUserStats(mEntry);
+ // dismiss the summary (if it exists)
+ if (mSummaryToDismiss != null) {
+ final NotificationEntry currentSummary = getEntry(mSummaryToDismiss.getKey());
+ if (currentSummary == mSummaryToDismiss) {
+ mLogger.logFutureDismissalDismissing(this, "summary");
+ dismissNotification(mSummaryToDismiss,
+ mStatsCreator.createDismissedByUserStats(mSummaryToDismiss));
+ } else {
+ mLogger.logFutureDismissalMismatchedEntry(this, "summary", currentSummary);
+ }
+ }
+ // dismiss this entry (if it is still around)
+ if (mDidSystemServerCancel) {
+ mLogger.logFutureDismissalAlreadyCancelledByServer(this);
+ } else if (currentEntry == mEntry) {
+ mLogger.logFutureDismissalDismissing(this, "entry");
+ dismissNotification(mEntry, stats);
+ } else {
+ mLogger.logFutureDismissalMismatchedEntry(this, "entry", currentEntry);
+ }
+ }
+
+ /** called when the dismissal should be completed */
+ @Override
+ public void run() {
+ Assert.isMainThread();
+ if (mDidRun) {
+ mLogger.logFutureDismissalDoubleRun(this);
+ return;
+ }
+ mDidRun = true;
+ onUiCancel();
+ }
+
+ /** provides a debug label for this instance */
+ public String getLabel() {
+ return mLabel;
+ }
+ }
+
@IntDef(prefix = { "REASON_" }, value = {
REASON_NOT_CANCELED,
REASON_UNKNOWN,
REASON_CLICK,
+ REASON_CANCEL,
REASON_CANCEL_ALL,
REASON_ERROR,
REASON_PACKAGE_CHANGED,
@@ -937,6 +1075,9 @@ public class NotifCollection implements Dumpable {
REASON_CHANNEL_BANNED,
REASON_SNOOZED,
REASON_TIMEOUT,
+ REASON_CHANNEL_REMOVED,
+ REASON_CLEAR_DATA,
+ REASON_ASSISTANT_CANCEL,
})
@Retention(RetentionPolicy.SOURCE)
public @interface CancellationReason {}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationEntry.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationEntry.java
index 4fc347a09292..e3c39ddad145 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationEntry.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationEntry.java
@@ -169,9 +169,6 @@ public final class NotificationEntry extends ListEntry {
*/
private boolean hasSentReply;
- private boolean mSensitive = true;
- private List<OnSensitivityChangedListener> mOnSensitivityChangedListeners = new ArrayList<>();
-
private boolean mAutoHeadsUp;
private boolean mPulseSupressed;
private int mBucket = BUCKET_ALERTING;
@@ -867,33 +864,29 @@ public final class NotificationEntry extends ListEntry {
}
/**
- * Set this notification to be sensitive.
- *
- * @param sensitive true if the content of this notification is sensitive right now
- * @param deviceSensitive true if the device in general is sensitive right now
- */
- public void setSensitive(boolean sensitive, boolean deviceSensitive) {
- getRow().setSensitive(sensitive, deviceSensitive);
- if (sensitive != mSensitive) {
- mSensitive = sensitive;
- for (int i = 0; i < mOnSensitivityChangedListeners.size(); i++) {
- mOnSensitivityChangedListeners.get(i).onSensitivityChanged(this);
- }
+ * Returns the visibility of this notification on the lockscreen, taking into account both the
+ * notification's defined visibility, as well as the visibility override as determined by the
+ * device policy.
+ */
+ public int getLockscreenVisibility() {
+ int setting = mRanking.getLockscreenVisibilityOverride();
+ if (setting == Ranking.VISIBILITY_NO_OVERRIDE) {
+ setting = mSbn.getNotification().visibility;
}
+ return setting;
}
- public boolean isSensitive() {
- return mSensitive;
- }
-
- /** Add a listener to be notified when the entry's sensitivity changes. */
- public void addOnSensitivityChangedListener(OnSensitivityChangedListener listener) {
- mOnSensitivityChangedListeners.add(listener);
- }
-
- /** Remove a listener that was registered above. */
- public void removeOnSensitivityChangedListener(OnSensitivityChangedListener listener) {
- mOnSensitivityChangedListeners.remove(listener);
+ /**
+ * Does this notification contain sensitive content? If the user's settings specify, then this
+ * content would need to be redacted when the device this public.
+ *
+ * NOTE: If the notification's visibility setting is VISIBILITY_SECRET, then this will return
+ * false; SECRET notifications are omitted entirely when the device is public, so effectively
+ * the contents of the notification are not sensitive whenever the notification is actually
+ * visible.
+ */
+ public boolean hasSensitiveContents() {
+ return getLockscreenVisibility() == Notification.VISIBILITY_PRIVATE;
}
public boolean isPulseSuppressed() {
@@ -954,12 +947,6 @@ public final class NotificationEntry extends ListEntry {
}
}
- /** Listener interface for {@link #addOnSensitivityChangedListener} */
- public interface OnSensitivityChangedListener {
- /** Called when the sensitivity changes */
- void onSensitivityChanged(@NonNull NotificationEntry entry);
- }
-
/** @see #getDismissState() */
public enum DismissState {
/** User has not dismissed this notif or its parent */
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/ShadeListBuilder.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/ShadeListBuilder.java
index 1b5e52d7f8fb..df2fe4e8511f 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/ShadeListBuilder.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/ShadeListBuilder.java
@@ -93,6 +93,7 @@ public class ShadeListBuilder implements Dumpable {
private final NotificationInteractionTracker mInteractionTracker;
private final DumpManager mDumpManager;
// used exclusivly by ShadeListBuilder#notifySectionEntriesUpdated
+ // TODO replace temp with collection pool for readability
private final ArrayList<ListEntry> mTempSectionMembers = new ArrayList<>();
private final boolean mAlwaysLogList;
@@ -230,13 +231,7 @@ public class ShadeListBuilder implements Dumpable {
mPipelineState.requireState(STATE_IDLE);
mNotifSections.clear();
- NotifSectioner lastSection = null;
for (NotifSectioner sectioner : sectioners) {
- if (lastSection != null && lastSection.getBucket() > sectioner.getBucket()) {
- throw new IllegalArgumentException("setSectioners with non contiguous sections "
- + lastSection.getName() + " - " + lastSection.getBucket() + " & "
- + sectioner.getName() + " - " + sectioner.getBucket());
- }
final NotifSection section = new NotifSection(sectioner, mNotifSections.size());
final NotifComparator sectionComparator = section.getComparator();
mNotifSections.add(section);
@@ -244,10 +239,23 @@ public class ShadeListBuilder implements Dumpable {
if (sectionComparator != null) {
sectionComparator.setInvalidationListener(this::onNotifComparatorInvalidated);
}
- lastSection = sectioner;
}
mNotifSections.add(new NotifSection(DEFAULT_SECTIONER, mNotifSections.size()));
+
+ // validate sections
+ final ArraySet<Integer> seenBuckets = new ArraySet<>();
+ int lastBucket = mNotifSections.size() > 0
+ ? mNotifSections.get(0).getBucket()
+ : 0;
+ for (NotifSection section : mNotifSections) {
+ if (lastBucket != section.getBucket() && seenBuckets.contains(section.getBucket())) {
+ throw new IllegalStateException("setSectioners with non contiguous sections "
+ + section.getLabel() + " has an already seen bucket");
+ }
+ lastBucket = section.getBucket();
+ seenBuckets.add(lastBucket);
+ }
}
void setNotifStabilityManager(@NonNull NotifStabilityManager notifStabilityManager) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/ActivityLaunchAnimCoordinator.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/ActivityLaunchAnimCoordinator.kt
deleted file mode 100644
index b54163d29e80..000000000000
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/ActivityLaunchAnimCoordinator.kt
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Copyright (C) 2022 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.systemui.statusbar.notification.collection.coordinator
-
-import com.android.systemui.statusbar.notification.collection.NotifPipeline
-import com.android.systemui.statusbar.notification.collection.NotificationEntry
-import com.android.systemui.statusbar.notification.collection.coordinator.dagger.CoordinatorScope
-import com.android.systemui.statusbar.notification.collection.notifcollection.NotifLifetimeExtender
-import com.android.systemui.statusbar.notification.collection.notifcollection.NotifLifetimeExtender.OnEndLifetimeExtensionCallback
-import com.android.systemui.statusbar.phone.NotifActivityLaunchEvents
-import dagger.Binds
-import dagger.Module
-import javax.inject.Inject
-
-/** Extends the lifetime of notifications while their activity launch animation is playing. */
-interface ActivityLaunchAnimCoordinator : Coordinator
-
-/** Provides an [ActivityLaunchAnimCoordinator] to [CoordinatorScope]. */
-@Module(includes = [PrivateActivityStarterCoordinatorModule::class])
-object ActivityLaunchAnimCoordinatorModule
-
-@Module
-private interface PrivateActivityStarterCoordinatorModule {
- @Binds
- fun bindCoordinator(impl: ActivityLaunchAnimCoordinatorImpl): ActivityLaunchAnimCoordinator
-}
-
-/**
- * Listens for [NotifActivityLaunchEvents], and then extends the lifetimes of any notifs while their
- * launch animation is playing.
- */
-@CoordinatorScope
-private class ActivityLaunchAnimCoordinatorImpl @Inject constructor(
- private val activityLaunchEvents: NotifActivityLaunchEvents
-) : ActivityLaunchAnimCoordinator {
- // Tracks notification launches, and whether or not their lifetimes are extended.
- private val notifsLaunchingActivities = mutableMapOf<String, Boolean>()
-
- private var onEndLifetimeExtensionCallback: OnEndLifetimeExtensionCallback? = null
-
- override fun attach(pipeline: NotifPipeline) {
- activityLaunchEvents.registerListener(activityStartEventListener)
- pipeline.addNotificationLifetimeExtender(extender)
- }
-
- private val activityStartEventListener = object : NotifActivityLaunchEvents.Listener {
- override fun onStartLaunchNotifActivity(entry: NotificationEntry) {
- notifsLaunchingActivities[entry.key] = false
- }
-
- override fun onFinishLaunchNotifActivity(entry: NotificationEntry) {
- if (notifsLaunchingActivities.remove(entry.key) == true) {
- // If we were extending the lifetime of this notification, stop.
- onEndLifetimeExtensionCallback?.onEndLifetimeExtension(extender, entry)
- }
- }
- }
-
- private val extender = object : NotifLifetimeExtender {
- override fun getName(): String = "ActivityStarterCoordinator"
-
- override fun setCallback(callback: OnEndLifetimeExtensionCallback) {
- onEndLifetimeExtensionCallback = callback
- }
-
- override fun maybeExtendLifetime(entry: NotificationEntry, reason: Int): Boolean {
- if (entry.key in notifsLaunchingActivities) {
- // Track that we're now extending this notif
- notifsLaunchingActivities[entry.key] = true
- return true
- }
- return false
- }
-
- override fun cancelLifetimeExtension(entry: NotificationEntry) {
- if (entry.key in notifsLaunchingActivities) {
- notifsLaunchingActivities[entry.key] = false
- }
- }
- }
-}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/NotifCoordinators.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/NotifCoordinators.kt
index 3516625cc471..0b3a0dc9dd58 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/NotifCoordinators.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/NotifCoordinators.kt
@@ -56,8 +56,6 @@ class NotifCoordinatorsImpl @Inject constructor(
smartspaceDedupingCoordinator: SmartspaceDedupingCoordinator,
viewConfigCoordinator: ViewConfigCoordinator,
visualStabilityCoordinator: VisualStabilityCoordinator,
- sensitiveContentCoordinator: SensitiveContentCoordinator,
- activityLaunchAnimCoordinator: ActivityLaunchAnimCoordinator
) : NotifCoordinators {
private val mCoordinators: MutableList<Coordinator> = ArrayList()
@@ -94,8 +92,6 @@ class NotifCoordinatorsImpl @Inject constructor(
mCoordinators.add(shadeEventCoordinator)
mCoordinators.add(viewConfigCoordinator)
mCoordinators.add(visualStabilityCoordinator)
- mCoordinators.add(sensitiveContentCoordinator)
- mCoordinators.add(activityLaunchAnimCoordinator)
if (notifPipelineFlags.isSmartspaceDedupingEnabled()) {
mCoordinators.add(smartspaceDedupingCoordinator)
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/RankingCoordinator.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/RankingCoordinator.java
index 57fd1975e13a..56484010c213 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/RankingCoordinator.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/RankingCoordinator.java
@@ -16,7 +16,6 @@
package com.android.systemui.statusbar.notification.collection.coordinator;
-import android.annotation.NonNull;
import android.annotation.Nullable;
import com.android.systemui.plugins.statusbar.StatusBarStateController;
@@ -29,13 +28,11 @@ import com.android.systemui.statusbar.notification.collection.listbuilder.plugga
import com.android.systemui.statusbar.notification.collection.listbuilder.pluggable.NotifSectioner;
import com.android.systemui.statusbar.notification.collection.provider.HighPriorityProvider;
import com.android.systemui.statusbar.notification.collection.render.NodeController;
-import com.android.systemui.statusbar.notification.collection.render.SectionHeaderController;
import com.android.systemui.statusbar.notification.dagger.AlertingHeader;
import com.android.systemui.statusbar.notification.dagger.SilentHeader;
import com.android.systemui.statusbar.notification.stack.NotificationPriorityBucketKt;
import java.util.Collections;
-import java.util.List;
import javax.inject.Inject;
@@ -53,10 +50,10 @@ public class RankingCoordinator implements Coordinator {
private final HighPriorityProvider mHighPriorityProvider;
private final SectionClassifier mSectionClassifier;
private final NodeController mSilentNodeController;
- private final SectionHeaderController mSilentHeaderController;
private final NodeController mAlertingHeaderController;
- private boolean mHasSilentEntries;
- private boolean mHasMinimizedEntries;
+ private final AlertingNotifSectioner mAlertingNotifSectioner = new AlertingNotifSectioner();
+ private final SilentNotifSectioner mSilentNotifSectioner = new SilentNotifSectioner();
+ private final MinimizedNotifSectioner mMinimizedNotifSectioner = new MinimizedNotifSectioner();
@Inject
public RankingCoordinator(
@@ -64,14 +61,12 @@ public class RankingCoordinator implements Coordinator {
HighPriorityProvider highPriorityProvider,
SectionClassifier sectionClassifier,
@AlertingHeader NodeController alertingHeaderController,
- @SilentHeader SectionHeaderController silentHeaderController,
@SilentHeader NodeController silentNodeController) {
mStatusBarStateController = statusBarStateController;
mHighPriorityProvider = highPriorityProvider;
mSectionClassifier = sectionClassifier;
mAlertingHeaderController = alertingHeaderController;
mSilentNodeController = silentNodeController;
- mSilentHeaderController = silentHeaderController;
}
@Override
@@ -95,8 +90,44 @@ public class RankingCoordinator implements Coordinator {
return mMinimizedNotifSectioner;
}
- private final NotifSectioner mAlertingNotifSectioner = new NotifSectioner("Alerting",
- NotificationPriorityBucketKt.BUCKET_ALERTING) {
+ /**
+ * Checks whether to filter out the given notification based the notification's Ranking object.
+ * NotifListBuilder invalidates the notification list each time the ranking is updated,
+ * so we don't need to explicitly invalidate this filter on ranking update.
+ */
+ private final NotifFilter mSuspendedFilter = new NotifFilter("IsSuspendedFilter") {
+ @Override
+ public boolean shouldFilterOut(NotificationEntry entry, long now) {
+ return entry.getRanking().isSuspended();
+ }
+ };
+
+ private final NotifFilter mDndVisualEffectsFilter = new NotifFilter(
+ "DndSuppressingVisualEffects") {
+ @Override
+ public boolean shouldFilterOut(NotificationEntry entry, long now) {
+ if (mStatusBarStateController.isDozing() && entry.shouldSuppressAmbient()) {
+ return true;
+ }
+
+ return !mStatusBarStateController.isDozing() && entry.shouldSuppressNotificationList();
+ }
+ };
+
+ private final StatusBarStateController.StateListener mStatusBarStateCallback =
+ new StatusBarStateController.StateListener() {
+ @Override
+ public void onDozingChanged(boolean isDozing) {
+ mDndVisualEffectsFilter.invalidateList();
+ }
+ };
+
+ private class AlertingNotifSectioner extends NotifSectioner {
+
+ AlertingNotifSectioner() {
+ super("Alerting", NotificationPriorityBucketKt.BUCKET_ALERTING);
+ }
+
@Override
public boolean isInSection(ListEntry entry) {
return mHighPriorityProvider.isHighPriority(entry);
@@ -111,10 +142,14 @@ public class RankingCoordinator implements Coordinator {
}
return null;
}
- };
+ }
+
+ private class SilentNotifSectioner extends NotifSectioner {
+
+ SilentNotifSectioner() {
+ super("Silent", NotificationPriorityBucketKt.BUCKET_SILENT);
+ }
- private final NotifSectioner mSilentNotifSectioner = new NotifSectioner("Silent",
- NotificationPriorityBucketKt.BUCKET_SILENT) {
@Override
public boolean isInSection(ListEntry entry) {
return !mHighPriorityProvider.isHighPriority(entry)
@@ -126,24 +161,14 @@ public class RankingCoordinator implements Coordinator {
public NodeController getHeaderNodeController() {
return mSilentNodeController;
}
+ }
- @Nullable
- @Override
- public void onEntriesUpdated(@NonNull List<ListEntry> entries) {
- mHasSilentEntries = false;
- for (int i = 0; i < entries.size(); i++) {
- if (entries.get(i).getRepresentativeEntry().getSbn().isClearable()) {
- mHasSilentEntries = true;
- break;
- }
- }
- mSilentHeaderController.setClearSectionEnabled(
- mHasSilentEntries | mHasMinimizedEntries);
+ private class MinimizedNotifSectioner extends NotifSectioner {
+
+ MinimizedNotifSectioner() {
+ super("Minimized", NotificationPriorityBucketKt.BUCKET_SILENT);
}
- };
- private final NotifSectioner mMinimizedNotifSectioner = new NotifSectioner("Minimized",
- NotificationPriorityBucketKt.BUCKET_SILENT) {
@Override
public boolean isInSection(ListEntry entry) {
return !mHighPriorityProvider.isHighPriority(entry)
@@ -155,51 +180,5 @@ public class RankingCoordinator implements Coordinator {
public NodeController getHeaderNodeController() {
return mSilentNodeController;
}
-
- @Nullable
- @Override
- public void onEntriesUpdated(@NonNull List<ListEntry> entries) {
- mHasMinimizedEntries = false;
- for (int i = 0; i < entries.size(); i++) {
- if (entries.get(i).getRepresentativeEntry().getSbn().isClearable()) {
- mHasMinimizedEntries = true;
- break;
- }
- }
- mSilentHeaderController.setClearSectionEnabled(
- mHasSilentEntries | mHasMinimizedEntries);
- }
- };
-
- /**
- * Checks whether to filter out the given notification based the notification's Ranking object.
- * NotifListBuilder invalidates the notification list each time the ranking is updated,
- * so we don't need to explicitly invalidate this filter on ranking update.
- */
- private final NotifFilter mSuspendedFilter = new NotifFilter("IsSuspendedFilter") {
- @Override
- public boolean shouldFilterOut(NotificationEntry entry, long now) {
- return entry.getRanking().isSuspended();
- }
- };
-
- private final NotifFilter mDndVisualEffectsFilter = new NotifFilter(
- "DndSuppressingVisualEffects") {
- @Override
- public boolean shouldFilterOut(NotificationEntry entry, long now) {
- if (mStatusBarStateController.isDozing() && entry.shouldSuppressAmbient()) {
- return true;
- }
-
- return !mStatusBarStateController.isDozing() && entry.shouldSuppressNotificationList();
- }
- };
-
- private final StatusBarStateController.StateListener mStatusBarStateCallback =
- new StatusBarStateController.StateListener() {
- @Override
- public void onDozingChanged(boolean isDozing) {
- mDndVisualEffectsFilter.invalidateList();
- }
- };
+ }
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/SensitiveContentCoordinator.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/SensitiveContentCoordinator.kt
deleted file mode 100644
index 3f8a39f62dfb..000000000000
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/SensitiveContentCoordinator.kt
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.systemui.statusbar.notification.collection.coordinator
-
-import android.os.UserHandle
-import com.android.keyguard.KeyguardUpdateMonitor
-import com.android.systemui.plugins.statusbar.StatusBarStateController
-import com.android.systemui.statusbar.NotificationLockscreenUserManager
-import com.android.systemui.statusbar.StatusBarState
-import com.android.systemui.statusbar.notification.DynamicPrivacyController
-import com.android.systemui.statusbar.notification.collection.GroupEntry
-import com.android.systemui.statusbar.notification.collection.ListEntry
-import com.android.systemui.statusbar.notification.collection.NotifPipeline
-import com.android.systemui.statusbar.notification.collection.NotificationEntry
-import com.android.systemui.statusbar.notification.collection.coordinator.dagger.CoordinatorScope
-import com.android.systemui.statusbar.notification.collection.listbuilder.OnBeforeRenderListListener
-import com.android.systemui.statusbar.notification.collection.listbuilder.pluggable.Invalidator
-import com.android.systemui.statusbar.policy.KeyguardStateController
-import dagger.Binds
-import dagger.Module
-import javax.inject.Inject
-
-@Module(includes = [PrivateSensitiveContentCoordinatorModule::class])
-interface SensitiveContentCoordinatorModule
-
-@Module
-private interface PrivateSensitiveContentCoordinatorModule {
- @Binds
- fun bindCoordinator(impl: SensitiveContentCoordinatorImpl): SensitiveContentCoordinator
-}
-
-/** Coordinates re-inflation and post-processing of sensitive notification content. */
-interface SensitiveContentCoordinator : Coordinator
-
-@CoordinatorScope
-private class SensitiveContentCoordinatorImpl @Inject constructor(
- private val dynamicPrivacyController: DynamicPrivacyController,
- private val lockscreenUserManager: NotificationLockscreenUserManager,
- private val keyguardUpdateMonitor: KeyguardUpdateMonitor,
- private val statusBarStateController: StatusBarStateController,
- private val keyguardStateController: KeyguardStateController
-) : Invalidator("SensitiveContentInvalidator"),
- SensitiveContentCoordinator,
- DynamicPrivacyController.Listener,
- OnBeforeRenderListListener {
-
- override fun attach(pipeline: NotifPipeline) {
- dynamicPrivacyController.addListener(this)
- pipeline.addOnBeforeRenderListListener(this)
- pipeline.addPreRenderInvalidator(this)
- }
-
- override fun onDynamicPrivacyChanged(): Unit = invalidateList()
-
- override fun onBeforeRenderList(entries: List<ListEntry>) {
- if (keyguardStateController.isKeyguardGoingAway() ||
- statusBarStateController.getState() == StatusBarState.KEYGUARD &&
- keyguardUpdateMonitor.getUserUnlockedWithBiometricAndIsBypassing(
- KeyguardUpdateMonitor.getCurrentUser())) {
- // don't update yet if:
- // - the keyguard is currently going away
- // - LS is about to be dismissed by a biometric that bypasses LS (avoid notif flash)
-
- // TODO(b/206118999): merge this class with KeyguardCoordinator which ensures the
- // dependent state changes invalidate the pipeline
- return
- }
-
- val currentUserId = lockscreenUserManager.currentUserId
- val devicePublic = lockscreenUserManager.isLockscreenPublicMode(currentUserId)
- val deviceSensitive = devicePublic &&
- !lockscreenUserManager.userAllowsPrivateNotificationsInPublic(currentUserId)
- val dynamicallyUnlocked = dynamicPrivacyController.isDynamicallyUnlocked
- for (entry in extractAllRepresentativeEntries(entries).filter { it.rowExists() }) {
- val notifUserId = entry.sbn.user.identifier
- val userLockscreen = devicePublic ||
- lockscreenUserManager.isLockscreenPublicMode(notifUserId)
- val userPublic = when {
- // if we're not on the lockscreen, we're definitely private
- !userLockscreen -> false
- // we are on the lockscreen, so unless we're dynamically unlocked, we're
- // definitely public
- !dynamicallyUnlocked -> true
- // we're dynamically unlocked, but check if the notification needs
- // a separate challenge if it's from a work profile
- else -> when (notifUserId) {
- currentUserId -> false
- UserHandle.USER_ALL -> false
- else -> lockscreenUserManager.needsSeparateWorkChallenge(notifUserId)
- }
- }
- val needsRedaction = lockscreenUserManager.needsRedaction(entry)
- val isSensitive = userPublic && needsRedaction
- entry.setSensitive(isSensitive, deviceSensitive)
- }
- }
-}
-
-private fun extractAllRepresentativeEntries(
- entries: List<ListEntry>
-): Sequence<NotificationEntry> =
- entries.asSequence().flatMap(::extractAllRepresentativeEntries)
-
-private fun extractAllRepresentativeEntries(listEntry: ListEntry): Sequence<NotificationEntry> =
- sequence {
- listEntry.representativeEntry?.let { yield(it) }
- if (listEntry is GroupEntry) {
- yieldAll(extractAllRepresentativeEntries(listEntry.children))
- }
- }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/StackCoordinator.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/StackCoordinator.kt
index 1c96e8ceb27f..2374e9c58177 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/StackCoordinator.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/StackCoordinator.kt
@@ -50,6 +50,8 @@ class StackCoordinator @Inject internal constructor(
var hasClearableAlertingNotifs = false
var hasNonClearableSilentNotifs = false
var hasClearableSilentNotifs = false
+ val clearableAlertingSensitiveNotifUsers = mutableSetOf<Int>()
+ val clearableSilentSensitiveNotifUsers = mutableSetOf<Int>()
entries.forEach {
val section = checkNotNull(it.section) { "Null section for ${it.key}" }
val entry = checkNotNull(it.representativeEntry) { "Null notif entry for ${it.key}" }
@@ -63,13 +65,22 @@ class StackCoordinator @Inject internal constructor(
!isSilent && isClearable -> hasClearableAlertingNotifs = true
!isSilent && !isClearable -> hasNonClearableAlertingNotifs = true
}
+ if (isClearable && entry.hasSensitiveContents()) {
+ if (isSilent) {
+ clearableSilentSensitiveNotifUsers.add(entry.sbn.userId)
+ } else {
+ clearableAlertingSensitiveNotifUsers.add(entry.sbn.userId)
+ }
+ }
}
return NotifStats(
numActiveNotifs = entries.size,
hasNonClearableAlertingNotifs = hasNonClearableAlertingNotifs,
hasClearableAlertingNotifs = hasClearableAlertingNotifs,
hasNonClearableSilentNotifs = hasNonClearableSilentNotifs,
- hasClearableSilentNotifs = hasClearableSilentNotifs
+ hasClearableSilentNotifs = hasClearableSilentNotifs,
+ clearableAlertingSensitiveNotifUsers = clearableAlertingSensitiveNotifUsers,
+ clearableSilentSensitiveNotifUsers = clearableSilentSensitiveNotifUsers
)
}
} \ No newline at end of file
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/dagger/CoordinatorsModule.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/dagger/CoordinatorsModule.kt
index 274affd9da43..839cf0d7ef92 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/dagger/CoordinatorsModule.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/dagger/CoordinatorsModule.kt
@@ -17,10 +17,8 @@
package com.android.systemui.statusbar.notification.collection.coordinator.dagger
import com.android.systemui.dagger.SysUISingleton
-import com.android.systemui.statusbar.notification.collection.coordinator.ActivityLaunchAnimCoordinatorModule
import com.android.systemui.statusbar.notification.collection.coordinator.NotifCoordinators
import com.android.systemui.statusbar.notification.collection.coordinator.NotifCoordinatorsImpl
-import com.android.systemui.statusbar.notification.collection.coordinator.SensitiveContentCoordinatorModule
import dagger.Binds
import dagger.Module
import dagger.Provides
@@ -49,8 +47,6 @@ interface CoordinatorsSubcomponent {
}
@Module(includes = [
- ActivityLaunchAnimCoordinatorModule::class,
- SensitiveContentCoordinatorModule::class,
])
private abstract class InternalCoordinatorsModule {
@Binds
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/inflation/NotificationRowBinderImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/inflation/NotificationRowBinderImpl.java
index 4c7b2bbfb6d9..6e96aad776d2 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/inflation/NotificationRowBinderImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/inflation/NotificationRowBinderImpl.java
@@ -16,6 +16,8 @@
package com.android.systemui.statusbar.notification.collection.inflation;
+import static com.android.systemui.statusbar.notification.row.NotificationRowContentBinder.FLAG_CONTENT_VIEW_PUBLIC;
+
import static java.util.Objects.requireNonNull;
import android.annotation.Nullable;
@@ -249,10 +251,13 @@ public class NotificationRowBinderImpl implements NotificationRowBinder {
RowContentBindParams params = mRowContentBindStage.getStageParams(entry);
params.setUseIncreasedCollapsedHeight(useIncreasedCollapsedHeight);
params.setUseLowPriority(isLowPriority);
-
- // TODO: Replace this API with RowContentBindParams directly. Also move to a separate
- // redaction controller.
- row.setNeedsRedaction(mNotificationLockscreenUserManager.needsRedaction(entry));
+ boolean needsRedaction =
+ mNotificationLockscreenUserManager.notifNeedsRedactionInPublic(entry);
+ if (needsRedaction) {
+ params.requireContentViews(FLAG_CONTENT_VIEW_PUBLIC);
+ } else {
+ params.markContentViewsFreeable(FLAG_CONTENT_VIEW_PUBLIC);
+ }
params.rebindAllContentViews();
mRowContentBindStage.requestRebind(entry, en -> {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/inflation/OnUserInteractionCallbackImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/inflation/OnUserInteractionCallbackImpl.java
index 3bd91b5c8480..7dd3672a6e30 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/inflation/OnUserInteractionCallbackImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/inflation/OnUserInteractionCallbackImpl.java
@@ -18,17 +18,17 @@ package com.android.systemui.statusbar.notification.collection.inflation;
import static android.service.notification.NotificationStats.DISMISS_SENTIMENT_NEUTRAL;
-import android.annotation.Nullable;
import android.os.SystemClock;
-import android.service.notification.NotificationListenerService;
import android.service.notification.NotificationStats;
+import androidx.annotation.NonNull;
+
import com.android.systemui.plugins.statusbar.StatusBarStateController;
import com.android.systemui.statusbar.notification.collection.NotifCollection;
+import com.android.systemui.statusbar.notification.collection.NotifCollection.CancellationReason;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
import com.android.systemui.statusbar.notification.collection.coordinator.VisualStabilityCoordinator;
import com.android.systemui.statusbar.notification.collection.notifcollection.DismissedByUserStats;
-import com.android.systemui.statusbar.notification.collection.render.GroupMembershipManager;
import com.android.systemui.statusbar.notification.collection.render.NotificationVisibilityProvider;
import com.android.systemui.statusbar.notification.row.OnUserInteractionCallback;
import com.android.systemui.statusbar.policy.HeadsUpManager;
@@ -43,54 +43,33 @@ public class OnUserInteractionCallbackImpl implements OnUserInteractionCallback
private final HeadsUpManager mHeadsUpManager;
private final StatusBarStateController mStatusBarStateController;
private final VisualStabilityCoordinator mVisualStabilityCoordinator;
- private final GroupMembershipManager mGroupMembershipManager;
public OnUserInteractionCallbackImpl(
NotificationVisibilityProvider visibilityProvider,
NotifCollection notifCollection,
HeadsUpManager headsUpManager,
StatusBarStateController statusBarStateController,
- VisualStabilityCoordinator visualStabilityCoordinator,
- GroupMembershipManager groupMembershipManager
+ VisualStabilityCoordinator visualStabilityCoordinator
) {
mVisibilityProvider = visibilityProvider;
mNotifCollection = notifCollection;
mHeadsUpManager = headsUpManager;
mStatusBarStateController = statusBarStateController;
mVisualStabilityCoordinator = visualStabilityCoordinator;
- mGroupMembershipManager = groupMembershipManager;
}
- /**
- * Callback triggered when a user:
- * 1. Manually dismisses a notification {@see ExpandableNotificationRow}.
- * 2. Clicks on a notification with flag {@link android.app.Notification#FLAG_AUTO_CANCEL}.
- * {@see StatusBarNotificationActivityStarter}
- */
- @Override
- public void onDismiss(
- NotificationEntry entry,
- @NotificationListenerService.NotificationCancelReason int cancellationReason,
- @Nullable NotificationEntry groupSummaryToDismiss
- ) {
+ @NonNull
+ private DismissedByUserStats getDismissedByUserStats(NotificationEntry entry) {
int dismissalSurface = NotificationStats.DISMISSAL_SHADE;
if (mHeadsUpManager.isAlerting(entry.getKey())) {
dismissalSurface = NotificationStats.DISMISSAL_PEEK;
} else if (mStatusBarStateController.isDozing()) {
dismissalSurface = NotificationStats.DISMISSAL_AOD;
}
-
- if (groupSummaryToDismiss != null) {
- onDismiss(groupSummaryToDismiss, cancellationReason, null);
- }
-
- mNotifCollection.dismissNotification(
- entry,
- new DismissedByUserStats(
- dismissalSurface,
- DISMISS_SENTIMENT_NEUTRAL,
- mVisibilityProvider.obtain(entry, true))
- );
+ return new DismissedByUserStats(
+ dismissalSurface,
+ DISMISS_SENTIMENT_NEUTRAL,
+ mVisibilityProvider.obtain(entry, true));
}
@Override
@@ -100,19 +79,11 @@ public class OnUserInteractionCallbackImpl implements OnUserInteractionCallback
SystemClock.uptimeMillis());
}
- /**
- * @param entry that is being dismissed
- * @return the group summary to dismiss along with this entry if this is the last entry in
- * the group. Else, returns null.
- */
+ @NonNull
@Override
- @Nullable
- public NotificationEntry getGroupSummaryToDismiss(NotificationEntry entry) {
- String group = entry.getSbn().getGroup();
- if (mNotifCollection.isOnlyChildInGroup(entry)) {
- NotificationEntry summary = mNotifCollection.getGroupSummary(group);
- if (summary != null && summary.isDismissable()) return summary;
- }
- return null;
+ public Runnable registerFutureDismissal(@NonNull NotificationEntry entry,
+ @CancellationReason int cancellationReason) {
+ return mNotifCollection.registerFutureDismissal(
+ entry, cancellationReason, this::getDismissedByUserStats);
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/legacy/OnUserInteractionCallbackImplLegacy.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/legacy/OnUserInteractionCallbackImplLegacy.java
index 8daf8be0cc8f..103b14b09e9c 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/legacy/OnUserInteractionCallbackImplLegacy.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/legacy/OnUserInteractionCallbackImplLegacy.java
@@ -18,12 +18,15 @@ package com.android.systemui.statusbar.notification.collection.legacy;
import static android.service.notification.NotificationStats.DISMISS_SENTIMENT_NEUTRAL;
-import android.annotation.Nullable;
import android.service.notification.NotificationListenerService;
import android.service.notification.NotificationStats;
+import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
+
import com.android.systemui.plugins.statusbar.StatusBarStateController;
import com.android.systemui.statusbar.notification.NotificationEntryManager;
+import com.android.systemui.statusbar.notification.collection.NotifCollection.CancellationReason;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
import com.android.systemui.statusbar.notification.collection.notifcollection.DismissedByUserStats;
import com.android.systemui.statusbar.notification.collection.render.GroupMembershipManager;
@@ -68,8 +71,7 @@ public class OnUserInteractionCallbackImplLegacy implements OnUserInteractionCal
* along with this dismissal. If null, does not additionally
* dismiss any notifications.
*/
- @Override
- public void onDismiss(
+ private void onDismiss(
NotificationEntry entry,
@NotificationListenerService.NotificationCancelReason int cancellationReason,
@Nullable NotificationEntry groupSummaryToDismiss
@@ -106,14 +108,21 @@ public class OnUserInteractionCallbackImplLegacy implements OnUserInteractionCal
* @return the group summary to dismiss along with this entry if this is the last entry in
* the group. Else, returns null.
*/
- @Override
@Nullable
- public NotificationEntry getGroupSummaryToDismiss(NotificationEntry entry) {
+ private NotificationEntry getGroupSummaryToDismiss(NotificationEntry entry) {
if (mGroupMembershipManager.isOnlyChildInGroup(entry)) {
NotificationEntry groupSummary = mGroupMembershipManager.getLogicalGroupSummary(entry);
return groupSummary.isDismissable() ? groupSummary : null;
}
return null;
}
+
+ @Override
+ @NonNull
+ public Runnable registerFutureDismissal(@NonNull NotificationEntry entry,
+ @CancellationReason int cancellationReason) {
+ NotificationEntry groupSummaryToDismiss = getGroupSummaryToDismiss(entry);
+ return () -> onDismiss(entry, cancellationReason, groupSummaryToDismiss);
+ }
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/notifcollection/NotifCollectionLogger.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/notifcollection/NotifCollectionLogger.kt
index 7302de57e955..7e7936717b84 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/notifcollection/NotifCollectionLogger.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/notifcollection/NotifCollectionLogger.kt
@@ -28,7 +28,9 @@ import com.android.systemui.log.LogLevel.WTF
import com.android.systemui.log.dagger.NotificationLog
import com.android.systemui.statusbar.notification.collection.NotifCollection
import com.android.systemui.statusbar.notification.collection.NotifCollection.CancellationReason
+import com.android.systemui.statusbar.notification.collection.NotifCollection.FutureDismissal
import com.android.systemui.statusbar.notification.collection.NotificationEntry
+import com.android.systemui.statusbar.notification.logKey
import javax.inject.Inject
fun cancellationReasonDebugString(@CancellationReason reason: Int) =
@@ -36,6 +38,7 @@ fun cancellationReasonDebugString(@CancellationReason reason: Int) =
-1 -> "REASON_NOT_CANCELED" // NotifCollection.REASON_NOT_CANCELED
NotifCollection.REASON_UNKNOWN -> "REASON_UNKNOWN"
NotificationListenerService.REASON_CLICK -> "REASON_CLICK"
+ NotificationListenerService.REASON_CANCEL -> "REASON_CANCEL"
NotificationListenerService.REASON_CANCEL_ALL -> "REASON_CANCEL_ALL"
NotificationListenerService.REASON_ERROR -> "REASON_ERROR"
NotificationListenerService.REASON_PACKAGE_CHANGED -> "REASON_PACKAGE_CHANGED"
@@ -53,6 +56,9 @@ fun cancellationReasonDebugString(@CancellationReason reason: Int) =
NotificationListenerService.REASON_CHANNEL_BANNED -> "REASON_CHANNEL_BANNED"
NotificationListenerService.REASON_SNOOZED -> "REASON_SNOOZED"
NotificationListenerService.REASON_TIMEOUT -> "REASON_TIMEOUT"
+ NotificationListenerService.REASON_CHANNEL_REMOVED -> "REASON_CHANNEL_REMOVED"
+ NotificationListenerService.REASON_CLEAR_DATA -> "REASON_CLEAR_DATA"
+ NotificationListenerService.REASON_ASSISTANT_CANCEL -> "REASON_ASSISTANT_CANCEL"
else -> "unknown"
}
@@ -241,6 +247,81 @@ class NotifCollectionLogger @Inject constructor(
"ERROR suppressed due to initialization forgiveness: $str1"
})
}
+
+ fun logFutureDismissalReused(dismissal: FutureDismissal) {
+ buffer.log(TAG, INFO, {
+ str1 = dismissal.label
+ }, {
+ "Reusing existing registration: $str1"
+ })
+ }
+
+ fun logFutureDismissalRegistered(dismissal: FutureDismissal) {
+ buffer.log(TAG, DEBUG, {
+ str1 = dismissal.label
+ }, {
+ "Registered: $str1"
+ })
+ }
+
+ fun logFutureDismissalDoubleCancelledByServer(dismissal: FutureDismissal) {
+ buffer.log(TAG, WARNING, {
+ str1 = dismissal.label
+ }, {
+ "System server double cancelled: $str1"
+ })
+ }
+
+ fun logFutureDismissalDoubleRun(dismissal: FutureDismissal) {
+ buffer.log(TAG, WARNING, {
+ str1 = dismissal.label
+ }, {
+ "Double run: $str1"
+ })
+ }
+
+ fun logFutureDismissalAlreadyCancelledByServer(dismissal: FutureDismissal) {
+ buffer.log(TAG, DEBUG, {
+ str1 = dismissal.label
+ }, {
+ "Ignoring: entry already cancelled by server: $str1"
+ })
+ }
+
+ fun logFutureDismissalGotSystemServerCancel(
+ dismissal: FutureDismissal,
+ @CancellationReason cancellationReason: Int
+ ) {
+ buffer.log(TAG, DEBUG, {
+ str1 = dismissal.label
+ int1 = cancellationReason
+ }, {
+ "SystemServer cancelled: $str1 reason=${cancellationReasonDebugString(int1)}"
+ })
+ }
+
+ fun logFutureDismissalDismissing(dismissal: FutureDismissal, type: String) {
+ buffer.log(TAG, DEBUG, {
+ str1 = dismissal.label
+ str2 = type
+ }, {
+ "Dismissing $str2 for: $str1"
+ })
+ }
+
+ fun logFutureDismissalMismatchedEntry(
+ dismissal: FutureDismissal,
+ type: String,
+ latestEntry: NotificationEntry?
+ ) {
+ buffer.log(TAG, WARNING, {
+ str1 = dismissal.label
+ str2 = type
+ str3 = latestEntry.logKey
+ }, {
+ "Mismatch: current $str2 is $str3 for: $str1"
+ })
+ }
}
private const val TAG = "NotifCollection"
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/render/NodeSpecBuilder.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/render/NodeSpecBuilder.kt
index 6db544c77f87..8be710c8842c 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/render/NodeSpecBuilder.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/render/NodeSpecBuilder.kt
@@ -57,7 +57,6 @@ class NodeSpecBuilder(
var currentSection: NotifSection? = null
val prevSections = mutableSetOf<NotifSection?>()
- var lastSection: NotifSection? = null
val showHeaders = sectionHeaderVisibilityProvider.sectionHeadersVisible
val sectionOrder = mutableListOf<NotifSection?>()
val sectionHeaders = mutableMapOf<NotifSection?, NodeController?>()
@@ -65,15 +64,6 @@ class NodeSpecBuilder(
for (entry in notifList) {
val section = entry.section!!
-
- lastSection?.let {
- if (it.bucket > section.bucket) {
- throw IllegalStateException("buildNodeSpec with non contiguous section " +
- "buckets ${it.sectioner.name} - ${it.bucket} & " +
- "${it.sectioner.name} - ${it.bucket}")
- }
- }
- lastSection = section
if (prevSections.contains(section)) {
throw java.lang.RuntimeException("Section ${section.label} has been duplicated")
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/render/NotifStackController.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/render/NotifStackController.kt
index b6278d1d5f01..580d853dc5e9 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/render/NotifStackController.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/render/NotifStackController.kt
@@ -28,11 +28,21 @@ data class NotifStats(
val hasNonClearableAlertingNotifs: Boolean,
val hasClearableAlertingNotifs: Boolean,
val hasNonClearableSilentNotifs: Boolean,
- val hasClearableSilentNotifs: Boolean
+ val hasClearableSilentNotifs: Boolean,
+ val clearableAlertingSensitiveNotifUsers: Set<Int>,
+ val clearableSilentSensitiveNotifUsers: Set<Int>
) {
companion object {
@JvmStatic
- val empty = NotifStats(0, false, false, false, false)
+ val empty = NotifStats(
+ numActiveNotifs = 0,
+ hasNonClearableAlertingNotifs = false,
+ hasClearableAlertingNotifs = false,
+ hasNonClearableSilentNotifs = false,
+ hasClearableSilentNotifs = false,
+ clearableAlertingSensitiveNotifUsers = emptySet(),
+ clearableSilentSensitiveNotifUsers = emptySet(),
+ )
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/dagger/NotificationSectionHeadersModule.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/dagger/NotificationSectionHeadersModule.kt
index 2a9cfd034dce..f58918fe6f80 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/dagger/NotificationSectionHeadersModule.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/dagger/NotificationSectionHeadersModule.kt
@@ -182,4 +182,4 @@ annotation class HeaderClickAction
@Scope
@Retention(AnnotationRetention.BINARY)
-annotation class SectionHeaderScope \ No newline at end of file
+annotation class SectionHeaderScope
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/dagger/NotificationsModule.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/dagger/NotificationsModule.java
index d96590a82547..c9c7fe9e0ab6 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/dagger/NotificationsModule.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/dagger/NotificationsModule.java
@@ -88,7 +88,6 @@ import com.android.systemui.statusbar.notification.stack.NotificationSectionsMan
import com.android.systemui.statusbar.notification.stack.StackScrollAlgorithm;
import com.android.systemui.statusbar.phone.CentralSurfaces;
import com.android.systemui.statusbar.phone.KeyguardBypassController;
-import com.android.systemui.statusbar.phone.NotifActivityLaunchEventsModule;
import com.android.systemui.statusbar.phone.NotifPanelEventsModule;
import com.android.systemui.statusbar.phone.ShadeController;
import com.android.systemui.statusbar.policy.HeadsUpManager;
@@ -111,7 +110,6 @@ import dagger.Provides;
@Module(includes = {
CoordinatorsModule.class,
KeyguardNotificationVisibilityProviderModule.class,
- NotifActivityLaunchEventsModule.class,
NotifPanelEventsModule.class,
NotifPipelineChoreographerModule.class,
NotificationSectionHeadersModule.class,
@@ -350,8 +348,7 @@ public interface NotificationsModule {
notifCollection.get(),
headsUpManager,
statusBarStateController,
- visualStabilityCoordinator.get(),
- groupMembershipManagerLazy.get())
+ visualStabilityCoordinator.get())
: new OnUserInteractionCallbackImplLegacy(
entryManager,
visibilityProvider.get(),
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/icon/IconManager.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/icon/IconManager.kt
index d8965418b4c4..015e3d8cd553 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/icon/IconManager.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/icon/IconManager.kt
@@ -28,6 +28,7 @@ import android.widget.ImageView
import com.android.internal.statusbar.StatusBarIcon
import com.android.systemui.R
import com.android.systemui.dagger.SysUISingleton
+import com.android.systemui.statusbar.NotificationLockscreenUserManager
import com.android.systemui.statusbar.StatusBarIconView
import com.android.systemui.statusbar.notification.InflationException
import com.android.systemui.statusbar.notification.collection.NotificationEntry
@@ -49,31 +50,29 @@ import javax.inject.Inject
class IconManager @Inject constructor(
private val notifCollection: CommonNotifCollection,
private val launcherApps: LauncherApps,
- private val iconBuilder: IconBuilder
+ private val iconBuilder: IconBuilder,
+ private val notifLockscreenUserManager: NotificationLockscreenUserManager
) : ConversationIconManager {
private var unimportantConversationKeys: Set<String> = emptySet()
fun attach() {
notifCollection.addCollectionListener(entryListener)
+ notifLockscreenUserManager.addOnNeedsRedactionInPublicChangedListener(sensitivityListener)
}
private val entryListener = object : NotifCollectionListener {
- override fun onEntryInit(entry: NotificationEntry) {
- entry.addOnSensitivityChangedListener(sensitivityListener)
- }
-
- override fun onEntryCleanUp(entry: NotificationEntry) {
- entry.removeOnSensitivityChangedListener(sensitivityListener)
- }
-
override fun onRankingApplied() {
// rankings affect whether a conversation is important, which can change the icons
recalculateForImportantConversationChange()
}
}
- private val sensitivityListener = NotificationEntry.OnSensitivityChangedListener {
- entry -> updateIconsSafe(entry)
+ private val sensitivityListener = Runnable {
+ for (entry in notifCollection.allNotifs) {
+ if (entry.hasSensitiveContents()) {
+ updateIconsSafe(entry)
+ }
+ }
}
private fun recalculateForImportantConversationChange() {
@@ -182,12 +181,16 @@ class IconManager @Inject constructor(
}
}
+ private inline val NotificationEntry.needsRedactionInPublic: Boolean get() =
+ hasSensitiveContents() &&
+ notifLockscreenUserManager.sensitiveNotifsNeedRedactionInPublic(sbn.userId)
+
@Throws(InflationException::class)
private fun getIconDescriptors(
entry: NotificationEntry
): Pair<StatusBarIcon, StatusBarIcon> {
val iconDescriptor = getIconDescriptor(entry, false /* redact */)
- val sensitiveDescriptor = if (entry.isSensitive) {
+ val sensitiveDescriptor = if (entry.needsRedactionInPublic) {
getIconDescriptor(entry, true /* redact */)
} else {
iconDescriptor
@@ -310,7 +313,7 @@ class IconManager @Inject constructor(
iconView === entry.icons.shelfIcon || iconView === entry.icons.aodIcon
val isSmallIcon = iconDescriptor.icon.equals(entry.sbn.notification.smallIcon)
return isImportantConversation(entry) && !isSmallIcon &&
- (!usedInSensitiveContext || !entry.isSensitive)
+ (!usedInSensitiveContext || !entry.needsRedactionInPublic)
}
private fun isImportantConversation(entry: NotificationEntry): Boolean {
@@ -338,4 +341,4 @@ interface ConversationIconManager {
* of a group from which the priority notification has been removed.
*/
fun setUnimportantConversations(keys: Collection<String>)
-} \ No newline at end of file
+}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java
index dff8c47e36e0..d5088acaa61c 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java
@@ -17,7 +17,6 @@
package com.android.systemui.statusbar.notification.row;
import static android.app.Notification.Action.SEMANTIC_ACTION_MARK_CONVERSATION_AS_PRIORITY;
-import static android.os.UserHandle.USER_SYSTEM;
import static android.service.notification.NotificationListenerService.REASON_CANCEL;
import static com.android.systemui.statusbar.notification.row.NotificationContentView.VISIBLE_TYPE_HEADSUP;
@@ -34,8 +33,6 @@ import android.app.Notification;
import android.app.NotificationChannel;
import android.app.role.RoleManager;
import android.content.Context;
-import android.content.pm.PackageInfo;
-import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Canvas;
@@ -51,7 +48,6 @@ import android.os.Bundle;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.Trace;
-import android.provider.Settings;
import android.service.notification.StatusBarNotification;
import android.util.ArraySet;
import android.util.AttributeSet;
@@ -60,6 +56,7 @@ import android.util.IndentingPrintWriter;
import android.util.Log;
import android.util.MathUtils;
import android.util.Property;
+import android.util.Slog;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
@@ -93,8 +90,8 @@ import com.android.systemui.statusbar.RemoteInputController;
import com.android.systemui.statusbar.SmartReplyController;
import com.android.systemui.statusbar.StatusBarIconView;
import com.android.systemui.statusbar.notification.AboveShelfChangedListener;
-import com.android.systemui.statusbar.notification.LaunchAnimationParameters;
import com.android.systemui.statusbar.notification.FeedbackIcon;
+import com.android.systemui.statusbar.notification.LaunchAnimationParameters;
import com.android.systemui.statusbar.notification.NotificationFadeAware;
import com.android.systemui.statusbar.notification.NotificationLaunchAnimatorController;
import com.android.systemui.statusbar.notification.NotificationUtils;
@@ -112,7 +109,6 @@ import com.android.systemui.statusbar.notification.stack.ExpandableViewState;
import com.android.systemui.statusbar.notification.stack.NotificationChildrenContainer;
import com.android.systemui.statusbar.notification.stack.NotificationStackScrollLayout;
import com.android.systemui.statusbar.notification.stack.SwipeableView;
-import com.android.systemui.statusbar.phone.CentralSurfaces;
import com.android.systemui.statusbar.phone.KeyguardBypassController;
import com.android.systemui.statusbar.policy.HeadsUpManager;
import com.android.systemui.statusbar.policy.InflatedSmartReplyState;
@@ -206,7 +202,6 @@ public class ExpandableNotificationRow extends ActivatableNotificationView
/** Are we showing the "public" version */
private boolean mShowingPublic;
private boolean mSensitive;
- private boolean mSensitiveHiddenInGeneral;
private boolean mShowingPublicInitialized;
private boolean mHideSensitiveForIntrinsicHeight;
private float mHeaderVisibleAmount = DEFAULT_HEADER_VISIBLE_AMOUNT;
@@ -364,9 +359,6 @@ public class ExpandableNotificationRow extends ActivatableNotificationView
@Nullable private OnExpansionChangedListener mExpansionChangedListener;
@Nullable private Runnable mOnIntrinsicHeightReachedRunnable;
- private SystemNotificationAsyncTask mSystemNotificationAsyncTask =
- new SystemNotificationAsyncTask();
-
private float mTopRoundnessDuringLaunchAnimation;
private float mBottomRoundnessDuringLaunchAnimation;
@@ -518,45 +510,20 @@ public class ExpandableNotificationRow extends ActivatableNotificationView
}
/**
- * Caches whether or not this row contains a system notification. Note, this is only cached
- * once per notification as the packageInfo can't technically change for a notification row.
- */
- private void cacheIsSystemNotification() {
- //TODO: This probably shouldn't be in ExpandableNotificationRow
- if (mEntry != null && mEntry.mIsSystemNotification == null) {
- if (mSystemNotificationAsyncTask.getStatus() == AsyncTask.Status.PENDING) {
- // Run async task once, only if it hasn't already been executed. Note this is
- // executed in serial - no need to parallelize this small task.
- mSystemNotificationAsyncTask.execute();
- }
- }
- }
-
- /**
* Returns whether this row is considered non-blockable (i.e. it's a non-blockable system notif
* or is in an allowList).
*/
public boolean getIsNonblockable() {
- // If the SystemNotifAsyncTask hasn't finished running or retrieved a value, we'll try once
- // again, but in-place on the main thread this time. This should rarely ever get called.
- if (mEntry != null && mEntry.mIsSystemNotification == null) {
- if (DEBUG) {
- Log.d(TAG, "Retrieving isSystemNotification on main thread");
- }
- mSystemNotificationAsyncTask.cancel(true /* mayInterruptIfRunning */);
- mEntry.mIsSystemNotification = isSystemNotification(mContext, mEntry.getSbn());
+ if (mEntry == null || mEntry.getChannel() == null) {
+ Log.w(TAG, "missing entry or channel");
+ return true;
}
-
- boolean isNonblockable = mEntry.getChannel().isImportanceLockedByCriticalDeviceFunction();
-
- if (!isNonblockable && mEntry != null && mEntry.mIsSystemNotification != null) {
- if (mEntry.mIsSystemNotification) {
- if (mEntry.getChannel() != null && !mEntry.getChannel().isBlockable()) {
- isNonblockable = true;
- }
- }
+ if (mEntry.getChannel().isImportanceLockedByCriticalDeviceFunction()
+ && !mEntry.getChannel().isBlockable()) {
+ return true;
}
- return isNonblockable;
+
+ return false;
}
private boolean isConversation() {
@@ -1456,8 +1423,7 @@ public class ExpandableNotificationRow extends ActivatableNotificationView
dismiss(fromAccessibility);
if (mEntry.isDismissable()) {
if (mOnUserInteractionCallback != null) {
- mOnUserInteractionCallback.onDismiss(mEntry, REASON_CANCEL,
- mOnUserInteractionCallback.getGroupSummaryToDismiss(mEntry));
+ mOnUserInteractionCallback.registerFutureDismissal(mEntry, REASON_CANCEL).run();
}
}
}
@@ -1538,6 +1504,7 @@ public class ExpandableNotificationRow extends ActivatableNotificationView
mUseIncreasedHeadsUpHeight = use;
}
+ // TODO: remove this method and mNeedsRedaction entirely once the old pipeline is gone
public void setNeedsRedaction(boolean needsRedaction) {
// TODO: Move inflation logic out of this call and remove this method
if (mNeedsRedaction != needsRedaction) {
@@ -1626,8 +1593,6 @@ public class ExpandableNotificationRow extends ActivatableNotificationView
mBubblesManagerOptional = bubblesManagerOptional;
mNotificationGutsManager = gutsManager;
mMetricsLogger = metricsLogger;
-
- cacheIsSystemNotification();
}
private void initDimens() {
@@ -2622,9 +2587,8 @@ public class ExpandableNotificationRow extends ActivatableNotificationView
getShowingLayout().requestSelectLayout(needsAnimation || isUserLocked());
}
- public void setSensitive(boolean sensitive, boolean hideSensitive) {
+ public void setSensitive(boolean sensitive) {
mSensitive = sensitive;
- mSensitiveHiddenInGeneral = hideSensitive;
}
@Override
@@ -2714,7 +2678,15 @@ public class ExpandableNotificationRow extends ActivatableNotificationView
* see {@link NotificationEntry#isDismissable()}.
*/
public boolean canViewBeDismissed() {
- return mEntry.isDismissable() && (!shouldShowPublic() || !mSensitiveHiddenInGeneral);
+ // Entry not dismissable.
+ if (!mEntry.isDismissable()) {
+ return false;
+ }
+ // Entry shouldn't be showing the public layout, it can be dismissed.
+ if (!shouldShowPublic()) {
+ return true;
+ }
+ return false;
}
/**
@@ -2723,7 +2695,7 @@ public class ExpandableNotificationRow extends ActivatableNotificationView
* clearability see {@link NotificationEntry#isClearable()}.
*/
public boolean canViewBeCleared() {
- return mEntry.isClearable() && (!shouldShowPublic() || !mSensitiveHiddenInGeneral);
+ return mEntry.isClearable() && !shouldShowPublic();
}
private boolean shouldShowPublic() {
@@ -3487,10 +3459,28 @@ public class ExpandableNotificationRow extends ActivatableNotificationView
pw.print(", translation: " + getTranslation());
pw.print(", removed: " + isRemoved());
pw.print(", expandAnimationRunning: " + mExpandAnimationRunning);
- NotificationContentView showingLayout = getShowingLayout();
- pw.print(", privateShowing: " + (showingLayout == mPrivateLayout));
- pw.println();
- showingLayout.dump(pw, args);
+ pw.print(", sensitive: " + mSensitive);
+ pw.print(", hideSensitiveForIntrinsicHeight: " + mHideSensitiveForIntrinsicHeight);
+ pw.println(", privateShowing: " + !shouldShowPublic());
+ pw.print("privateLayout: ");
+ if (mPrivateLayout != null) {
+ pw.println();
+ DumpUtilsKt.withIncreasedIndent(pw, () -> {
+ mPrivateLayout.dump(pw, args);
+ mPrivateLayout.dumpSmartReplies(pw);
+ });
+ } else {
+ pw.println("null");
+ }
+ pw.print("publicLayout: ");
+ if (mPublicLayout != null) {
+ pw.println();
+ DumpUtilsKt.withIncreasedIndent(pw, () -> {
+ mPublicLayout.dump(pw, args);
+ });
+ } else {
+ pw.println("null");
+ }
if (getViewState() != null) {
getViewState().dump(pw, args);
@@ -3516,31 +3506,10 @@ public class ExpandableNotificationRow extends ActivatableNotificationView
}
pw.decreaseIndent();
pw.println("}");
- } else if (mPrivateLayout != null) {
- mPrivateLayout.dumpSmartReplies(pw);
}
});
}
- /**
- * Background task for executing IPCs to check if the notification is a system notification. The
- * output is used for both the blocking helper and the notification info.
- */
- private class SystemNotificationAsyncTask extends AsyncTask<Void, Void, Boolean> {
-
- @Override
- protected Boolean doInBackground(Void... voids) {
- return isSystemNotification(mContext, mEntry.getSbn());
- }
-
- @Override
- protected void onPostExecute(Boolean result) {
- if (mEntry != null) {
- mEntry.mIsSystemNotification = result;
- }
- }
- }
-
private void setTargetPoint(Point p) {
mTargetPoint = p;
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRowController.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRowController.java
index 599039d46556..a60026c7a97b 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRowController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRowController.java
@@ -35,6 +35,7 @@ import com.android.systemui.plugins.FalsingManager;
import com.android.systemui.plugins.statusbar.NotificationMenuRowPlugin;
import com.android.systemui.plugins.statusbar.StatusBarStateController;
import com.android.systemui.shared.plugins.PluginManager;
+import com.android.systemui.statusbar.NotificationLockscreenUserManager;
import com.android.systemui.statusbar.NotificationMediaManager;
import com.android.systemui.statusbar.SmartReplyController;
import com.android.systemui.statusbar.notification.FeedbackIcon;
@@ -69,6 +70,7 @@ import javax.inject.Named;
public class ExpandableNotificationRowController implements NotifViewController {
private static final String TAG = "NotifRowController";
private final ExpandableNotificationRow mView;
+ private final NotificationLockscreenUserManager mLockscreenUserManager;
private final NotificationListContainer mListContainer;
private final RemoteInputViewSubcomponent.Factory mRemoteInputViewSubcomponentFactory;
private final ActivatableNotificationViewController mActivatableNotificationViewController;
@@ -86,7 +88,6 @@ public class ExpandableNotificationRowController implements NotifViewController
private final ExpandableNotificationRow.OnExpandClickListener mOnExpandClickListener;
private final StatusBarStateController mStatusBarStateController;
private final MetricsLogger mMetricsLogger;
-
private final ExpandableNotificationRow.ExpansionLogger mExpansionLogger =
this::logNotificationExpansion;
private final ExpandableNotificationRow.CoordinateOnClickListener mOnFeedbackClickListener;
@@ -100,12 +101,12 @@ public class ExpandableNotificationRowController implements NotifViewController
private final Optional<BubblesManager> mBubblesManagerOptional;
private final SmartReplyConstants mSmartReplyConstants;
private final SmartReplyController mSmartReplyController;
-
private final ExpandableNotificationRowDragController mDragController;
@Inject
public ExpandableNotificationRowController(
ExpandableNotificationRow view,
+ NotificationLockscreenUserManager lockscreenUserManager,
ActivatableNotificationViewController activatableNotificationViewController,
RemoteInputViewSubcomponent.Factory rivSubcomponentFactory,
MetricsLogger metricsLogger,
@@ -135,6 +136,7 @@ public class ExpandableNotificationRowController implements NotifViewController
Optional<BubblesManager> bubblesManagerOptional,
ExpandableNotificationRowDragController dragController) {
mView = view;
+ mLockscreenUserManager = lockscreenUserManager;
mListContainer = listContainer;
mRemoteInputViewSubcomponentFactory = rivSubcomponentFactory;
mActivatableNotificationViewController = activatableNotificationViewController;
@@ -214,6 +216,10 @@ public class ExpandableNotificationRowController implements NotifViewController
mView.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
}
+ mLockscreenUserManager
+ .addOnNeedsRedactionInPublicChangedListener(mNeedsRedactionListener);
+ mNeedsRedactionListener.run();
+
mView.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
@Override
public void onViewAttachedToWindow(View v) {
@@ -232,6 +238,14 @@ public class ExpandableNotificationRowController implements NotifViewController
});
}
+ private final Runnable mNeedsRedactionListener = new Runnable() {
+ @Override
+ public void run() {
+ mView.setSensitive(
+ mLockscreenUserManager.notifNeedsRedactionInPublic(mView.getEntry()));
+ }
+ };
+
private final StatusBarStateController.StateListener mStatusBarStateListener =
new StatusBarStateController.StateListener() {
@Override
@@ -333,4 +347,5 @@ public class ExpandableNotificationRowController implements NotifViewController
public void setFeedbackIcon(@Nullable FeedbackIcon icon) {
mView.setFeedbackIcon(icon);
}
+
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationContentView.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationContentView.java
index ba26cfaa30b4..a7c6bfb0289c 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationContentView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationContentView.java
@@ -61,6 +61,7 @@ import com.android.systemui.statusbar.policy.SmartReplyStateInflaterKt;
import com.android.systemui.statusbar.policy.SmartReplyView;
import com.android.systemui.statusbar.policy.dagger.RemoteInputViewSubcomponent;
import com.android.systemui.util.Compile;
+import com.android.systemui.util.DumpUtilsKt;
import com.android.systemui.wmshell.BubblesManager;
import java.io.PrintWriter;
@@ -1994,22 +1995,33 @@ public class NotificationContentView extends FrameLayout implements Notification
}
}
- public void dump(PrintWriter pw, String[] args) {
+ public void dump(PrintWriter pwOriginal, String[] args) {
+ IndentingPrintWriter pw = DumpUtilsKt.asIndenting(pwOriginal);
pw.print("contentView visibility: " + getVisibility());
pw.print(", alpha: " + getAlpha());
pw.print(", clipBounds: " + getClipBounds());
pw.print(", contentHeight: " + mContentHeight);
- pw.print(", visibleType: " + mVisibleType);
- View view = getViewForVisibleType(mVisibleType);
- pw.print(", visibleView ");
- if (view != null) {
- pw.print(" visibility: " + view.getVisibility());
- pw.print(", alpha: " + view.getAlpha());
- pw.print(", clipBounds: " + view.getClipBounds());
- } else {
- pw.print("null");
- }
- pw.println();
+ pw.println(", currentVisibleType: " + mVisibleType);
+ DumpUtilsKt.withIncreasedIndent(pw, () -> {
+ int[] visTypes = {
+ VISIBLE_TYPE_CONTRACTED,
+ VISIBLE_TYPE_EXPANDED,
+ VISIBLE_TYPE_HEADSUP,
+ VISIBLE_TYPE_SINGLELINE
+ };
+ for (int visType : visTypes) {
+ pw.print("visType: " + visType + " :: ");
+ View view = getViewForVisibleType(visType);
+ if (view != null) {
+ pw.print("visibility: " + view.getVisibility());
+ pw.print(", alpha: " + view.getAlpha());
+ pw.print(", clipBounds: " + view.getClipBounds());
+ } else {
+ pw.print("null");
+ }
+ pw.println();
+ }
+ });
}
/** Add any existing SmartReplyView to the dump */
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/OnUserInteractionCallback.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/OnUserInteractionCallback.java
index 94c5507cfbf4..98d43539841d 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/OnUserInteractionCallback.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/OnUserInteractionCallback.java
@@ -16,8 +16,9 @@
package com.android.systemui.statusbar.notification.row;
-import android.service.notification.NotificationListenerService;
+import androidx.annotation.NonNull;
+import com.android.systemui.statusbar.notification.collection.NotifCollection.CancellationReason;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
/**
@@ -26,29 +27,23 @@ import com.android.systemui.statusbar.notification.collection.NotificationEntry;
public interface OnUserInteractionCallback {
/**
- * Handle a user interaction that triggers a notification dismissal. Called when a user clicks
- * on an auto-cancelled notification or manually swipes to dismiss the notification.
- *
- * @param entry notification being dismissed
- * @param cancellationReason reason for the cancellation
- * @param groupSummaryToDismiss group summary to dismiss with `entry`.
- */
- void onDismiss(
- NotificationEntry entry,
- @NotificationListenerService.NotificationCancelReason int cancellationReason,
- NotificationEntry groupSummaryToDismiss);
-
- /**
* Triggered after a user has changed the importance of the notification via its
* {@link NotificationGuts}.
*/
void onImportanceChanged(NotificationEntry entry);
-
/**
- * @param entry being dismissed by the user
- * @return group summary that should be dismissed along with `entry`. Can be null if no
- * relevant group summary exists or the group summary should not be dismissed with `entry`.
+ * Called once it is known that a dismissal will take place for the given reason.
+ * This returns a Runnable which MUST be invoked when the dismissal is ready to be completed.
+ *
+ * Registering for future dismissal is typically done before notifying the NMS that a
+ * notification was clicked or dismissed, but the local dismissal may happen later.
+ *
+ * @param entry the entry being cancelled
+ * @param cancellationReason the reason for the cancellation
+ * @return the runnable to call when the dismissal can happen
*/
- NotificationEntry getGroupSummaryToDismiss(NotificationEntry entry);
+ @NonNull
+ Runnable registerFutureDismissal(@NonNull NotificationEntry entry,
+ @CancellationReason int cancellationReason);
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/RowContentBindParams.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/RowContentBindParams.java
index f26ecc32821d..a52f638e7c26 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/RowContentBindParams.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/RowContentBindParams.java
@@ -102,8 +102,9 @@ public final class RowContentBindParams {
* @see InflationFlag
*/
public void markContentViewsFreeable(@InflationFlag int contentViews) {
+ @InflationFlag int existingContentViews = contentViews &= mContentViews;
mContentViews &= ~contentViews;
- mDirtyContentViews &= ~contentViews;
+ mDirtyContentViews |= existingContentViews;
}
public @InflationFlag int getContentViews() {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/StackScrollerDecorView.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/StackScrollerDecorView.java
index aa3e027fe1af..7414bdc13672 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/StackScrollerDecorView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/StackScrollerDecorView.java
@@ -16,6 +16,7 @@
package com.android.systemui.statusbar.notification.row;
+import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.util.AttributeSet;
@@ -25,6 +26,8 @@ import android.view.animation.Interpolator;
import com.android.internal.annotations.VisibleForTesting;
import com.android.systemui.animation.Interpolators;
+import java.util.function.Consumer;
+
/**
* A common base class for all views in the notification stack scroller which don't have a
* background.
@@ -48,7 +51,7 @@ public abstract class StackScrollerDecorView extends ExpandableView {
};
private boolean mSecondaryAnimating = false;
- private final Runnable mSecondaryVisibilityEndRunnable = () -> {
+ private final Consumer<Boolean> mSecondaryVisibilityEndRunnable = (cancelled) -> {
mSecondaryAnimating = false;
// If we were on screen, become GONE to avoid touches
if (mSecondaryView == null) return;
@@ -96,18 +99,20 @@ public abstract class StackScrollerDecorView extends ExpandableView {
* @param animate True if we should fade to new visibility
* @param runAfter Runnable to run after visibility updates
*/
- public void setContentVisible(boolean visible, boolean animate, Runnable runAfter) {
+ public void setContentVisible(boolean visible, boolean animate, Consumer<Boolean> runAfter) {
if (mContentVisible != visible) {
mContentAnimating = animate;
mContentVisible = visible;
- Runnable endRunnable = runAfter == null ? mContentVisibilityEndRunnable : () -> {
+ Consumer<Boolean> endRunnable = (cancelled) -> {
mContentVisibilityEndRunnable.run();
- runAfter.run();
+ if (runAfter != null) {
+ runAfter.accept(cancelled);
+ }
};
setViewVisible(mContent, visible, animate, endRunnable);
} else if (runAfter != null) {
// Execute the runAfter runnable immediately if there's no animation to perform.
- runAfter.run();
+ runAfter.accept(true);
}
if (!mContentAnimating) {
@@ -119,10 +124,6 @@ public abstract class StackScrollerDecorView extends ExpandableView {
return mContentVisible;
}
- public void setVisible(boolean nowVisible, boolean animate) {
- setVisible(nowVisible, animate, null);
- }
-
/**
* Make this view visible. If {@code false} is passed, the view will fade out it's content
* and set the view Visibility to GONE. If only the content should be changed
@@ -131,7 +132,7 @@ public abstract class StackScrollerDecorView extends ExpandableView {
* @param nowVisible should the view be visible
* @param animate should the change be animated.
*/
- public void setVisible(boolean nowVisible, boolean animate, Runnable runAfter) {
+ public void setVisible(boolean nowVisible, boolean animate) {
if (mIsVisible != nowVisible) {
mIsVisible = nowVisible;
if (animate) {
@@ -142,10 +143,10 @@ public abstract class StackScrollerDecorView extends ExpandableView {
} else {
setWillBeGone(true);
}
- setContentVisible(nowVisible, true /* animate */, runAfter);
+ setContentVisible(nowVisible, true /* animate */, null /* runAfter */);
} else {
setVisibility(nowVisible ? VISIBLE : GONE);
- setContentVisible(nowVisible, false /* animate */, runAfter);
+ setContentVisible(nowVisible, false /* animate */, null /* runAfter */);
setWillBeGone(false);
notifyHeightChanged(false /* needsAnimation */);
}
@@ -166,7 +167,7 @@ public abstract class StackScrollerDecorView extends ExpandableView {
}
if (!mSecondaryAnimating) {
- mSecondaryVisibilityEndRunnable.run();
+ mSecondaryVisibilityEndRunnable.accept(true /* cancelled */);
}
}
@@ -195,7 +196,7 @@ public abstract class StackScrollerDecorView extends ExpandableView {
* @param endRunnable A runnable that is run when the animation is done.
*/
private void setViewVisible(View view, boolean nowVisible,
- boolean animate, Runnable endRunnable) {
+ boolean animate, Consumer<Boolean> endRunnable) {
if (view == null) {
return;
}
@@ -211,7 +212,7 @@ public abstract class StackScrollerDecorView extends ExpandableView {
if (!animate) {
view.setAlpha(endValue);
if (endRunnable != null) {
- endRunnable.run();
+ endRunnable.accept(true);
}
return;
}
@@ -222,7 +223,19 @@ public abstract class StackScrollerDecorView extends ExpandableView {
.alpha(endValue)
.setInterpolator(interpolator)
.setDuration(mDuration)
- .withEndAction(endRunnable);
+ .setListener(new AnimatorListenerAdapter() {
+ boolean mCancelled;
+
+ @Override
+ public void onAnimationCancel(Animator animation) {
+ mCancelled = true;
+ }
+
+ @Override
+ public void onAnimationEnd(Animator animation) {
+ endRunnable.accept(mCancelled);
+ }
+ });
}
@Override
@@ -231,7 +244,7 @@ public abstract class StackScrollerDecorView extends ExpandableView {
Runnable onFinishedRunnable,
AnimatorListenerAdapter animationListener) {
// TODO: Use duration
- setContentVisible(false, true /* animate */, onFinishedRunnable);
+ setContentVisible(false, true /* animate */, (cancelled) -> onFinishedRunnable.run());
return 0;
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayout.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayout.java
index 3ea5e5b753a3..4d325e154a4f 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayout.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayout.java
@@ -1805,13 +1805,20 @@ public class NotificationStackScrollLayout extends ViewGroup implements Dumpable
}
@ShadeViewRefactor(RefactorComponent.STATE_RESOLVER)
- public void dismissViewAnimated(View child, Runnable endRunnable, int delay, long duration) {
+ public void dismissViewAnimated(
+ View child, Consumer<Boolean> endRunnable, int delay, long duration) {
if (child instanceof SectionHeaderView) {
((StackScrollerDecorView) child).setContentVisible(
false /* visible */, true /* animate */, endRunnable);
return;
}
- mSwipeHelper.dismissChild(child, 0, endRunnable, delay, true, duration,
+ mSwipeHelper.dismissChild(
+ child,
+ 0 /* velocity */,
+ endRunnable,
+ delay,
+ true /* useAccelerateInterpolator */,
+ duration,
true /* isClearAll */);
}
@@ -5196,11 +5203,15 @@ public class NotificationStackScrollLayout extends ViewGroup implements Dumpable
if (mClearAllListener != null) {
mClearAllListener.onClearAll(selection);
}
- final Runnable dismissInBackend = () -> {
- onClearAllAnimationsEnd(rowsToDismissInBackend, selection);
+ final Consumer<Boolean> dismissInBackend = (cancelled) -> {
+ if (cancelled) {
+ post(() -> onClearAllAnimationsEnd(rowsToDismissInBackend, selection));
+ } else {
+ onClearAllAnimationsEnd(rowsToDismissInBackend, selection);
+ }
};
if (viewsToAnimateAway.isEmpty()) {
- dismissInBackend.run();
+ dismissInBackend.accept(true);
return;
}
// Disable normal animations
@@ -5215,7 +5226,7 @@ public class NotificationStackScrollLayout extends ViewGroup implements Dumpable
final int numItems = viewsToAnimateAway.size();
for (int i = numItems - 1; i >= 0; i--) {
View view = viewsToAnimateAway.get(i);
- Runnable endRunnable = null;
+ Consumer<Boolean> endRunnable = null;
if (i == 0) {
endRunnable = dismissInBackend;
}
@@ -5517,6 +5528,7 @@ public class NotificationStackScrollLayout extends ViewGroup implements Dumpable
*/
public void setFractionToShade(float fraction) {
mAmbientState.setFractionToShade(fraction);
+ updateContentHeight(); // Recompute stack height with different section gap.
requestChildrenUpdate();
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutController.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutController.java
index 2493ccbe5a48..6a8f4796813a 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutController.java
@@ -216,6 +216,9 @@ public class NotificationStackScrollLayoutController {
mBarState = mStatusBarStateController.getState();
mStatusBarStateController.addCallback(
mStateListener, SysuiStatusBarStateController.RANK_STACK_SCROLLER);
+ mLockscreenUserManager.addOnNeedsRedactionInPublicChangedListener(
+ mOnNeedsRedactionInPublicChangedListener);
+ updateClearButtonVisibility();
}
@Override
@@ -223,6 +226,8 @@ public class NotificationStackScrollLayoutController {
mConfigurationController.removeCallback(mConfigurationListener);
mZenModeController.removeCallback(mZenModeControllerCallback);
mStatusBarStateController.removeCallback(mStateListener);
+ mLockscreenUserManager.removeOnNeedsRedactionInPublicChangedListener(
+ mOnNeedsRedactionInPublicChangedListener);
}
};
@@ -326,6 +331,7 @@ public class NotificationStackScrollLayoutController {
mLockscreenUserManager.isAnyProfilePublicMode());
mView.onStatePostChange(mStatusBarStateController.fromShadeLocked());
mNotificationEntryManager.updateNotifications("CentralSurfaces state changed");
+ updateClearButtonVisibility();
}
};
@@ -338,6 +344,17 @@ public class NotificationStackScrollLayoutController {
}
};
+ private final Runnable mOnNeedsRedactionInPublicChangedListener = new Runnable() {
+ @Override
+ public void run() {
+ // Whether or not the notification needs redaction when in public has changed, but if
+ // we're not actually in public, then we don't need to update anything.
+ if (mLockscreenUserManager.isAnyProfilePublicMode()) {
+ updateClearButtonVisibility();
+ }
+ }
+ };
+
/**
* Set the overexpansion of the panel to be applied to the view.
*/
@@ -1274,12 +1291,44 @@ public class NotificationStackScrollLayoutController {
return hasNotifications(selection, true /* clearable */);
}
+ private boolean hasRedactedClearableSilentNotifs() {
+ if (!mLockscreenUserManager.isAnyProfilePublicMode()) {
+ return false;
+ }
+ for (int userId : mNotifStats.getClearableSilentSensitiveNotifUsers()) {
+ if (mLockscreenUserManager.sensitiveNotifsNeedRedactionInPublic(userId)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private boolean hasClearableSilentNotifs() {
+ return mNotifStats.getHasClearableSilentNotifs() && !hasRedactedClearableSilentNotifs();
+ }
+
+ private boolean hasRedactedClearableAlertingNotifs() {
+ if (!mLockscreenUserManager.isAnyProfilePublicMode()) {
+ return false;
+ }
+ for (int userId : mNotifStats.getClearableAlertingSensitiveNotifUsers()) {
+ if (mLockscreenUserManager.sensitiveNotifsNeedRedactionInPublic(userId)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private boolean hasClearableAlertingNotifs() {
+ return mNotifStats.getHasClearableAlertingNotifs() && !hasRedactedClearableAlertingNotifs();
+ }
+
public boolean hasNotifications(@SelectedRows int selection, boolean isClearable) {
boolean hasAlertingMatchingClearable = isClearable
- ? mNotifStats.getHasClearableAlertingNotifs()
+ ? hasClearableAlertingNotifs()
: mNotifStats.getHasNonClearableAlertingNotifs();
boolean hasSilentMatchingClearable = isClearable
- ? mNotifStats.getHasClearableSilentNotifs()
+ ? hasClearableSilentNotifs()
: mNotifStats.getHasNonClearableSilentNotifs();
switch (selection) {
case ROWS_GENTLE:
@@ -1579,6 +1628,15 @@ public class NotificationStackScrollLayoutController {
mNotificationActivityStarter = activityStarter;
}
+ private void updateClearButtonVisibility() {
+ updateClearSilentButton();
+ updateFooter();
+ }
+
+ private void updateClearSilentButton() {
+ mSilentHeaderController.setClearSectionEnabled(hasClearableSilentNotifs());
+ }
+
/**
* Enum for UiEvent logged from this class
*/
@@ -1904,6 +1962,7 @@ public class NotificationStackScrollLayoutController {
@Override
public void setNotifStats(@NonNull NotifStats notifStats) {
mNotifStats = notifStats;
+ updateClearSilentButton();
updateFooter();
updateShowEmptyShadeView();
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/StackScrollAlgorithm.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/StackScrollAlgorithm.java
index 2b79986662f1..799fee5e865d 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/StackScrollAlgorithm.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/StackScrollAlgorithm.java
@@ -49,9 +49,10 @@ public class StackScrollAlgorithm {
public static final float START_FRACTION = 0.5f;
- private static final String LOG_TAG = "StackScrollAlgorithm";
- private final ViewGroup mHostView;
+ private static final String TAG = "StackScrollAlgorithm";
+ private static final Boolean DEBUG = false;
+ private final ViewGroup mHostView;
private int mPaddingBetweenElements;
private int mGapHeight;
private int mGapHeightOnLockscreen;
@@ -126,6 +127,37 @@ public class StackScrollAlgorithm {
return getExpansionFractionWithoutShelf(mTempAlgorithmState, ambientState);
}
+ private void log(String s) {
+ if (DEBUG) {
+ android.util.Log.i(TAG, s);
+ }
+ }
+
+ public void logView(View view, String s) {
+ String viewString = "";
+ if (view instanceof ExpandableNotificationRow) {
+ ExpandableNotificationRow row = ((ExpandableNotificationRow) view);
+ if (row.getEntry() == null) {
+ viewString = "ExpandableNotificationRow has null NotificationEntry";
+ } else {
+ viewString = row.getEntry().getSbn().getId() + "";
+ }
+ } else if (view == null) {
+ viewString = "View is null";
+ } else if (view instanceof SectionHeaderView) {
+ viewString = "SectionHeaderView";
+ } else if (view instanceof FooterView) {
+ viewString = "FooterView";
+ } else if (view instanceof MediaContainerView) {
+ viewString = "MediaContainerView";
+ } else if (view instanceof EmptyShadeView) {
+ viewString = "EmptyShadeView";
+ } else {
+ viewString = view.toString();
+ }
+ log(viewString + " " + s);
+ }
+
private void resetChildViewStates() {
int numChildren = mHostView.getChildCount();
for (int i = 0; i < numChildren; i++) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/HeadsUpAppearanceController.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/HeadsUpAppearanceController.java
index 9863a0ed1ce0..f386797e322a 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/HeadsUpAppearanceController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/HeadsUpAppearanceController.java
@@ -29,6 +29,7 @@ import com.android.systemui.plugins.statusbar.StatusBarStateController;
import com.android.systemui.statusbar.CommandQueue;
import com.android.systemui.statusbar.CrossFadeHelper;
import com.android.systemui.statusbar.HeadsUpStatusBarView;
+import com.android.systemui.statusbar.NotificationLockscreenUserManager;
import com.android.systemui.statusbar.StatusBarState;
import com.android.systemui.statusbar.notification.NotificationWakeUpCoordinator;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
@@ -40,8 +41,8 @@ import com.android.systemui.statusbar.policy.KeyguardStateController;
import com.android.systemui.statusbar.policy.OnHeadsUpChangedListener;
import com.android.systemui.util.ViewController;
-import java.util.Optional;
import java.util.ArrayList;
+import java.util.Optional;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
@@ -61,17 +62,17 @@ public class HeadsUpAppearanceController extends ViewController<HeadsUpStatusBar
private final NotificationIconAreaController mNotificationIconAreaController;
private final HeadsUpManagerPhone mHeadsUpManager;
private final NotificationStackScrollLayoutController mStackScrollerController;
-
private final DarkIconDispatcher mDarkIconDispatcher;
private final NotificationPanelViewController mNotificationPanelViewController;
- private final Consumer<ExpandableNotificationRow>
- mSetTrackingHeadsUp = this::setTrackingHeadsUp;
+ private final Consumer<ExpandableNotificationRow> mSetTrackingHeadsUp =
+ this::setTrackingHeadsUp;
private final BiConsumer<Float, Float> mSetExpandedHeight = this::setAppearFraction;
private final KeyguardBypassController mBypassController;
private final StatusBarStateController mStatusBarStateController;
private final CommandQueue mCommandQueue;
private final NotificationWakeUpCoordinator mWakeUpCoordinator;
-
+ private final NotificationLockscreenUserManager mNotifLockscreenUserManager;
+ private final Runnable mRedactionChanged = this::updateRedaction;
private final View mClockView;
private final Optional<View> mOperatorNameViewOptional;
@@ -90,6 +91,13 @@ public class HeadsUpAppearanceController extends ViewController<HeadsUpStatusBar
};
private boolean mAnimationsEnabled = true;
private final KeyguardStateController mKeyguardStateController;
+ private final StatusBarStateController.StateListener mStatusBarStateListener =
+ new StatusBarStateController.StateListener() {
+ @Override
+ public void onStatePostChange() {
+ updateRedaction();
+ }
+ };
@VisibleForTesting
@Inject
@@ -98,6 +106,7 @@ public class HeadsUpAppearanceController extends ViewController<HeadsUpStatusBar
HeadsUpManagerPhone headsUpManager,
StatusBarStateController stateController,
KeyguardBypassController bypassController,
+ NotificationLockscreenUserManager notifLockscreenUserManager,
NotificationWakeUpCoordinator wakeUpCoordinator,
DarkIconDispatcher darkIconDispatcher,
KeyguardStateController keyguardStateController,
@@ -125,6 +134,7 @@ public class HeadsUpAppearanceController extends ViewController<HeadsUpStatusBar
mClockView = clockView;
mOperatorNameViewOptional = operatorNameViewOptional;
mDarkIconDispatcher = darkIconDispatcher;
+ mNotifLockscreenUserManager = notifLockscreenUserManager;
mView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
@Override
@@ -156,6 +166,8 @@ public class HeadsUpAppearanceController extends ViewController<HeadsUpStatusBar
mNotificationPanelViewController.setHeadsUpAppearanceController(this);
mStackScrollerController.addOnExpandedHeightChangedListener(mSetExpandedHeight);
mDarkIconDispatcher.addDarkReceiver(this);
+ mNotifLockscreenUserManager.addOnNeedsRedactionInPublicChangedListener(mRedactionChanged);
+ mStatusBarStateController.addCallback(mStatusBarStateListener);
}
@Override
@@ -167,6 +179,9 @@ public class HeadsUpAppearanceController extends ViewController<HeadsUpStatusBar
mNotificationPanelViewController.setHeadsUpAppearanceController(null);
mStackScrollerController.removeOnExpandedHeightChangedListener(mSetExpandedHeight);
mDarkIconDispatcher.removeDarkReceiver(this);
+ mNotifLockscreenUserManager
+ .removeOnNeedsRedactionInPublicChangedListener(mRedactionChanged);
+ mStatusBarStateController.removeCallback(mStatusBarStateListener);
}
private void updateIsolatedIconLocation(boolean requireStateUpdate) {
@@ -180,6 +195,19 @@ public class HeadsUpAppearanceController extends ViewController<HeadsUpStatusBar
updateHeader(entry);
}
+ private void updateRedaction() {
+ NotificationEntry showingEntry = mView.getShowingEntry();
+ if (showingEntry == null) {
+ return;
+ }
+ int notifUserId = showingEntry.getSbn().getUserId();
+ boolean redactSensitiveContent =
+ mNotifLockscreenUserManager.isLockscreenPublicMode(notifUserId)
+ && mNotifLockscreenUserManager
+ .sensitiveNotifsNeedRedactionInPublic(notifUserId);
+ mView.setRedactSensitiveContent(redactSensitiveContent);
+ }
+
private void updateTopEntry() {
NotificationEntry newEntry = null;
if (shouldBeVisible()) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBottomAreaView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBottomAreaView.java
index 347e05cc7f75..fd307df8d304 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBottomAreaView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBottomAreaView.java
@@ -1198,15 +1198,19 @@ public class KeyguardBottomAreaView extends FrameLayout implements View.OnClickL
if (tileIcon != null) {
mWalletButton.setImageDrawable(tileIcon);
}
- updateWalletVisibility();
- updateAffordanceColors();
+ post(() -> {
+ updateWalletVisibility();
+ updateAffordanceColors();
+ });
}
@Override
public void onWalletCardRetrievalError(@NonNull GetWalletCardsError error) {
mHasCard = false;
- updateWalletVisibility();
- updateAffordanceColors();
+ post(() -> {
+ updateWalletVisibility();
+ updateAffordanceColors();
+ });
}
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBouncer.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBouncer.java
index 0b721383e2d1..8792118fb9ef 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBouncer.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBouncer.java
@@ -188,6 +188,10 @@ public class KeyguardBouncer {
}
if (mContainer.getVisibility() == View.VISIBLE || mShowingSoon) {
+ // Calls to reset must resume the ViewControllers when in fullscreen mode
+ if (needsFullscreenBouncer()) {
+ mKeyguardViewController.onResume();
+ }
return;
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NPVCDownEventState.kt b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NPVCDownEventState.kt
index 06235071734e..d44a56942065 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NPVCDownEventState.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NPVCDownEventState.kt
@@ -14,9 +14,9 @@
package com.android.systemui.statusbar.phone
import android.view.MotionEvent
-import com.android.internal.util.RingBuffer
import com.android.systemui.dump.DumpsysTableLogger
import com.android.systemui.dump.Row
+import com.android.systemui.util.collection.RingBuffer
import java.text.SimpleDateFormat
import java.util.Locale
@@ -67,16 +67,9 @@ class NPVCDownEventState private constructor(
* Do not use [append] to add new elements. Instead use [insert], as it will recycle if
* necessary.
*/
- class Buffer(
- capacity: Int
- ) : RingBuffer<NPVCDownEventState>(NPVCDownEventState::class.java, capacity) {
- override fun append(t: NPVCDownEventState?) {
- throw UnsupportedOperationException("Not supported, use insert instead")
- }
+ class Buffer(capacity: Int) {
- override fun createNewItem(): NPVCDownEventState {
- return NPVCDownEventState()
- }
+ private val buffer = RingBuffer(capacity) { NPVCDownEventState() }
/**
* Insert a new element in the buffer.
@@ -94,7 +87,7 @@ class NPVCDownEventState private constructor(
touchSlopExceededBeforeDown: Boolean,
lastEventSynthesized: Boolean
) {
- nextSlot.apply {
+ buffer.advance().apply {
this.timeStamp = timeStamp
this.x = x
this.y = y
@@ -115,7 +108,7 @@ class NPVCDownEventState private constructor(
* @see NPVCDownEventState.asStringList
*/
fun toList(): List<Row> {
- return toArray().map { it.asStringList }
+ return buffer.asSequence().map { it.asStringList }.toList()
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotifActivityLaunchEvents.kt b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotifActivityLaunchEvents.kt
deleted file mode 100644
index f46d07338206..000000000000
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotifActivityLaunchEvents.kt
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (C) 2022 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.systemui.statusbar.phone
-
-import com.android.systemui.statusbar.notification.collection.NotificationEntry
-
-/** Provides events about [android.app.Activity] launches from Notifications. */
-interface NotifActivityLaunchEvents {
-
- /** Registers a [Listener] to be invoked when notification activity launch events occur. */
- fun registerListener(listener: Listener)
-
- /** Unregisters a [Listener] previously registered via [registerListener] */
- fun unregisterListener(listener: Listener)
-
- /** Listener for events about [android.app.Activity] launches from Notifications. */
- interface Listener {
-
- /** Invoked when an activity has started launching from a notification. */
- fun onStartLaunchNotifActivity(entry: NotificationEntry)
-
- /** Invoked when an activity has finished launching. */
- fun onFinishLaunchNotifActivity(entry: NotificationEntry)
- }
-}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelViewController.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelViewController.java
index ec13b1f835e8..314ab2221b19 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelViewController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelViewController.java
@@ -32,7 +32,6 @@ import static com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_N
import static com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_QUICK_SETTINGS_EXPANDED;
import static com.android.systemui.statusbar.StatusBarState.KEYGUARD;
import static com.android.systemui.statusbar.StatusBarState.SHADE;
-import static com.android.systemui.statusbar.notification.stack.NotificationStackScrollLayout.ROWS_ALL;
import static com.android.systemui.statusbar.notification.stack.StackStateAnimator.ANIMATION_DURATION_FOLD_TO_AOD;
import static com.android.systemui.statusbar.phone.panelstate.PanelExpansionStateManagerKt.STATE_CLOSED;
import static com.android.systemui.statusbar.phone.panelstate.PanelExpansionStateManagerKt.STATE_OPEN;
@@ -1693,9 +1692,11 @@ public class NotificationPanelViewController extends PanelViewController {
if (mShouldUseSplitNotificationShade && isOnKeyguard()) {
// It's a special case as this method is likely to not be initiated by finger movement
// but rather called from adb shell or accessibility service.
- // In the future method below could be used for non-split shade as well but currently
- // motion in that case looks worse than using flingSettings.
- // TODO: make below function transitioning smoothly also in portrait with empty target
+ // We're using LockscreenShadeTransitionController because on lockscreen that's the
+ // source of truth for all shade motion. Not using it would make part of state to be
+ // outdated and will cause bugs. Ideally we'd use this controller also for non-split
+ // case but currently motion in portrait looks worse than when using flingSettings.
+ // TODO: make below function transitioning smoothly also in portrait with null target
mLockscreenShadeTransitionController.goToLockedShade(
/* expandedView= */null, /* needsQSAnimation= */false);
} else if (isFullyCollapsed()) {
@@ -2363,9 +2364,12 @@ public class NotificationPanelViewController extends PanelViewController {
mScrimController.setQsPosition(qsExpansionFraction, qsPanelBottomY);
setQSClippingBounds();
- // Only need to notify the notification stack when we're not in split screen mode. If we
- // do, then the notification panel starts scrolling along with the QS.
- if (!mShouldUseSplitNotificationShade) {
+ if (mShouldUseSplitNotificationShade) {
+ // In split shade we want to pretend that QS are always collapsed so their behaviour and
+ // interactions don't influence notifications as they do in portrait. But we want to set
+ // 0 explicitly in case we're rotating from non-split shade with QS expansion of 1.
+ mNotificationStackScrollLayoutController.setQsExpansionFraction(0);
+ } else {
mNotificationStackScrollLayoutController.setQsExpansionFraction(qsExpansionFraction);
}
@@ -3373,9 +3377,9 @@ public class NotificationPanelViewController extends PanelViewController {
@Override
public void setIsLaunchAnimationRunning(boolean running) {
- boolean wasRunning = isLaunchTransitionRunning();
+ boolean wasRunning = mIsLaunchAnimationRunning;
super.setIsLaunchAnimationRunning(running);
- if (wasRunning != isLaunchTransitionRunning()) {
+ if (wasRunning != mIsLaunchAnimationRunning) {
mPanelEventsEmitter.notifyLaunchingActivityChanged(running);
}
}
@@ -3939,10 +3943,6 @@ public class NotificationPanelViewController extends PanelViewController {
}
}
- public boolean hasActiveClearableNotifications() {
- return mNotificationStackScrollLayoutController.hasActiveClearableNotifications(ROWS_ALL);
- }
-
public RemoteInputController.Delegate createRemoteInputDelegate() {
return mNotificationStackScrollLayoutController.createDelegate();
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimController.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimController.java
index f9e17da9773f..0e77866bef1d 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimController.java
@@ -402,6 +402,8 @@ public class ScrimController implements ViewTreeObserver.OnPreDrawListener, Dump
mScrimBehind.setFocusable(!state.isLowPowerState());
mNotificationsScrim.setFocusable(!state.isLowPowerState());
+ mScrimInFront.setBlendWithMainColor(state.shouldBlendWithMainColor());
+
// Cancel blanking transitions that were pending before we requested a new state
if (mPendingFrameCallback != null) {
mScrimBehind.removeCallbacks(mPendingFrameCallback);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimState.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimState.java
index 47b705845fce..4a5f712d587c 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimState.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimState.java
@@ -203,6 +203,11 @@ public enum ScrimState {
public boolean isLowPowerState() {
return true;
}
+
+ @Override
+ public boolean shouldBlendWithMainColor() {
+ return false;
+ }
},
/**
@@ -325,6 +330,13 @@ public enum ScrimState {
public void prepare(ScrimState previousState) {
}
+ /**
+ * Whether a particular state should enable blending with extracted theme colors.
+ */
+ public boolean shouldBlendWithMainColor() {
+ return true;
+ }
+
public float getFrontAlpha() {
return mFrontAlpha;
}
@@ -422,4 +434,4 @@ public enum ScrimState {
public void setClipQsScrim(boolean clipsQsScrim) {
mClipQsScrim = clipsQsScrim;
}
-} \ No newline at end of file
+}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarLaunchAnimatorController.kt b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarLaunchAnimatorController.kt
index 56b6dfc42ee3..c0922163903f 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarLaunchAnimatorController.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarLaunchAnimatorController.kt
@@ -20,7 +20,9 @@ class StatusBarLaunchAnimatorController(
override fun onIntentStarted(willAnimate: Boolean) {
delegate.onIntentStarted(willAnimate)
- if (!willAnimate) {
+ if (willAnimate) {
+ centralSurfaces.notificationPanelViewController.setIsLaunchAnimationRunning(true)
+ } else {
centralSurfaces.collapsePanelOnMainThread()
}
}
@@ -51,6 +53,7 @@ class StatusBarLaunchAnimatorController(
override fun onLaunchAnimationCancelled() {
delegate.onLaunchAnimationCancelled()
+ centralSurfaces.notificationPanelViewController.setIsLaunchAnimationRunning(false)
centralSurfaces.onLaunchAnimationCancelled(isLaunchForActivity)
}
} \ No newline at end of file
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarter.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarter.java
index 87ca942edff2..cf776e3b60d1 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarter.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarter.java
@@ -41,7 +41,6 @@ import android.text.TextUtils;
import android.util.EventLog;
import android.view.View;
-import androidx.annotation.NonNull;
import androidx.annotation.VisibleForTesting;
import com.android.internal.jank.InteractionJankMonitor;
@@ -52,7 +51,6 @@ import com.android.systemui.ActivityIntentHelper;
import com.android.systemui.EventLogTags;
import com.android.systemui.animation.ActivityLaunchAnimator;
import com.android.systemui.assist.AssistManager;
-import com.android.systemui.dagger.SysUISingleton;
import com.android.systemui.plugins.ActivityStarter;
import com.android.systemui.plugins.statusbar.StatusBarStateController;
import com.android.systemui.statusbar.CommandQueue;
@@ -77,7 +75,6 @@ import com.android.systemui.statusbar.notification.row.OnUserInteractionCallback
import com.android.systemui.statusbar.phone.dagger.CentralSurfacesComponent;
import com.android.systemui.statusbar.policy.HeadsUpUtil;
import com.android.systemui.statusbar.policy.KeyguardStateController;
-import com.android.systemui.util.ListenerSet;
import com.android.systemui.wmshell.BubblesManager;
import java.util.Optional;
@@ -131,7 +128,6 @@ class StatusBarNotificationActivityStarter implements NotificationActivityStarte
private final ActivityLaunchAnimator mActivityLaunchAnimator;
private final NotificationLaunchAnimatorControllerProvider mNotificationAnimationProvider;
private final OnUserInteractionCallback mOnUserInteractionCallback;
- private final LaunchEventsEmitter mLaunchEventsEmitter;
private boolean mIsCollapsingToShowActivityOverLockscreen;
@@ -170,8 +166,7 @@ class StatusBarNotificationActivityStarter implements NotificationActivityStarte
NotificationPresenter presenter,
NotificationPanelViewController panel,
ActivityLaunchAnimator activityLaunchAnimator,
- NotificationLaunchAnimatorControllerProvider notificationAnimationProvider,
- LaunchEventsEmitter launchEventsEmitter) {
+ NotificationLaunchAnimatorControllerProvider notificationAnimationProvider) {
mContext = context;
mCommandQueue = commandQueue;
mMainThreadHandler = mainThreadHandler;
@@ -207,7 +202,6 @@ class StatusBarNotificationActivityStarter implements NotificationActivityStarte
mNotificationPanel = panel;
mActivityLaunchAnimator = activityLaunchAnimator;
mNotificationAnimationProvider = notificationAnimationProvider;
- mLaunchEventsEmitter = launchEventsEmitter;
if (!mNotifPipelineFlags.isNewPipelineEnabled()) {
mEntryManager.addNotificationEntryListener(new NotificationEntryListener() {
@@ -229,14 +223,13 @@ class StatusBarNotificationActivityStarter implements NotificationActivityStarte
/**
* Called when a notification is clicked.
*
- * @param sbn notification that was clicked
+ * @param entry notification that was clicked
* @param row row for that notification
*/
@Override
- public void onNotificationClicked(StatusBarNotification sbn, ExpandableNotificationRow row) {
- mLogger.logStartingActivityFromClick(sbn.getKey());
+ public void onNotificationClicked(NotificationEntry entry, ExpandableNotificationRow row) {
+ mLogger.logStartingActivityFromClick(entry);
- final NotificationEntry entry = row.getEntry();
if (mRemoteInputManager.isRemoteInputActive(entry)
&& !TextUtils.isEmpty(row.getActiveRemoteInputText())) {
// We have an active remote input typed and the user clicked on the notification.
@@ -244,7 +237,7 @@ class StatusBarNotificationActivityStarter implements NotificationActivityStarte
mRemoteInputManager.closeRemoteInputs();
return;
}
- Notification notification = sbn.getNotification();
+ Notification notification = entry.getSbn().getNotification();
final PendingIntent intent = notification.contentIntent != null
? notification.contentIntent
: notification.fullScreenIntent;
@@ -254,12 +247,10 @@ class StatusBarNotificationActivityStarter implements NotificationActivityStarte
// The only valid case is Bubble notifications. Guard against other cases
// entering here.
if (intent == null && !isBubble) {
- mLogger.logNonClickableNotification(sbn.getKey());
+ mLogger.logNonClickableNotification(entry);
return;
}
- mLaunchEventsEmitter.notifyStartLaunchNotifActivity(entry);
-
boolean isActivityIntent = intent != null && intent.isActivity() && !isBubble;
final boolean willLaunchResolverActivity = isActivityIntent
&& mActivityIntentHelper.wouldLaunchResolverActivity(intent.getIntent(),
@@ -287,7 +278,7 @@ class StatusBarNotificationActivityStarter implements NotificationActivityStarte
} else {
mActivityStarter.dismissKeyguardThenExecute(
postKeyguardAction,
- () -> mLaunchEventsEmitter.notifyFinishLaunchNotifActivity(entry),
+ null,
willLaunchResolverActivity);
}
}
@@ -299,7 +290,7 @@ class StatusBarNotificationActivityStarter implements NotificationActivityStarte
boolean isActivityIntent,
boolean animate,
boolean showOverLockscreen) {
- mLogger.logHandleClickAfterKeyguardDismissed(entry.getKey());
+ mLogger.logHandleClickAfterKeyguardDismissed(entry);
final Runnable runnable = () -> handleNotificationClickAfterPanelCollapsed(
entry, row, intent, isActivityIntent, animate);
@@ -326,7 +317,7 @@ class StatusBarNotificationActivityStarter implements NotificationActivityStarte
boolean isActivityIntent,
boolean animate) {
String notificationKey = entry.getKey();
- mLogger.logHandleClickAfterPanelCollapsed(notificationKey);
+ mLogger.logHandleClickAfterPanelCollapsed(entry);
try {
// The intent we are sending is for the application, which
@@ -367,11 +358,9 @@ class StatusBarNotificationActivityStarter implements NotificationActivityStarte
}
final boolean canBubble = entry.canBubble();
if (canBubble) {
- mLogger.logExpandingBubble(notificationKey);
+ mLogger.logExpandingBubble(entry);
removeHunAfterClick(row);
expandBubbleStackOnMainThread(entry);
- mMainThreadHandler.post(
- () -> mLaunchEventsEmitter.notifyFinishLaunchNotifActivity(entry));
} else {
startNotificationIntent(intent, fillInIntent, entry, row, animate, isActivityIntent);
}
@@ -381,30 +370,13 @@ class StatusBarNotificationActivityStarter implements NotificationActivityStarte
final NotificationVisibility nv = mVisibilityProvider.obtain(entry, true);
- // retrieve the group summary to remove with this entry before we tell NMS the
- // notification was clicked to avoid a race condition
- final boolean shouldAutoCancel = shouldAutoCancel(entry.getSbn());
- final NotificationEntry summaryToRemove = shouldAutoCancel
- ? mOnUserInteractionCallback.getGroupSummaryToDismiss(entry) : null;
-
- // inform NMS that the notification was clicked
- mClickNotifier.onNotificationClick(notificationKey, nv);
-
- if (!canBubble && (shouldAutoCancel
+ if (!canBubble && (shouldAutoCancel(entry.getSbn())
|| mRemoteInputManager.isNotificationKeptForRemoteInputHistory(notificationKey))) {
+ final Runnable removeNotification =
+ mOnUserInteractionCallback.registerFutureDismissal(entry, REASON_CLICK);
// Immediately remove notification from visually showing.
// We have to post the removal to the UI thread for synchronization.
mMainThreadHandler.post(() -> {
- final Runnable removeNotification = () -> {
- mOnUserInteractionCallback.onDismiss(entry, REASON_CLICK, summaryToRemove);
- if (!animate) {
- // If we're animating, this would be invoked after the activity launch
- // animation completes. Since we're not animating, the launch already
- // happened synchronously, so we notify the launch is complete here after
- // onDismiss.
- mLaunchEventsEmitter.notifyFinishLaunchNotifActivity(entry);
- }
- };
if (mPresenter.isCollapsing()) {
// To avoid lags we're only performing the remove after the shade is collapsed
mShadeController.addPostCollapseAction(removeNotification);
@@ -412,12 +384,11 @@ class StatusBarNotificationActivityStarter implements NotificationActivityStarte
removeNotification.run();
}
});
- } else if (!canBubble && !animate) {
- // Not animating, this is the end of the launch flow (see above comment for more info).
- mMainThreadHandler.post(
- () -> mLaunchEventsEmitter.notifyFinishLaunchNotifActivity(entry));
}
+ // inform NMS that the notification was clicked
+ mClickNotifier.onNotificationClick(notificationKey, nv);
+
mIsCollapsingToShowActivityOverLockscreen = false;
}
@@ -434,24 +405,14 @@ class StatusBarNotificationActivityStarter implements NotificationActivityStarte
// will focus follow operation only after drag-and-drop that notification.
final NotificationVisibility nv = mVisibilityProvider.obtain(entry, true);
- // retrieve the group summary to remove with this entry before we tell NMS the
- // notification was clicked to avoid a race condition
- final boolean shouldAutoCancel = shouldAutoCancel(entry.getSbn());
- final NotificationEntry summaryToRemove = shouldAutoCancel
- ? mOnUserInteractionCallback.getGroupSummaryToDismiss(entry) : null;
-
String notificationKey = entry.getKey();
- // inform NMS that the notification was clicked
- mClickNotifier.onNotificationClick(notificationKey, nv);
-
- if (shouldAutoCancel || mRemoteInputManager.isNotificationKeptForRemoteInputHistory(
- notificationKey)) {
+ if (shouldAutoCancel(entry.getSbn())
+ || mRemoteInputManager.isNotificationKeptForRemoteInputHistory(notificationKey)) {
+ final Runnable removeNotification =
+ mOnUserInteractionCallback.registerFutureDismissal(entry, REASON_CLICK);
// Immediately remove notification from visually showing.
// We have to post the removal to the UI thread for synchronization.
mMainThreadHandler.post(() -> {
- final Runnable removeNotification = () ->
- mOnUserInteractionCallback.onDismiss(
- entry, REASON_CLICK, summaryToRemove);
if (mPresenter.isCollapsing()) {
// To avoid lags we're only performing the remove
// after the shade is collapsed
@@ -462,6 +423,9 @@ class StatusBarNotificationActivityStarter implements NotificationActivityStarte
});
}
+ // inform NMS that the notification was clicked
+ mClickNotifier.onNotificationClick(notificationKey, nv);
+
mIsCollapsingToShowActivityOverLockscreen = false;
}
@@ -489,15 +453,11 @@ class StatusBarNotificationActivityStarter implements NotificationActivityStarte
ExpandableNotificationRow row,
boolean animate,
boolean isActivityIntent) {
- mLogger.logStartNotificationIntent(entry.getKey());
+ mLogger.logStartNotificationIntent(entry);
try {
- Runnable onFinishAnimationCallback = animate
- ? () -> mLaunchEventsEmitter.notifyFinishLaunchNotifActivity(entry)
- : null;
ActivityLaunchAnimator.Controller animationController =
new StatusBarLaunchAnimatorController(
- mNotificationAnimationProvider
- .getAnimatorController(row, onFinishAnimationCallback),
+ mNotificationAnimationProvider.getAnimatorController(row, null),
mCentralSurfaces,
isActivityIntent);
mActivityLaunchAnimator.startPendingIntentWithAnimation(
@@ -515,7 +475,7 @@ class StatusBarNotificationActivityStarter implements NotificationActivityStarte
: getActivityOptions(mCentralSurfaces.getDisplayId(), adapter);
int result = intent.sendAndReturnResult(mContext, 0, fillInIntent, null,
null, null, options);
- mLogger.logSendPendingIntent(entry.getKey(), intent, result);
+ mLogger.logSendPendingIntent(entry, intent, result);
return result;
});
} catch (PendingIntent.CanceledException e) {
@@ -622,9 +582,9 @@ class StatusBarNotificationActivityStarter implements NotificationActivityStarte
void handleFullScreenIntent(NotificationEntry entry) {
if (mNotificationInterruptStateProvider.shouldLaunchFullScreenIntentWhenAdded(entry)) {
if (shouldSuppressFullScreenIntent(entry)) {
- mLogger.logFullScreenIntentSuppressedByDnD(entry.getKey());
+ mLogger.logFullScreenIntentSuppressedByDnD(entry);
} else if (entry.getImportance() < NotificationManager.IMPORTANCE_HIGH) {
- mLogger.logFullScreenIntentNotImportantEnough(entry.getKey());
+ mLogger.logFullScreenIntentNotImportantEnough(entry);
} else {
// Stop screensaver if the notification has a fullscreen intent.
// (like an incoming phone call)
@@ -639,7 +599,7 @@ class StatusBarNotificationActivityStarter implements NotificationActivityStarte
// not immersive & a fullscreen alert should be shown
final PendingIntent fullscreenIntent =
entry.getSbn().getNotification().fullScreenIntent;
- mLogger.logSendingFullScreenIntent(entry.getKey(), fullscreenIntent);
+ mLogger.logSendingFullScreenIntent(entry, fullscreenIntent);
try {
EventLog.writeEvent(EventLogTags.SYSUI_FULLSCREEN_NOTIFICATION,
entry.getKey());
@@ -685,35 +645,4 @@ class StatusBarNotificationActivityStarter implements NotificationActivityStarte
return entry.shouldSuppressFullScreenIntent();
}
-
- @SysUISingleton
- static class LaunchEventsEmitter implements NotifActivityLaunchEvents {
-
- private final ListenerSet<Listener> mListeners = new ListenerSet<>();
-
- @Inject
- LaunchEventsEmitter() {}
-
- @Override
- public void registerListener(@NonNull Listener listener) {
- mListeners.addIfAbsent(listener);
- }
-
- @Override
- public void unregisterListener(@NonNull Listener listener) {
- mListeners.remove(listener);
- }
-
- private void notifyStartLaunchNotifActivity(NotificationEntry entry) {
- for (Listener listener : mListeners) {
- listener.onStartLaunchNotifActivity(entry);
- }
- }
-
- private void notifyFinishLaunchNotifActivity(NotificationEntry entry) {
- for (Listener listener : mListeners) {
- listener.onFinishLaunchNotifActivity(entry);
- }
- }
- }
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarterLogger.kt b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarterLogger.kt
index 2fbe520a4b61..b9a1413ff791 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarterLogger.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarterLogger.kt
@@ -23,46 +23,48 @@ import com.android.systemui.log.LogLevel.ERROR
import com.android.systemui.log.LogLevel.INFO
import com.android.systemui.log.LogLevel.WARNING
import com.android.systemui.log.dagger.NotifInteractionLog
+import com.android.systemui.statusbar.notification.collection.NotificationEntry
+import com.android.systemui.statusbar.notification.logKey
import javax.inject.Inject
class StatusBarNotificationActivityStarterLogger @Inject constructor(
@NotifInteractionLog private val buffer: LogBuffer
) {
- fun logStartingActivityFromClick(key: String) {
+ fun logStartingActivityFromClick(entry: NotificationEntry) {
buffer.log(TAG, DEBUG, {
- str1 = key
+ str1 = entry.logKey
}, {
"(1/5) onNotificationClicked: $str1"
})
}
- fun logHandleClickAfterKeyguardDismissed(key: String) {
+ fun logHandleClickAfterKeyguardDismissed(entry: NotificationEntry) {
buffer.log(TAG, DEBUG, {
- str1 = key
+ str1 = entry.logKey
}, {
"(2/5) handleNotificationClickAfterKeyguardDismissed: $str1"
})
}
- fun logHandleClickAfterPanelCollapsed(key: String) {
+ fun logHandleClickAfterPanelCollapsed(entry: NotificationEntry) {
buffer.log(TAG, DEBUG, {
- str1 = key
+ str1 = entry.logKey
}, {
"(3/5) handleNotificationClickAfterPanelCollapsed: $str1"
})
}
- fun logStartNotificationIntent(key: String) {
+ fun logStartNotificationIntent(entry: NotificationEntry) {
buffer.log(TAG, INFO, {
- str1 = key
+ str1 = entry.logKey
}, {
"(4/5) startNotificationIntent: $str1"
})
}
- fun logSendPendingIntent(key: String, pendingIntent: PendingIntent, result: Int) {
+ fun logSendPendingIntent(entry: NotificationEntry, pendingIntent: PendingIntent, result: Int) {
buffer.log(TAG, INFO, {
- str1 = key
+ str1 = entry.logKey
str2 = pendingIntent.intent.toString()
int1 = result
}, {
@@ -70,9 +72,9 @@ class StatusBarNotificationActivityStarterLogger @Inject constructor(
})
}
- fun logExpandingBubble(key: String) {
+ fun logExpandingBubble(entry: NotificationEntry) {
buffer.log(TAG, DEBUG, {
- str1 = key
+ str1 = entry.logKey
}, {
"Expanding bubble for $str1 (rather than firing intent)"
})
@@ -86,33 +88,33 @@ class StatusBarNotificationActivityStarterLogger @Inject constructor(
})
}
- fun logNonClickableNotification(key: String) {
+ fun logNonClickableNotification(entry: NotificationEntry) {
buffer.log(TAG, ERROR, {
- str1 = key
+ str1 = entry.logKey
}, {
"onNotificationClicked called for non-clickable notification! $str1"
})
}
- fun logFullScreenIntentSuppressedByDnD(key: String) {
+ fun logFullScreenIntentSuppressedByDnD(entry: NotificationEntry) {
buffer.log(TAG, DEBUG, {
- str1 = key
+ str1 = entry.logKey
}, {
"No Fullscreen intent: suppressed by DND: $str1"
})
}
- fun logFullScreenIntentNotImportantEnough(key: String) {
+ fun logFullScreenIntentNotImportantEnough(entry: NotificationEntry) {
buffer.log(TAG, DEBUG, {
- str1 = key
+ str1 = entry.logKey
}, {
"No Fullscreen intent: not important enough: $str1"
})
}
- fun logSendingFullScreenIntent(key: String, pendingIntent: PendingIntent) {
+ fun logSendingFullScreenIntent(entry: NotificationEntry, pendingIntent: PendingIntent) {
buffer.log(TAG, INFO, {
- str1 = key
+ str1 = entry.logKey
str2 = pendingIntent.intent.toString()
}, {
"Notification $str1 has fullScreenIntent; sending fullScreenIntent $str2"
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationPresenter.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationPresenter.java
index aa061d74f6c6..037063f4f7b0 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationPresenter.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationPresenter.java
@@ -411,8 +411,8 @@ class StatusBarNotificationPresenter implements NotificationPresenter,
if (nowExpanded) {
if (mStatusBarStateController.getState() == StatusBarState.KEYGUARD) {
mShadeTransitionController.goToLockedShade(clickedEntry.getRow());
- } else if (clickedEntry.isSensitive()
- && mDynamicPrivacyController.isInLockedDownShade()) {
+ } else if (mDynamicPrivacyController.isInLockedDownShade()
+ && mLockscreenUserManager.notifNeedsRedactionInPublic(clickedEntry)) {
mStatusBarStateController.setLeaveOpenOnKeyguardHide(true);
mActivityStarter.dismissKeyguardThenExecute(() -> false /* dismissAction */
, null /* cancelRunnable */, false /* afterKeyguardGone */);
@@ -480,7 +480,7 @@ class StatusBarNotificationPresenter implements NotificationPresenter,
.isLockscreenPublicMode(mLockscreenUserManager.getCurrentUserId());
boolean userPublic = devicePublic
|| mLockscreenUserManager.isLockscreenPublicMode(sbn.getUserId());
- boolean needsRedaction = mLockscreenUserManager.needsRedaction(entry);
+ boolean needsRedaction = mLockscreenUserManager.notifNeedsRedactionInPublic(entry);
if (userPublic && needsRedaction) {
// TODO(b/135046837): we can probably relax this with dynamic privacy
return true;
diff --git a/packages/SystemUI/src/com/android/systemui/theme/ThemeOverlayController.java b/packages/SystemUI/src/com/android/systemui/theme/ThemeOverlayController.java
index 7920d388c670..c6a8445d2443 100644
--- a/packages/SystemUI/src/com/android/systemui/theme/ThemeOverlayController.java
+++ b/packages/SystemUI/src/com/android/systemui/theme/ThemeOverlayController.java
@@ -78,6 +78,7 @@ import org.json.JSONException;
import org.json.JSONObject;
import java.io.PrintWriter;
+import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
@@ -639,6 +640,11 @@ public class ThemeOverlayController extends CoreStartable implements Dumpable {
}
private Style fetchThemeStyleFromSetting() {
+ // Allow-list of Style objects that can be created from a setting string, i.e. can be
+ // used as a system-wide theme.
+ // - Content intentionally excluded, intended for media player, not system-wide
+ List<Style> validStyles = Arrays.asList(Style.EXPRESSIVE, Style.SPRITZ, Style.TONAL_SPOT,
+ Style.FRUIT_SALAD, Style.RAINBOW, Style.VIBRANT);
Style style = mThemeStyle;
final String overlayPackageJson = mSecureSettings.getStringForUser(
Settings.Secure.THEME_CUSTOMIZATION_OVERLAY_PACKAGES,
@@ -648,6 +654,9 @@ public class ThemeOverlayController extends CoreStartable implements Dumpable {
JSONObject object = new JSONObject(overlayPackageJson);
style = Style.valueOf(
object.getString(ThemeOverlayApplier.OVERLAY_CATEGORY_THEME_STYLE));
+ if (!validStyles.contains(style)) {
+ style = Style.TONAL_SPOT;
+ }
} catch (JSONException | IllegalArgumentException e) {
Log.i(TAG, "Failed to parse THEME_CUSTOMIZATION_OVERLAY_PACKAGES.", e);
style = Style.TONAL_SPOT;
diff --git a/packages/SystemUI/src/com/android/systemui/tv/TvBottomSheetActivity.java b/packages/SystemUI/src/com/android/systemui/tv/TvBottomSheetActivity.java
index 2b7a33260248..90f24347d20d 100644
--- a/packages/SystemUI/src/com/android/systemui/tv/TvBottomSheetActivity.java
+++ b/packages/SystemUI/src/com/android/systemui/tv/TvBottomSheetActivity.java
@@ -18,15 +18,18 @@ package com.android.systemui.tv;
import android.app.Activity;
import android.graphics.PixelFormat;
+import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
+import android.view.View;
import android.view.WindowManager;
import com.android.systemui.R;
+import java.util.Collections;
import java.util.function.Consumer;
/**
@@ -75,6 +78,12 @@ public abstract class TvBottomSheetActivity extends Activity {
getWindow().setElevation(getWindow().getElevation() + 5);
getWindow().setBackgroundBlurRadius(getResources().getDimensionPixelSize(
R.dimen.bottom_sheet_background_blur_radius));
+
+ final View rootView = findViewById(R.id.bottom_sheet);
+ rootView.addOnLayoutChangeListener((view, l, t, r, b, oldL, oldT, oldR, oldB) -> {
+ rootView.setUnrestrictedPreferKeepClearRects(
+ Collections.singletonList(new Rect(0, 0, r - l, b - t)));
+ });
}
@Override
diff --git a/packages/SystemUI/src/com/android/systemui/unfold/UnfoldTransitionModule.kt b/packages/SystemUI/src/com/android/systemui/unfold/UnfoldTransitionModule.kt
index d2d2361d613d..eea6ac0e72e9 100644
--- a/packages/SystemUI/src/com/android/systemui/unfold/UnfoldTransitionModule.kt
+++ b/packages/SystemUI/src/com/android/systemui/unfold/UnfoldTransitionModule.kt
@@ -20,6 +20,7 @@ import android.content.Context
import android.view.IWindowManager
import com.android.systemui.keyguard.LifecycleScreenStatusProvider
import com.android.systemui.unfold.config.UnfoldTransitionConfig
+import com.android.systemui.unfold.system.SystemUnfoldSharedModule
import com.android.systemui.unfold.updates.FoldStateProvider
import com.android.systemui.unfold.updates.screen.ScreenStatusProvider
import com.android.systemui.unfold.util.NaturalRotationUnfoldProgressProvider
@@ -34,7 +35,7 @@ import java.util.Optional
import javax.inject.Named
import javax.inject.Singleton
-@Module(includes = [UnfoldSharedModule::class])
+@Module(includes = [UnfoldSharedModule::class, SystemUnfoldSharedModule::class])
class UnfoldTransitionModule {
@Provides @UnfoldTransitionATracePrefix fun tracingTagPrefix() = "systemui"
@@ -62,11 +63,6 @@ class UnfoldTransitionModule {
@Provides
@Singleton
- fun provideUnfoldTransitionConfig(context: Context): UnfoldTransitionConfig =
- createConfig(context)
-
- @Provides
- @Singleton
fun provideNaturalRotationProgressProvider(
context: Context,
windowManager: IWindowManager,
diff --git a/packages/SystemUI/src/com/android/systemui/util/NotificationChannels.java b/packages/SystemUI/src/com/android/systemui/util/NotificationChannels.java
index 76dfcb182e97..53da213eb38e 100644
--- a/packages/SystemUI/src/com/android/systemui/util/NotificationChannels.java
+++ b/packages/SystemUI/src/com/android/systemui/util/NotificationChannels.java
@@ -35,11 +35,15 @@ import javax.inject.Inject;
public class NotificationChannels extends CoreStartable {
public static String ALERTS = "ALR";
public static String SCREENSHOTS_HEADSUP = "SCN_HEADSUP";
- public static String GENERAL = "GEN";
+ // Deprecated. Please use or create a more specific channel that users will better understand
+ @Deprecated
+ static String GENERAL = "GEN";
public static String STORAGE = "DSK";
public static String BATTERY = "BAT";
public static String TVPIP = TvPipNotificationController.NOTIFICATION_CHANNEL; // "TVPIP"
public static String HINTS = "HNT";
+ public static String INSTANT = "INS";
+ public static String SETUP = "STP";
@Inject
public NotificationChannels(Context context) {
@@ -64,11 +68,17 @@ public class NotificationChannels extends CoreStartable {
context.getString(R.string.notification_channel_alerts),
NotificationManager.IMPORTANCE_HIGH);
- final NotificationChannel general = new NotificationChannel(
- GENERAL,
- context.getString(R.string.notification_channel_general),
+ final NotificationChannel instant = new NotificationChannel(
+ INSTANT,
+ context.getString(R.string.notification_channel_instant),
NotificationManager.IMPORTANCE_MIN);
+ final NotificationChannel setup = new NotificationChannel(
+ SETUP,
+ context.getString(R.string.notification_channel_setup),
+ NotificationManager.IMPORTANCE_DEFAULT);
+ setup.setSound(null, null);
+
final NotificationChannel storage = new NotificationChannel(
STORAGE,
context.getString(R.string.notification_channel_storage),
@@ -84,7 +94,8 @@ public class NotificationChannels extends CoreStartable {
nm.createNotificationChannels(Arrays.asList(
alerts,
- general,
+ instant,
+ setup,
storage,
createScreenshotChannel(
context.getString(R.string.notification_channel_screenshot)),
@@ -123,6 +134,11 @@ public class NotificationChannels extends CoreStartable {
@Override
public void start() {
createAll(mContext);
+ cleanUp();
+ }
+
+ private void cleanUp() {
+ mContext.getSystemService(NotificationManager.class).deleteNotificationChannel(GENERAL);
}
private static boolean isTv(Context context) {
diff --git a/packages/SystemUI/src/com/android/systemui/util/collection/RingBuffer.kt b/packages/SystemUI/src/com/android/systemui/util/collection/RingBuffer.kt
new file mode 100644
index 000000000000..97dc842ec699
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/util/collection/RingBuffer.kt
@@ -0,0 +1,122 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.util.collection
+
+import kotlin.math.max
+
+/**
+ * A simple ring buffer implementation
+ *
+ * Use [advance] to get the least recent item in the buffer (and then presumably fill it with
+ * appropriate data). This will cause it to become the most recent item.
+ *
+ * As the buffer is used, it will grow, allocating new instances of T using [factory] until it
+ * reaches [maxSize]. After this point, no new instances will be created. Instead, the "oldest"
+ * instances will be recycled from the back of the buffer and placed at the front.
+ *
+ * @param maxSize The maximum size the buffer can grow to before it begins functioning as a ring.
+ * @param factory A function that creates a fresh instance of T. Used by the buffer while it's
+ * growing to [maxSize].
+ */
+class RingBuffer<T>(
+ private val maxSize: Int,
+ private val factory: () -> T
+) : Iterable<T> {
+
+ private val buffer = MutableList<T?>(maxSize) { null }
+
+ /**
+ * An abstract representation that points to the "end" of the buffer. Increments every time
+ * [advance] is called and never wraps. Use [indexOf] to calculate the associated index into
+ * the backing array. Always points to the "next" available slot in the buffer. Before the
+ * buffer has completely filled, the value pointed to will be null. Afterward, it will be the
+ * value at the "beginning" of the buffer.
+ *
+ * This value is unlikely to overflow. Assuming [advance] is called at rate of 100 calls/ms,
+ * omega will overflow after a little under three million years of continuous operation.
+ */
+ private var omega: Long = 0
+
+ /**
+ * The number of items currently stored in the buffer. Calls to [advance] will cause this value
+ * to increase by one until it reaches [maxSize].
+ */
+ val size: Int
+ get() = if (omega < maxSize) omega.toInt() else maxSize
+
+ /**
+ * Advances the buffer's position by one and returns the value that is now present at the "end"
+ * of the buffer. If the buffer is not yet full, uses [factory] to create a new item.
+ * Otherwise, reuses the value that was previously at the "beginning" of the buffer.
+ *
+ * IMPORTANT: The value is returned as-is, without being reset. It will retain any data that
+ * was previously stored on it.
+ */
+ fun advance(): T {
+ val index = indexOf(omega)
+ omega += 1
+ val entry = buffer[index] ?: factory().also {
+ buffer[index] = it
+ }
+ return entry
+ }
+
+ /**
+ * Returns the value stored at [index], which can range from 0 (the "start", or oldest element
+ * of the buffer) to [size] - 1 (the "end", or newest element of the buffer).
+ */
+ operator fun get(index: Int): T {
+ if (index < 0 || index >= size) {
+ throw IndexOutOfBoundsException("Index $index is out of bounds")
+ }
+
+ // If omega is larger than the maxSize, then the buffer is full, and omega is equivalent
+ // to the "start" of the buffer. If omega is smaller than the maxSize, then the buffer is
+ // not yet full and our start should be 0. However, in modspace, maxSize and 0 are
+ // equivalent, so we can get away with using it as the start value instead.
+ val start = max(omega, maxSize.toLong())
+
+ return buffer[indexOf(start + index)]!!
+ }
+
+ inline fun forEach(action: (T) -> Unit) {
+ for (i in 0 until size) {
+ action(get(i))
+ }
+ }
+
+ override fun iterator(): Iterator<T> {
+ return object : Iterator<T> {
+ private var position: Int = 0
+
+ override fun next(): T {
+ if (position >= size) {
+ throw NoSuchElementException()
+ }
+ return get(position).also { position += 1 }
+ }
+
+ override fun hasNext(): Boolean {
+ return position < size
+ }
+ }
+ }
+
+ private fun indexOf(position: Long): Int {
+ return (position % maxSize).toInt()
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/volume/VolumeDialogImpl.java b/packages/SystemUI/src/com/android/systemui/volume/VolumeDialogImpl.java
index bfdcbd6deb48..cf0d0238b3cc 100644
--- a/packages/SystemUI/src/com/android/systemui/volume/VolumeDialogImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/volume/VolumeDialogImpl.java
@@ -32,6 +32,8 @@ import static android.view.View.LAYOUT_DIRECTION_RTL;
import static android.view.View.VISIBLE;
import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
+import static com.android.internal.jank.InteractionJankMonitor.CUJ_VOLUME_CONTROL;
+import static com.android.internal.jank.InteractionJankMonitor.Configuration.Builder;
import static com.android.systemui.volume.Events.DISMISS_REASON_SETTINGS_CLICKED;
import android.animation.Animator;
@@ -68,6 +70,7 @@ import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
+import android.os.Trace;
import android.os.VibrationEffect;
import android.provider.Settings;
import android.provider.Settings.Global;
@@ -101,9 +104,11 @@ import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
+import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.android.internal.graphics.drawable.BackgroundBlurDrawable;
+import com.android.internal.jank.InteractionJankMonitor;
import com.android.internal.view.RotationPolicy;
import com.android.settingslib.Utils;
import com.android.systemui.Prefs;
@@ -149,6 +154,13 @@ public class VolumeDialogImpl implements VolumeDialog,
private static final int DRAWER_ANIMATION_DURATION_SHORT = 175;
private static final int DRAWER_ANIMATION_DURATION = 250;
+ /** Shows volume dialog show animation. */
+ private static final String TYPE_SHOW = "show";
+ /** Dismiss volume dialog animation. */
+ private static final String TYPE_DISMISS = "dismiss";
+ /** Volume dialog slider animation. */
+ private static final String TYPE_UPDATE = "update";
+
private final int mDialogShowAnimationDurationMs;
private final int mDialogHideAnimationDurationMs;
private int mDialogWidth;
@@ -258,6 +270,7 @@ public class VolumeDialogImpl implements VolumeDialog,
private final boolean mUseBackgroundBlur;
private Consumer<Boolean> mCrossWindowBlurEnabledListener;
private BackgroundBlurDrawable mDialogRowsViewBackground;
+ private final InteractionJankMonitor mInteractionJankMonitor;
public VolumeDialogImpl(
Context context,
@@ -266,7 +279,8 @@ public class VolumeDialogImpl implements VolumeDialog,
DeviceProvisionedController deviceProvisionedController,
ConfigurationController configurationController,
MediaOutputDialogFactory mediaOutputDialogFactory,
- ActivityStarter activityStarter) {
+ ActivityStarter activityStarter,
+ InteractionJankMonitor interactionJankMonitor) {
mContext =
new ContextThemeWrapper(context, R.style.volume_dialog_theme);
mController = volumeDialogController;
@@ -290,6 +304,7 @@ public class VolumeDialogImpl implements VolumeDialog,
mContext.getResources().getInteger(R.integer.config_dialogHideAnimationDurationMs);
mUseBackgroundBlur =
mContext.getResources().getBoolean(R.bool.config_volumeDialogUseBackgroundBlur);
+ mInteractionJankMonitor = interactionJankMonitor;
if (mUseBackgroundBlur) {
final int dialogRowsViewColorAboveBlur = mContext.getColor(
@@ -422,6 +437,7 @@ public class VolumeDialogImpl implements VolumeDialog,
.alpha(1)
.translationX(0)
.setDuration(mDialogShowAnimationDurationMs)
+ .setListener(getJankListener(getDialogView(), TYPE_SHOW, DIALOG_TIMEOUT_MILLIS))
.setInterpolator(new SystemUIInterpolators.LogDecelerateInterpolator())
.withEndAction(() -> {
if (!Prefs.getBoolean(mContext, Prefs.Key.TOUCHED_RINGER_TOGGLE, false)) {
@@ -692,7 +708,7 @@ public class VolumeDialogImpl implements VolumeDialog,
final int m = seekBar.getMax();
final int n = m / 100 - 1;
final int level = progress == 0 ? 0
- : progress == m ? (m / 100) : (1 + (int)((progress / (float) m) * n));
+ : progress == m ? (m / 100) : (1 + (int) ((progress / (float) m) * n));
return level;
}
@@ -1251,7 +1267,33 @@ public class VolumeDialogImpl implements VolumeDialog,
mHandler.obtainMessage(H.DISMISS, reason, 0).sendToTarget();
}
+ private Animator.AnimatorListener getJankListener(View v, String type, long timeout) {
+ return new Animator.AnimatorListener() {
+ @Override
+ public void onAnimationStart(@NonNull Animator animation) {
+ mInteractionJankMonitor.begin(Builder.withView(CUJ_VOLUME_CONTROL, v).setTag(type)
+ .setTimeout(timeout));
+ }
+
+ @Override
+ public void onAnimationEnd(@NonNull Animator animation) {
+ mInteractionJankMonitor.end(CUJ_VOLUME_CONTROL);
+ }
+
+ @Override
+ public void onAnimationCancel(@NonNull Animator animation) {
+ mInteractionJankMonitor.cancel(CUJ_VOLUME_CONTROL);
+ }
+
+ @Override
+ public void onAnimationRepeat(@NonNull Animator animation) {
+ // no-op
+ }
+ };
+ }
+
private void showH(int reason) {
+ Trace.beginSection("VolumeDialogImpl#showH");
if (D.BUG) Log.d(TAG, "showH r=" + Events.SHOW_REASONS[reason]);
mHandler.removeMessages(H.SHOW);
mHandler.removeMessages(H.DISMISS);
@@ -1272,6 +1314,7 @@ public class VolumeDialogImpl implements VolumeDialog,
mController.getCaptionsComponentState(false);
checkODICaptionsTooltip(false);
updateBackgroundForDrawerClosedAmount();
+ Trace.endSection();
}
protected void rescheduleTimeoutH() {
@@ -1305,6 +1348,7 @@ public class VolumeDialogImpl implements VolumeDialog,
}
protected void dismissH(int reason) {
+ Trace.beginSection("VolumeDialogImpl#dismissH");
if (D.BUG) {
Log.d(TAG, "mDialog.dismiss() reason: " + Events.DISMISS_REASONS[reason]
+ " from: " + Debug.getCaller());
@@ -1335,7 +1379,8 @@ public class VolumeDialogImpl implements VolumeDialog,
hideRingerDrawer();
}, 50));
if (!shouldSlideInVolumeTray()) animator.translationX(mDialogView.getWidth() / 2.0f);
- animator.start();
+ animator.setListener(getJankListener(getDialogView(), TYPE_DISMISS,
+ mDialogHideAnimationDurationMs)).start();
checkODICaptionsTooltip(true);
mController.notifyVisible(false);
synchronized (mSafetyWarningLock) {
@@ -1344,6 +1389,7 @@ public class VolumeDialogImpl implements VolumeDialog,
mSafetyWarning.dismiss();
}
}
+ Trace.endSection();
}
private boolean showActiveStreamOnly() {
@@ -1383,6 +1429,7 @@ public class VolumeDialogImpl implements VolumeDialog,
}
private void updateRowsH(final VolumeRow activeRow) {
+ Trace.beginSection("VolumeDialogImpl#updateRowsH");
if (D.BUG) Log.d(TAG, "updateRowsH");
if (!mShowing) {
trimObsoleteH();
@@ -1446,6 +1493,7 @@ public class VolumeDialogImpl implements VolumeDialog,
}
updateBackgroundForDrawerClosedAmount();
+ Trace.endSection();
}
protected void updateRingerH() {
@@ -1730,7 +1778,9 @@ public class VolumeDialogImpl implements VolumeDialog,
final boolean enableSlider = !zenMuted;
final int vlevel = row.ss.muted && (!isRingStream && !zenMuted) ? 0
: row.ss.level;
+ Trace.beginSection("VolumeDialogImpl#updateVolumeRowSliderH");
updateVolumeRowSliderH(row, enableSlider, vlevel);
+ Trace.endSection();
if (row.number != null) row.number.setText(Integer.toString(vlevel));
}
@@ -1824,6 +1874,8 @@ public class VolumeDialogImpl implements VolumeDialog,
}
row.animTargetProgress = newProgress;
row.anim.setDuration(UPDATE_ANIMATION_DURATION);
+ row.anim.addListener(
+ getJankListener(row.view, TYPE_UPDATE, UPDATE_ANIMATION_DURATION));
row.anim.start();
} else {
// update slider directly to clamped value
diff --git a/packages/SystemUI/src/com/android/systemui/volume/dagger/VolumeModule.java b/packages/SystemUI/src/com/android/systemui/volume/dagger/VolumeModule.java
index 79aa643fc6c2..f3855bddfe48 100644
--- a/packages/SystemUI/src/com/android/systemui/volume/dagger/VolumeModule.java
+++ b/packages/SystemUI/src/com/android/systemui/volume/dagger/VolumeModule.java
@@ -19,6 +19,7 @@ package com.android.systemui.volume.dagger;
import android.content.Context;
import android.media.AudioManager;
+import com.android.internal.jank.InteractionJankMonitor;
import com.android.systemui.media.dialog.MediaOutputDialogFactory;
import com.android.systemui.plugins.ActivityStarter;
import com.android.systemui.plugins.VolumeDialog;
@@ -51,7 +52,8 @@ public interface VolumeModule {
DeviceProvisionedController deviceProvisionedController,
ConfigurationController configurationController,
MediaOutputDialogFactory mediaOutputDialogFactory,
- ActivityStarter activityStarter) {
+ ActivityStarter activityStarter,
+ InteractionJankMonitor interactionJankMonitor) {
VolumeDialogImpl impl = new VolumeDialogImpl(
context,
volumeDialogController,
@@ -59,7 +61,8 @@ public interface VolumeModule {
deviceProvisionedController,
configurationController,
mediaOutputDialogFactory,
- activityStarter);
+ activityStarter,
+ interactionJankMonitor);
impl.setStreamImportant(AudioManager.STREAM_SYSTEM, false);
impl.setAutomute(true);
impl.setSilentMode(false);
diff --git a/packages/SystemUI/src/com/android/systemui/wallet/controller/QuickAccessWalletController.java b/packages/SystemUI/src/com/android/systemui/wallet/controller/QuickAccessWalletController.java
index acff8712e92e..8c842f162e24 100644
--- a/packages/SystemUI/src/com/android/systemui/wallet/controller/QuickAccessWalletController.java
+++ b/packages/SystemUI/src/com/android/systemui/wallet/controller/QuickAccessWalletController.java
@@ -19,7 +19,6 @@ package com.android.systemui.wallet.controller;
import static com.android.systemui.wallet.controller.QuickAccessWalletController.WalletChangeEvent.DEFAULT_PAYMENT_APP_CHANGE;
import static com.android.systemui.wallet.controller.QuickAccessWalletController.WalletChangeEvent.WALLET_PREFERENCE_CHANGE;
-import android.annotation.CallbackExecutor;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
@@ -65,7 +64,6 @@ public class QuickAccessWalletController {
private static final long RECREATION_TIME_WINDOW = TimeUnit.MINUTES.toMillis(10L);
private final Context mContext;
private final Executor mExecutor;
- private final Executor mCallbackExecutor;
private final Executor mBgExecutor;
private final SecureSettings mSecureSettings;
private final SystemClock mClock;
@@ -82,14 +80,12 @@ public class QuickAccessWalletController {
public QuickAccessWalletController(
Context context,
@Main Executor executor,
- @CallbackExecutor Executor callbackExecutor,
@Background Executor bgExecutor,
SecureSettings secureSettings,
QuickAccessWalletClient quickAccessWalletClient,
SystemClock clock) {
mContext = context;
mExecutor = executor;
- mCallbackExecutor = callbackExecutor;
mBgExecutor = bgExecutor;
mSecureSettings = secureSettings;
mQuickAccessWalletClient = quickAccessWalletClient;
@@ -180,7 +176,7 @@ public class QuickAccessWalletController {
int iconSizePx = mContext.getResources().getDimensionPixelSize(R.dimen.wallet_icon_size);
GetWalletCardsRequest request =
new GetWalletCardsRequest(cardWidth, cardHeight, iconSizePx, /* maxCards= */ 1);
- mQuickAccessWalletClient.getWalletCards(mExecutor, request, cardsRetriever);
+ mQuickAccessWalletClient.getWalletCards(mBgExecutor, request, cardsRetriever);
}
/**
@@ -212,7 +208,7 @@ public class QuickAccessWalletController {
public void startQuickAccessUiIntent(ActivityStarter activityStarter,
ActivityLaunchAnimator.Controller animationController,
boolean hasCard) {
- mQuickAccessWalletClient.getWalletPendingIntent(mCallbackExecutor,
+ mQuickAccessWalletClient.getWalletPendingIntent(mBgExecutor,
walletPendingIntent -> {
if (walletPendingIntent != null) {
startQuickAccessViaPendingIntent(walletPendingIntent, activityStarter,
diff --git a/packages/SystemUI/tests/src/com/android/systemui/ScreenDecorationsTest.java b/packages/SystemUI/tests/src/com/android/systemui/ScreenDecorationsTest.java
index 7c211b22e657..57253af57f0e 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/ScreenDecorationsTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/ScreenDecorationsTest.java
@@ -159,6 +159,7 @@ public class ScreenDecorationsTest extends SysuiTestCase {
when(mContext.getDisplay()).thenReturn(mDisplay);
// Not support hwc layer by default
doReturn(null).when(mDisplay).getDisplayDecorationSupport();
+ doReturn(mDisplayMode).when(mDisplay).getMode();
when(mMockTypedArray.length()).thenReturn(0);
mPrivacyDotTopLeftDecorProvider = spy(new PrivacyDotCornerDecorProviderImpl(
diff --git a/packages/SystemUI/tests/src/com/android/systemui/biometrics/UdfpsControllerOverlayTest.kt b/packages/SystemUI/tests/src/com/android/systemui/biometrics/UdfpsControllerOverlayTest.kt
index 6eba2154e46c..431739b6187a 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/biometrics/UdfpsControllerOverlayTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/biometrics/UdfpsControllerOverlayTest.kt
@@ -367,6 +367,73 @@ class UdfpsControllerOverlayTest : SysuiTestCase() {
assertThat(controllerOverlay.matchesRequestId(REQUEST_ID)).isTrue()
assertThat(controllerOverlay.matchesRequestId(REQUEST_ID + 1)).isFalse()
}
+
+ @Test
+ fun testTouchOutsideAreaNoRotation() = withReason(REASON_ENROLL_ENROLLING) {
+ val touchHints =
+ context.resources.getStringArray(R.array.udfps_accessibility_touch_hints)
+ val rotation = Surface.ROTATION_0
+ // touch at 0 degrees
+ assertThat(controllerOverlay.onTouchOutsideOfSensorAreaImpl(0.0f /* x */, 0.0f /* y */,
+ 0.0f /* sensorX */, 0.0f /* sensorY */, rotation))
+ .isEqualTo(touchHints[0])
+ // touch at 90 degrees
+ assertThat(controllerOverlay.onTouchOutsideOfSensorAreaImpl(0.0f /* x */, -1.0f /* y */,
+ 0.0f /* sensorX */, 0.0f /* sensorY */, rotation))
+ .isEqualTo(touchHints[1])
+ // touch at 180 degrees
+ assertThat(controllerOverlay.onTouchOutsideOfSensorAreaImpl(-1.0f /* x */, 0.0f /* y */,
+ 0.0f /* sensorX */, 0.0f /* sensorY */, rotation))
+ .isEqualTo(touchHints[2])
+ // touch at 270 degrees
+ assertThat(controllerOverlay.onTouchOutsideOfSensorAreaImpl(0.0f /* x */, 1.0f /* y */,
+ 0.0f /* sensorX */, 0.0f /* sensorY */, rotation))
+ .isEqualTo(touchHints[3])
+ }
+
+ fun testTouchOutsideAreaNoRotation90Degrees() = withReason(REASON_ENROLL_ENROLLING) {
+ val touchHints =
+ context.resources.getStringArray(R.array.udfps_accessibility_touch_hints)
+ val rotation = Surface.ROTATION_90
+ // touch at 0 degrees -> 90 degrees
+ assertThat(controllerOverlay.onTouchOutsideOfSensorAreaImpl(0.0f /* x */, 0.0f /* y */,
+ 0.0f /* sensorX */, 0.0f /* sensorY */, rotation))
+ .isEqualTo(touchHints[1])
+ // touch at 90 degrees -> 180 degrees
+ assertThat(controllerOverlay.onTouchOutsideOfSensorAreaImpl(0.0f /* x */, -1.0f /* y */,
+ 0.0f /* sensorX */, 0.0f /* sensorY */, rotation))
+ .isEqualTo(touchHints[2])
+ // touch at 180 degrees -> 270 degrees
+ assertThat(controllerOverlay.onTouchOutsideOfSensorAreaImpl(-1.0f /* x */, 0.0f /* y */,
+ 0.0f /* sensorX */, 0.0f /* sensorY */, rotation))
+ .isEqualTo(touchHints[3])
+ // touch at 270 degrees -> 0 degrees
+ assertThat(controllerOverlay.onTouchOutsideOfSensorAreaImpl(0.0f /* x */, 1.0f /* y */,
+ 0.0f /* sensorX */, 0.0f /* sensorY */, rotation))
+ .isEqualTo(touchHints[0])
+ }
+
+ fun testTouchOutsideAreaNoRotation270Degrees() = withReason(REASON_ENROLL_ENROLLING) {
+ val touchHints =
+ context.resources.getStringArray(R.array.udfps_accessibility_touch_hints)
+ val rotation = Surface.ROTATION_270
+ // touch at 0 degrees -> 270 degrees
+ assertThat(controllerOverlay.onTouchOutsideOfSensorAreaImpl(0.0f /* x */, 0.0f /* y */,
+ 0.0f /* sensorX */, 0.0f /* sensorY */, rotation))
+ .isEqualTo(touchHints[3])
+ // touch at 90 degrees -> 0 degrees
+ assertThat(controllerOverlay.onTouchOutsideOfSensorAreaImpl(0.0f /* x */, -1.0f /* y */,
+ 0.0f /* sensorX */, 0.0f /* sensorY */, rotation))
+ .isEqualTo(touchHints[0])
+ // touch at 180 degrees -> 90 degrees
+ assertThat(controllerOverlay.onTouchOutsideOfSensorAreaImpl(-1.0f /* x */, 0.0f /* y */,
+ 0.0f /* sensorX */, 0.0f /* sensorY */, rotation))
+ .isEqualTo(touchHints[1])
+ // touch at 270 degrees -> 180 degrees
+ assertThat(controllerOverlay.onTouchOutsideOfSensorAreaImpl(0.0f /* x */, 1.0f /* y */,
+ 0.0f /* sensorX */, 0.0f /* sensorY */, rotation))
+ .isEqualTo(touchHints[2])
+ }
}
private class EnrollListener(
diff --git a/packages/SystemUI/tests/src/com/android/systemui/biometrics/UdfpsDialogMeasureAdapterTest.java b/packages/SystemUI/tests/src/com/android/systemui/biometrics/UdfpsDialogMeasureAdapterTest.java
index cd646c665d03..78fb5b00a21e 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/biometrics/UdfpsDialogMeasureAdapterTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/biometrics/UdfpsDialogMeasureAdapterTest.java
@@ -70,7 +70,7 @@ public class UdfpsDialogMeasureAdapterTest extends SysuiTestCase {
assertEquals(970,
UdfpsDialogMeasureAdapter.calculateBottomSpacerHeightForPortrait(
props, displayHeightPx, textIndicatorHeightPx, buttonBarHeightPx,
- dialogBottomMarginPx, navbarHeightPx
+ dialogBottomMarginPx, navbarHeightPx, 1.0f /* resolutionScale */
));
}
@@ -135,6 +135,7 @@ public class UdfpsDialogMeasureAdapterTest extends SysuiTestCase {
assertEquals(1205,
UdfpsDialogMeasureAdapter.calculateHorizontalSpacerWidthForLandscape(
- props, displayWidthPx, dialogMarginPx, navbarHorizontalInsetPx));
+ props, displayWidthPx, dialogMarginPx, navbarHorizontalInsetPx,
+ 1.0f /* resolutionScale */));
}
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/bluetooth/BroadcastDialogTest.java b/packages/SystemUI/tests/src/com/android/systemui/bluetooth/BroadcastDialogTest.java
new file mode 100644
index 000000000000..a61cecbabf30
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/bluetooth/BroadcastDialogTest.java
@@ -0,0 +1,83 @@
+/**
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.bluetooth;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.Mockito.mock;
+
+import androidx.test.filters.SmallTest;
+
+import android.testing.AndroidTestingRunner;
+import android.testing.TestableLooper;
+import android.view.View;
+import android.widget.Button;
+import android.widget.TextView;
+
+import com.android.internal.logging.UiEventLogger;
+import com.android.systemui.R;
+import com.android.systemui.SysuiTestCase;
+import com.android.systemui.media.dialog.MediaOutputDialogFactory;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.MockitoAnnotations;
+
+@SmallTest
+@RunWith(AndroidTestingRunner.class)
+@TestableLooper.RunWithLooper(setAsMainLooper = true)
+public class BroadcastDialogTest extends SysuiTestCase {
+
+ private static final String SWITCH_APP = "Music";
+ private static final String TEST_PACKAGE = "com.google.android.apps.nbu.files";
+ private BroadcastDialog mBroadcastDialog;
+ private View mDialogView;
+ private TextView mSubTitle;
+ private Button mChangeOutputButton;
+
+ @Before
+ public void setUp() {
+ MockitoAnnotations.initMocks(this);
+ mBroadcastDialog = new BroadcastDialog(mContext, mock(MediaOutputDialogFactory.class),
+ SWITCH_APP, TEST_PACKAGE, mock(UiEventLogger.class));
+ mBroadcastDialog.show();
+ mDialogView = mBroadcastDialog.mDialogView;
+ }
+
+ @After
+ public void tearDown() {
+ mBroadcastDialog.dismiss();
+ }
+
+ @Test
+ public void onCreate_withCurrentApp_checkSwitchAppContent() {
+ mSubTitle = mDialogView.requireViewById(R.id.dialog_subtitle);
+
+ assertThat(mSubTitle.getText()).isEqualTo(
+ mContext.getString(R.string.bt_le_audio_broadcast_dialog_sub_title, SWITCH_APP));
+ }
+
+ @Test
+ public void onClick_withChangeOutput_dismissBroadcastDialog() {
+ mChangeOutputButton = mDialogView.requireViewById(R.id.change_output);
+ mChangeOutputButton.performClick();
+
+ assertThat(mBroadcastDialog.isShowing()).isFalse();
+ }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/dump/LogBufferHelper.kt b/packages/SystemUI/tests/src/com/android/systemui/dump/LogBufferHelper.kt
index 0720bdb06556..bd029a727ee3 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/dump/LogBufferHelper.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/dump/LogBufferHelper.kt
@@ -24,7 +24,7 @@ import com.android.systemui.log.LogcatEchoTracker
* Creates a LogBuffer that will echo everything to logcat, which is useful for debugging tests.
*/
fun logcatLogBuffer(name: String = "EchoToLogcatLogBuffer") =
- LogBuffer(name, 50, 50, LogcatEchoTrackerAlways())
+ LogBuffer(name, 50, LogcatEchoTrackerAlways())
/**
* A [LogcatEchoTracker] that always allows echoing to the logcat.
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/KeyguardUnlockAnimationControllerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/keyguard/KeyguardUnlockAnimationControllerTest.kt
index 2abc666e87fb..a4d223853b12 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/keyguard/KeyguardUnlockAnimationControllerTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/KeyguardUnlockAnimationControllerTest.kt
@@ -14,6 +14,8 @@ import androidx.test.filters.SmallTest
import com.android.keyguard.KeyguardViewController
import com.android.systemui.SysuiTestCase
import com.android.systemui.flags.FeatureFlags
+import com.android.systemui.shared.system.smartspace.ILauncherUnlockAnimationController
+import com.android.systemui.statusbar.NotificationShadeWindowController
import com.android.systemui.statusbar.SysuiStatusBarStateController
import com.android.systemui.statusbar.phone.BiometricUnlockController
import com.android.systemui.statusbar.policy.KeyguardStateController
@@ -52,6 +54,11 @@ class KeyguardUnlockAnimationControllerTest : SysuiTestCase() {
private lateinit var surfaceTransactionApplier: SyncRtSurfaceTransactionApplier
@Mock
private lateinit var statusBarStateController: SysuiStatusBarStateController
+ @Mock
+ private lateinit var notificationShadeWindowController: NotificationShadeWindowController
+
+ @Mock
+ private lateinit var launcherUnlockAnimationController: ILauncherUnlockAnimationController.Stub
private lateinit var remoteAnimationTarget: RemoteAnimationTarget
@@ -60,8 +67,11 @@ class KeyguardUnlockAnimationControllerTest : SysuiTestCase() {
MockitoAnnotations.initMocks(this)
keyguardUnlockAnimationController = KeyguardUnlockAnimationController(
context, keyguardStateController, { keyguardViewMediator }, keyguardViewController,
- featureFlags, { biometricUnlockController }, statusBarStateController
+ featureFlags, { biometricUnlockController }, statusBarStateController,
+ notificationShadeWindowController
)
+ keyguardUnlockAnimationController.setLauncherUnlockController(
+ launcherUnlockAnimationController)
`when`(keyguardViewController.viewRootImpl).thenReturn(mock(ViewRootImpl::class.java))
@@ -194,4 +204,18 @@ class KeyguardUnlockAnimationControllerTest : SysuiTestCase() {
assertTrue(keyguardUnlockAnimationController.isPlayingCannedUnlockAnimation())
assertFalse(keyguardUnlockAnimationController.surfaceBehindAlphaAnimator.isRunning)
}
+
+ @Test
+ fun doNotPlayCannedUnlockAnimation_ifLaunchingApp() {
+ `when`(notificationShadeWindowController.isLaunchingActivity).thenReturn(true)
+
+ keyguardUnlockAnimationController.notifyStartSurfaceBehindRemoteAnimation(
+ remoteAnimationTarget,
+ 0 /* startTime */,
+ true /* requestedShowSurfaceBehindKeyguard */
+ )
+
+ assertFalse(keyguardUnlockAnimationController.canPerformInWindowLauncherAnimations())
+ assertFalse(keyguardUnlockAnimationController.isPlayingCannedUnlockAnimation())
+ }
} \ No newline at end of file
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/LockIconViewControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/keyguard/LockIconViewControllerTest.java
index c532ed5ab651..24d051508fde 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/keyguard/LockIconViewControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/LockIconViewControllerTest.java
@@ -135,8 +135,7 @@ public class LockIconViewControllerTest extends SysuiTestCase {
.startMocking();
MockitoAnnotations.initMocks(this);
- when(mLockIconView.getResources()).thenReturn(mResources);
- when(mLockIconView.getContext()).thenReturn(mContext);
+ setupLockIconViewMocks();
when(mContext.getResources()).thenReturn(mResources);
when(mContext.getSystemService(WindowManager.class)).thenReturn(mWindowManager);
Rect windowBounds = new Rect(0, 0, 800, 1200);
@@ -206,13 +205,14 @@ public class LockIconViewControllerTest extends SysuiTestCase {
}
@Test
- public void testUpdateFingerprintLocationOnAuthenticatorsRegistered() {
+ public void testUpdateLockIconLocationOnAuthenticatorsRegistered() {
// GIVEN fp sensor location is not available pre-init
when(mKeyguardUpdateMonitor.isUdfpsSupported()).thenReturn(false);
when(mAuthController.getFingerprintSensorLocation()).thenReturn(null);
mLockIconViewController.init();
captureAttachListener();
mAttachListener.onViewAttachedToWindow(mLockIconView);
+ resetLockIconView(); // reset any method call counts for when we verify method calls later
// GIVEN fp sensor location is available post-attached
captureAuthControllerCallback();
@@ -228,6 +228,29 @@ public class LockIconViewControllerTest extends SysuiTestCase {
}
@Test
+ public void testUpdateLockIconLocationOnUdfpsLocationChanged() {
+ // GIVEN fp sensor location is not available pre-init
+ when(mKeyguardUpdateMonitor.isUdfpsSupported()).thenReturn(false);
+ when(mAuthController.getFingerprintSensorLocation()).thenReturn(null);
+ mLockIconViewController.init();
+ captureAttachListener();
+ mAttachListener.onViewAttachedToWindow(mLockIconView);
+ resetLockIconView(); // reset any method call counts for when we verify method calls later
+
+ // GIVEN fp sensor location is available post-attached
+ captureAuthControllerCallback();
+ Pair<Float, PointF> udfps = setupUdfps();
+
+ // WHEN udfps location changes
+ mAuthControllerCallback.onUdfpsLocationChanged();
+ mDelayableExecutor.runAllReady();
+
+ // THEN lock icon view location is updated with the same coordinates as auth controller vals
+ verify(mLockIconView).setCenterLocation(eq(udfps.second), eq(udfps.first),
+ eq(PADDING));
+ }
+
+ @Test
public void testLockIconViewBackgroundEnabledWhenUdfpsIsSupported() {
// GIVEN Udpfs sensor location is available
setupUdfps();
@@ -440,4 +463,14 @@ public class LockIconViewControllerTest extends SysuiTestCase {
mKeyguardUpdateMonitorCallbackCaptor.capture());
mKeyguardUpdateMonitorCallback = mKeyguardUpdateMonitorCallbackCaptor.getValue();
}
+
+ private void setupLockIconViewMocks() {
+ when(mLockIconView.getResources()).thenReturn(mResources);
+ when(mLockIconView.getContext()).thenReturn(mContext);
+ }
+
+ private void resetLockIconView() {
+ reset(mLockIconView);
+ setupLockIconViewMocks();
+ }
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/media/MediaCarouselControllerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/media/MediaCarouselControllerTest.kt
index 0d917e3b19a8..ceb811b8d8aa 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/media/MediaCarouselControllerTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/media/MediaCarouselControllerTest.kt
@@ -63,6 +63,7 @@ class MediaCarouselControllerTest : SysuiTestCase() {
@Mock lateinit var falsingManager: FalsingManager
@Mock lateinit var dumpManager: DumpManager
@Mock lateinit var logger: MediaUiEventLogger
+ @Mock lateinit var debugLogger: MediaCarouselControllerLogger
private val clock = FakeSystemClock()
private lateinit var mediaCarouselController: MediaCarouselController
@@ -83,7 +84,8 @@ class MediaCarouselControllerTest : SysuiTestCase() {
falsingCollector,
falsingManager,
dumpManager,
- logger
+ logger,
+ debugLogger
)
MediaPlayerData.clear()
diff --git a/packages/SystemUI/tests/src/com/android/systemui/media/MediaTimeoutListenerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/media/MediaTimeoutListenerTest.kt
index 91c0cc2ff891..823d4ae8c447 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/media/MediaTimeoutListenerTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/media/MediaTimeoutListenerTest.kt
@@ -23,6 +23,8 @@ import android.media.session.PlaybackState
import android.testing.AndroidTestingRunner
import androidx.test.filters.SmallTest
import com.android.systemui.SysuiTestCase
+import com.android.systemui.plugins.statusbar.StatusBarStateController
+import com.android.systemui.statusbar.SysuiStatusBarStateController
import com.android.systemui.util.concurrency.FakeExecutor
import com.android.systemui.util.mockito.any
import com.android.systemui.util.mockito.capture
@@ -63,10 +65,13 @@ class MediaTimeoutListenerTest : SysuiTestCase() {
@Mock private lateinit var mediaControllerFactory: MediaControllerFactory
@Mock private lateinit var mediaController: MediaController
@Mock private lateinit var logger: MediaTimeoutLogger
+ @Mock private lateinit var statusBarStateController: SysuiStatusBarStateController
private lateinit var executor: FakeExecutor
@Mock private lateinit var timeoutCallback: (String, Boolean) -> Unit
@Mock private lateinit var stateCallback: (String, PlaybackState) -> Unit
@Captor private lateinit var mediaCallbackCaptor: ArgumentCaptor<MediaController.Callback>
+ @Captor private lateinit var dozingCallbackCaptor:
+ ArgumentCaptor<StatusBarStateController.StateListener>
@JvmField @Rule val mockito = MockitoJUnit.rule()
private lateinit var metadataBuilder: MediaMetadata.Builder
private lateinit var playbackBuilder: PlaybackState.Builder
@@ -74,12 +79,19 @@ class MediaTimeoutListenerTest : SysuiTestCase() {
private lateinit var mediaData: MediaData
private lateinit var resumeData: MediaData
private lateinit var mediaTimeoutListener: MediaTimeoutListener
+ private var clock = FakeSystemClock()
@Before
fun setup() {
`when`(mediaControllerFactory.create(any())).thenReturn(mediaController)
- executor = FakeExecutor(FakeSystemClock())
- mediaTimeoutListener = MediaTimeoutListener(mediaControllerFactory, executor, logger)
+ executor = FakeExecutor(clock)
+ mediaTimeoutListener = MediaTimeoutListener(
+ mediaControllerFactory,
+ executor,
+ logger,
+ statusBarStateController,
+ clock
+ )
mediaTimeoutListener.timeoutCallback = timeoutCallback
mediaTimeoutListener.stateCallback = stateCallback
@@ -530,6 +542,49 @@ class MediaTimeoutListenerTest : SysuiTestCase() {
verify(stateCallback, never()).invoke(eq(KEY), eq(playingState!!))
}
+ @Test
+ fun testTimeoutCallback_dozedPastTimeout_invokedOnWakeup() {
+ // When paused media is loaded
+ testOnMediaDataLoaded_registersPlaybackListener()
+ mediaCallbackCaptor.value.onPlaybackStateChanged(PlaybackState.Builder()
+ .setState(PlaybackState.STATE_PAUSED, 0L, 0f).build())
+ verify(statusBarStateController).addCallback(capture(dozingCallbackCaptor))
+
+ // And we doze past the scheduled timeout
+ val time = clock.currentTimeMillis()
+ clock.setElapsedRealtime(time + PAUSED_MEDIA_TIMEOUT)
+ assertThat(executor.numPending()).isEqualTo(1)
+
+ // Then when no longer dozing, the timeout runs immediately
+ dozingCallbackCaptor.value.onDozingChanged(false)
+ verify(timeoutCallback).invoke(eq(KEY), eq(true))
+ verify(logger).logTimeout(eq(KEY))
+
+ // and cancel any later scheduled timeout
+ verify(logger).logTimeoutCancelled(eq(KEY), any())
+ assertThat(executor.numPending()).isEqualTo(0)
+ }
+
+ @Test
+ fun testTimeoutCallback_dozeShortTime_notInvokedOnWakeup() {
+ // When paused media is loaded
+ val time = clock.currentTimeMillis()
+ clock.setElapsedRealtime(time)
+ testOnMediaDataLoaded_registersPlaybackListener()
+ mediaCallbackCaptor.value.onPlaybackStateChanged(PlaybackState.Builder()
+ .setState(PlaybackState.STATE_PAUSED, 0L, 0f).build())
+ verify(statusBarStateController).addCallback(capture(dozingCallbackCaptor))
+
+ // And we doze, but not past the scheduled timeout
+ clock.setElapsedRealtime(time + PAUSED_MEDIA_TIMEOUT / 2L)
+ assertThat(executor.numPending()).isEqualTo(1)
+
+ // Then when no longer dozing, the timeout remains scheduled
+ dozingCallbackCaptor.value.onDozingChanged(false)
+ verify(timeoutCallback, never()).invoke(eq(KEY), eq(true))
+ assertThat(executor.numPending()).isEqualTo(1)
+ }
+
private fun loadMediaDataWithPlaybackState(state: PlaybackState) {
`when`(mediaController.playbackState).thenReturn(state)
mediaTimeoutListener.onMediaDataLoaded(KEY, null, mediaData)
diff --git a/packages/SystemUI/tests/src/com/android/systemui/monet/ColorSchemeTest.java b/packages/SystemUI/tests/src/com/android/systemui/monet/ColorSchemeTest.java
index 863484b62a00..890e4de118e3 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/monet/ColorSchemeTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/monet/ColorSchemeTest.java
@@ -133,7 +133,7 @@ public class ColorSchemeTest extends SysuiTestCase {
Style.VIBRANT /* style */);
int neutralMid = colorScheme.getNeutral1().get(colorScheme.getNeutral1().size() / 2);
Cam cam = Cam.fromInt(neutralMid);
- Assert.assertTrue("chroma was " + cam.getChroma(), Math.floor(cam.getChroma()) <= 10.0);
+ Assert.assertTrue("chroma was " + cam.getChroma(), Math.floor(cam.getChroma()) <= 12.0);
}
@Test
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qrcodescanner/controller/QRCodeScannerControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/qrcodescanner/controller/QRCodeScannerControllerTest.java
index 4a6bbbcf1d6b..346d1e60fcf9 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qrcodescanner/controller/QRCodeScannerControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/qrcodescanner/controller/QRCodeScannerControllerTest.java
@@ -24,7 +24,6 @@ import static com.android.systemui.qrcodescanner.controller.QRCodeScannerControl
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -32,6 +31,7 @@ import static org.mockito.Mockito.when;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
+import android.content.res.Resources;
import android.os.UserHandle;
import android.provider.DeviceConfig;
import android.provider.Settings;
@@ -41,7 +41,6 @@ import android.testing.TestableLooper;
import androidx.test.filters.SmallTest;
import com.android.internal.config.sysui.SystemUiDeviceConfigFlags;
-import com.android.systemui.R;
import com.android.systemui.SysuiTestCase;
import com.android.systemui.settings.UserTracker;
import com.android.systemui.util.DeviceConfigProxyFake;
@@ -90,8 +89,9 @@ public class QRCodeScannerControllerTest extends SysuiTestCase {
when(mPackageManager.queryIntentActivities(any(Intent.class),
any(Integer.class))).thenReturn(resolveInfoList);
when(mPackageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)).thenReturn(true);
- mContext.getOrCreateTestableResources().addOverride(R.string.def_qr_code_component,
- defaultActivity);
+ mContext.getOrCreateTestableResources().addOverride(
+ com.android.internal.R.string.config_defaultQrCodeComponent, defaultActivity);
+
mContext.getOrCreateTestableResources().addOverride(
android.R.bool.config_enableQrCodeScannerOnLockScreen, enableOnLockScreen);
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/FgsManagerControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/qs/FgsManagerControllerTest.java
new file mode 100644
index 000000000000..2927669020c8
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/FgsManagerControllerTest.java
@@ -0,0 +1,285 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.qs;
+
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.argThat;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.ArgumentMatchers.isNull;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+
+import android.app.IActivityManager;
+import android.app.IForegroundServiceObserver;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.PackageManager;
+import android.content.pm.UserInfo;
+import android.os.Binder;
+import android.os.RemoteException;
+import android.provider.DeviceConfig;
+import android.testing.AndroidTestingRunner;
+import android.testing.TestableLooper;
+
+import androidx.test.filters.SmallTest;
+
+import com.android.internal.config.sysui.SystemUiDeviceConfigFlags;
+import com.android.systemui.SysuiTestCase;
+import com.android.systemui.animation.DialogLaunchAnimator;
+import com.android.systemui.broadcast.BroadcastDispatcher;
+import com.android.systemui.dump.DumpManager;
+import com.android.systemui.settings.UserTracker;
+import com.android.systemui.util.DeviceConfigProxyFake;
+import com.android.systemui.util.concurrency.FakeExecutor;
+import com.android.systemui.util.time.FakeSystemClock;
+
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.ArgumentMatchers;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.MockitoAnnotations;
+
+import java.util.ArrayList;
+import java.util.List;
+
+@RunWith(AndroidTestingRunner.class)
+@TestableLooper.RunWithLooper
+@SmallTest
+public class FgsManagerControllerTest extends SysuiTestCase {
+
+ FakeSystemClock mSystemClock;
+ FakeExecutor mMainExecutor;
+ FakeExecutor mBackgroundExecutor;
+ DeviceConfigProxyFake mDeviceConfigProxyFake;
+
+ @Mock
+ IActivityManager mIActivityManager;
+ @Mock
+ PackageManager mPackageManager;
+ @Mock
+ UserTracker mUserTracker;
+ @Mock
+ DialogLaunchAnimator mDialogLaunchAnimator;
+ @Mock
+ BroadcastDispatcher mBroadcastDispatcher;
+ @Mock
+ DumpManager mDumpManager;
+
+ private FgsManagerController mFmc;
+
+ private IForegroundServiceObserver mIForegroundServiceObserver;
+ private UserTracker.Callback mUserTrackerCallback;
+ private BroadcastReceiver mShowFgsManagerReceiver;
+
+ private List<UserInfo> mUserProfiles;
+
+ @Before
+ public void setUp() throws RemoteException {
+ MockitoAnnotations.initMocks(this);
+
+ mDeviceConfigProxyFake = new DeviceConfigProxyFake();
+ mDeviceConfigProxyFake.setProperty(DeviceConfig.NAMESPACE_SYSTEMUI,
+ SystemUiDeviceConfigFlags.TASK_MANAGER_ENABLED, "true", false);
+ mSystemClock = new FakeSystemClock();
+ mMainExecutor = new FakeExecutor(mSystemClock);
+ mBackgroundExecutor = new FakeExecutor(mSystemClock);
+
+ mUserProfiles = new ArrayList<>();
+ Mockito.doReturn(mUserProfiles).when(mUserTracker).getUserProfiles();
+
+ mFmc = createFgsManagerController();
+ }
+
+ @Test
+ public void testNumPackages() throws RemoteException {
+ setUserProfiles(0);
+
+ Binder b1 = new Binder();
+ Binder b2 = new Binder();
+ Assert.assertEquals(0, mFmc.getNumRunningPackages());
+ mIForegroundServiceObserver.onForegroundStateChanged(b1, "pkg1", 0, true);
+ Assert.assertEquals(1, mFmc.getNumRunningPackages());
+ mIForegroundServiceObserver.onForegroundStateChanged(b2, "pkg2", 0, true);
+ Assert.assertEquals(2, mFmc.getNumRunningPackages());
+ mIForegroundServiceObserver.onForegroundStateChanged(b1, "pkg1", 0, false);
+ Assert.assertEquals(1, mFmc.getNumRunningPackages());
+ mIForegroundServiceObserver.onForegroundStateChanged(b2, "pkg2", 0, false);
+ Assert.assertEquals(0, mFmc.getNumRunningPackages());
+ }
+
+ @Test
+ public void testNumPackagesDoesNotChangeWhenSecondFgsIsStarted() throws RemoteException {
+ setUserProfiles(0);
+
+ // Different tokens == different services
+ Binder b1 = new Binder();
+ Binder b2 = new Binder();
+ Assert.assertEquals(0, mFmc.getNumRunningPackages());
+ mIForegroundServiceObserver.onForegroundStateChanged(b1, "pkg1", 0, true);
+ Assert.assertEquals(1, mFmc.getNumRunningPackages());
+ mIForegroundServiceObserver.onForegroundStateChanged(b2, "pkg1", 0, true);
+ Assert.assertEquals(1, mFmc.getNumRunningPackages());
+ mIForegroundServiceObserver.onForegroundStateChanged(b1, "pkg1", 0, false);
+ Assert.assertEquals(1, mFmc.getNumRunningPackages());
+ mIForegroundServiceObserver.onForegroundStateChanged(b2, "pkg1", 0, false);
+ Assert.assertEquals(0, mFmc.getNumRunningPackages());
+ }
+
+ @Test
+ public void testNumPackagesListener() throws RemoteException {
+ setUserProfiles(0);
+
+ FgsManagerController.OnNumberOfPackagesChangedListener onNumberOfPackagesChangedListener =
+ Mockito.mock(FgsManagerController.OnNumberOfPackagesChangedListener.class);
+
+ mFmc.addOnNumberOfPackagesChangedListener(onNumberOfPackagesChangedListener);
+
+ Binder b1 = new Binder();
+ Binder b2 = new Binder();
+
+ verify(onNumberOfPackagesChangedListener, never()).onNumberOfPackagesChanged(anyInt());
+
+ mIForegroundServiceObserver.onForegroundStateChanged(b1, "pkg1", 0, true);
+ mBackgroundExecutor.advanceClockToLast();
+ mBackgroundExecutor.runAllReady();
+ verify(onNumberOfPackagesChangedListener).onNumberOfPackagesChanged(1);
+
+ mIForegroundServiceObserver.onForegroundStateChanged(b2, "pkg2", 0, true);
+ mBackgroundExecutor.advanceClockToLast();
+ mBackgroundExecutor.runAllReady();
+ verify(onNumberOfPackagesChangedListener).onNumberOfPackagesChanged(2);
+
+ mIForegroundServiceObserver.onForegroundStateChanged(b1, "pkg1", 0, false);
+ mBackgroundExecutor.advanceClockToLast();
+ mBackgroundExecutor.runAllReady();
+ verify(onNumberOfPackagesChangedListener, times(2)).onNumberOfPackagesChanged(1);
+
+ mIForegroundServiceObserver.onForegroundStateChanged(b2, "pkg2", 0, false);
+ mBackgroundExecutor.advanceClockToLast();
+ mBackgroundExecutor.runAllReady();
+ verify(onNumberOfPackagesChangedListener).onNumberOfPackagesChanged(0);
+ }
+
+ @Test
+ public void testChangesSinceLastDialog() throws RemoteException {
+ setUserProfiles(0);
+
+ Assert.assertFalse(mFmc.getChangesSinceDialog());
+ mIForegroundServiceObserver.onForegroundStateChanged(new Binder(), "pkg", 0, true);
+ Assert.assertTrue(mFmc.getChangesSinceDialog());
+ }
+
+ @Test
+ public void testProfilePackagesCounted() throws RemoteException {
+ setUserProfiles(0, 10);
+
+ mIForegroundServiceObserver.onForegroundStateChanged(new Binder(), "pkg1", 0, true);
+ mIForegroundServiceObserver.onForegroundStateChanged(new Binder(), "pkg2", 10, true);
+ Assert.assertEquals(2, mFmc.getNumRunningPackages());
+ }
+
+ @Test
+ public void testSecondaryUserPackagesAreNotCounted() throws RemoteException {
+ setUserProfiles(0);
+
+ mIForegroundServiceObserver.onForegroundStateChanged(new Binder(), "pkg1", 0, true);
+ mIForegroundServiceObserver.onForegroundStateChanged(new Binder(), "pkg2", 10, true);
+ Assert.assertEquals(1, mFmc.getNumRunningPackages());
+ }
+
+ @Test
+ public void testSecondaryUserPackagesAreCountedWhenUserSwitch() throws RemoteException {
+ setUserProfiles(0);
+
+ mIForegroundServiceObserver.onForegroundStateChanged(new Binder(), "pkg1", 0, true);
+ mIForegroundServiceObserver.onForegroundStateChanged(new Binder(), "pkg2", 10, true);
+ mIForegroundServiceObserver.onForegroundStateChanged(new Binder(), "pkg3", 10, true);
+
+ Assert.assertEquals(1, mFmc.getNumRunningPackages());
+
+ setUserProfiles(10);
+ Assert.assertEquals(2, mFmc.getNumRunningPackages());
+ }
+
+
+
+ FgsManagerController createFgsManagerController() throws RemoteException {
+ ArgumentCaptor<IForegroundServiceObserver> iForegroundServiceObserverArgumentCaptor =
+ ArgumentCaptor.forClass(IForegroundServiceObserver.class);
+ ArgumentCaptor<UserTracker.Callback> userTrackerCallbackArgumentCaptor =
+ ArgumentCaptor.forClass(UserTracker.Callback.class);
+ ArgumentCaptor<BroadcastReceiver> showFgsManagerReceiverArgumentCaptor =
+ ArgumentCaptor.forClass(BroadcastReceiver.class);
+
+ FgsManagerController result = new FgsManagerController(
+ mContext,
+ mMainExecutor,
+ mBackgroundExecutor,
+ mSystemClock,
+ mIActivityManager,
+ mPackageManager,
+ mUserTracker,
+ mDeviceConfigProxyFake,
+ mDialogLaunchAnimator,
+ mBroadcastDispatcher,
+ mDumpManager
+ );
+ result.init();
+
+ verify(mIActivityManager).registerForegroundServiceObserver(
+ iForegroundServiceObserverArgumentCaptor.capture()
+ );
+ verify(mUserTracker).addCallback(
+ userTrackerCallbackArgumentCaptor.capture(),
+ ArgumentMatchers.eq(mBackgroundExecutor)
+ );
+ verify(mBroadcastDispatcher).registerReceiver(
+ showFgsManagerReceiverArgumentCaptor.capture(),
+ argThat(fltr -> fltr.matchAction(Intent.ACTION_SHOW_FOREGROUND_SERVICE_MANAGER)),
+ eq(mMainExecutor),
+ isNull(),
+ eq(Context.RECEIVER_NOT_EXPORTED),
+ isNull()
+ );
+
+ mIForegroundServiceObserver = iForegroundServiceObserverArgumentCaptor.getValue();
+ mUserTrackerCallback = userTrackerCallbackArgumentCaptor.getValue();
+ mShowFgsManagerReceiver = showFgsManagerReceiverArgumentCaptor.getValue();
+
+ return result;
+ }
+
+ private void setUserProfiles(int current, int... profileUserIds) {
+ mUserProfiles.clear();
+ mUserProfiles.add(new UserInfo(current, "current:" + current, 0));
+ for (int id : profileUserIds) {
+ mUserProfiles.add(new UserInfo(id, "profile:" + id, 0));
+ }
+
+ if (mUserTrackerCallback != null) {
+ mUserTrackerCallback.onUserChanged(current, mock(Context.class));
+ mUserTrackerCallback.onProfilesChanged(mUserProfiles);
+ }
+ }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/DreamTileTest.java b/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/DreamTileTest.java
index 5b7af654bbb6..c2a41d5e41fb 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/DreamTileTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/DreamTileTest.java
@@ -20,6 +20,7 @@ import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertFalse;
import static junit.framework.TestCase.assertTrue;
+import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -27,7 +28,7 @@ import static org.mockito.Mockito.when;
import android.content.ComponentName;
import android.os.Handler;
import android.os.RemoteException;
-import android.os.UserManager;
+import android.os.UserHandle;
import android.provider.Settings;
import android.service.dreams.IDreamManager;
import android.service.quicksettings.Tile;
@@ -45,6 +46,7 @@ import com.android.systemui.plugins.ActivityStarter;
import com.android.systemui.plugins.statusbar.StatusBarStateController;
import com.android.systemui.qs.QSTileHost;
import com.android.systemui.qs.logging.QSLogger;
+import com.android.systemui.settings.UserTracker;
import com.android.systemui.util.settings.FakeSettings;
import com.android.systemui.util.settings.SecureSettings;
@@ -74,7 +76,7 @@ public class DreamTileTest extends SysuiTestCase {
@Mock
private BroadcastDispatcher mBroadcastDispatcher;
@Mock
- private UserManager mUserManager;
+ private UserTracker mUserTracker;
private TestableLooper mTestableLooper;
@@ -196,15 +198,21 @@ public class DreamTileTest extends SysuiTestCase {
DreamTile supportedTileAllUsers = constructTileForTest(true, false);
- when(mUserManager.isSystemUser()).thenReturn(true);
+ UserHandle systemUserHandle = mock(UserHandle.class);
+ when(systemUserHandle.isSystem()).thenReturn(true);
+
+ UserHandle nonSystemUserHandle = mock(UserHandle.class);
+ when(nonSystemUserHandle.isSystem()).thenReturn(false);
+
+ when(mUserTracker.getUserHandle()).thenReturn(systemUserHandle);
assertTrue(supportedTileAllUsers.isAvailable());
- when(mUserManager.isSystemUser()).thenReturn(false);
+ when(mUserTracker.getUserHandle()).thenReturn(nonSystemUserHandle);
assertTrue(supportedTileAllUsers.isAvailable());
DreamTile supportedTileOnlySystemUser = constructTileForTest(true, true);
- when(mUserManager.isSystemUser()).thenReturn(true);
+ when(mUserTracker.getUserHandle()).thenReturn(systemUserHandle);
assertTrue(supportedTileOnlySystemUser.isAvailable());
- when(mUserManager.isSystemUser()).thenReturn(false);
+ when(mUserTracker.getUserHandle()).thenReturn(nonSystemUserHandle);
assertFalse(supportedTileOnlySystemUser.isAvailable());
}
@@ -227,7 +235,7 @@ public class DreamTileTest extends SysuiTestCase {
mDreamManager,
mSecureSettings,
mBroadcastDispatcher,
- mUserManager,
+ mUserTracker,
dreamSupported, dreamOnlyEnabledForSystemUser);
}
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/HotspotTileTest.java b/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/HotspotTileTest.java
new file mode 100644
index 000000000000..b86713d0890b
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/HotspotTileTest.java
@@ -0,0 +1,125 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.qs.tiles;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import android.os.Handler;
+import android.service.quicksettings.Tile;
+import android.testing.AndroidTestingRunner;
+import android.testing.TestableLooper;
+
+import androidx.test.filters.SmallTest;
+
+import com.android.dx.mockito.inline.extended.ExtendedMockito;
+import com.android.internal.logging.MetricsLogger;
+import com.android.settingslib.wifi.WifiEnterpriseRestrictionUtils;
+import com.android.systemui.R;
+import com.android.systemui.SysuiTestCase;
+import com.android.systemui.classifier.FalsingManagerFake;
+import com.android.systemui.plugins.ActivityStarter;
+import com.android.systemui.plugins.qs.QSTile;
+import com.android.systemui.plugins.statusbar.StatusBarStateController;
+import com.android.systemui.qs.QSTileHost;
+import com.android.systemui.qs.logging.QSLogger;
+import com.android.systemui.statusbar.policy.DataSaverController;
+import com.android.systemui.statusbar.policy.HotspotController;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoSession;
+import org.mockito.junit.MockitoJUnit;
+import org.mockito.junit.MockitoRule;
+
+@RunWith(AndroidTestingRunner.class)
+@TestableLooper.RunWithLooper(setAsMainLooper = true)
+@SmallTest
+public class HotspotTileTest extends SysuiTestCase {
+
+ @Rule
+ public MockitoRule mRule = MockitoJUnit.rule();
+ @Mock
+ private QSTileHost mHost;
+ @Mock
+ private HotspotController mHotspotController;
+ @Mock
+ private DataSaverController mDataSaverController;
+
+ private TestableLooper mTestableLooper;
+ private HotspotTile mTile;
+ private QSTile.BooleanState mState = new QSTile.BooleanState();
+
+ @Before
+ public void setUp() throws Exception {
+ mTestableLooper = TestableLooper.get(this);
+ when(mHost.getContext()).thenReturn(mContext);
+ when(mHost.getUserContext()).thenReturn(mContext);
+ when(mDataSaverController.isDataSaverEnabled()).thenReturn(false);
+
+ mTile = new HotspotTile(
+ mHost,
+ mTestableLooper.getLooper(),
+ new Handler(mTestableLooper.getLooper()),
+ new FalsingManagerFake(),
+ mock(MetricsLogger.class),
+ mock(StatusBarStateController.class),
+ mock(ActivityStarter.class),
+ mock(QSLogger.class),
+ mHotspotController,
+ mDataSaverController
+ );
+
+ mTile.initialize();
+ mTestableLooper.processAllMessages();
+ }
+
+ @Test
+ public void handleUpdateState_wifiTetheringIsAllowed_stateIsNotUnavailable() {
+ MockitoSession mockitoSession = ExtendedMockito.mockitoSession()
+ .spyStatic(WifiEnterpriseRestrictionUtils.class)
+ .startMocking();
+ when(WifiEnterpriseRestrictionUtils.isWifiTetheringAllowed(mContext)).thenReturn(true);
+
+ mTile.handleUpdateState(mState, null);
+
+ assertThat(mState.state).isNotEqualTo(Tile.STATE_UNAVAILABLE);
+ assertThat(String.valueOf(mState.secondaryLabel))
+ .isNotEqualTo(mContext.getString(R.string.wifitrackerlib_admin_restricted_network));
+ mockitoSession.finishMocking();
+ }
+
+ @Test
+ public void handleUpdateState_wifiTetheringIsDisallowed_stateIsUnavailable() {
+ MockitoSession mockitoSession = ExtendedMockito.mockitoSession()
+ .spyStatic(WifiEnterpriseRestrictionUtils.class)
+ .startMocking();
+ when(WifiEnterpriseRestrictionUtils.isWifiTetheringAllowed(mContext)).thenReturn(false);
+
+ mTile.handleUpdateState(mState, null);
+
+ assertThat(mState.state).isEqualTo(Tile.STATE_UNAVAILABLE);
+ assertThat(String.valueOf(mState.secondaryLabel))
+ .isEqualTo(mContext.getString(R.string.wifitrackerlib_admin_restricted_network));
+ mockitoSession.finishMocking();
+ }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/shared/animation/UnfoldConstantTranslateAnimatorTest.kt b/packages/SystemUI/tests/src/com/android/systemui/shared/animation/UnfoldConstantTranslateAnimatorTest.kt
index 32314159f865..a4a89a4c67f2 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/shared/animation/UnfoldConstantTranslateAnimatorTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/shared/animation/UnfoldConstantTranslateAnimatorTest.kt
@@ -1,3 +1,17 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the
+ * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
package com.android.systemui.shared.animation
import android.testing.AndroidTestingRunner
@@ -7,31 +21,24 @@ import androidx.test.filters.SmallTest
import com.android.systemui.SysuiTestCase
import com.android.systemui.shared.animation.UnfoldConstantTranslateAnimator.Direction
import com.android.systemui.shared.animation.UnfoldConstantTranslateAnimator.ViewIdToTranslate
-import com.android.systemui.unfold.UnfoldTransitionProgressProvider
-import com.android.systemui.unfold.UnfoldTransitionProgressProvider.TransitionProgressListener
+import com.android.systemui.unfold.TestUnfoldTransitionProvider
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
-import org.mockito.ArgumentCaptor
-import org.mockito.Captor
import org.mockito.Mock
-import org.mockito.Mockito.verify
-import org.mockito.Mockito.`when` as whenever
import org.mockito.MockitoAnnotations
+import org.mockito.Mockito.`when` as whenever
@SmallTest
@RunWith(AndroidTestingRunner::class)
class UnfoldConstantTranslateAnimatorTest : SysuiTestCase() {
- @Mock private lateinit var progressProvider: UnfoldTransitionProgressProvider
+ private val progressProvider = TestUnfoldTransitionProvider()
@Mock private lateinit var parent: ViewGroup
- @Captor private lateinit var progressListenerCaptor: ArgumentCaptor<TransitionProgressListener>
-
private lateinit var animator: UnfoldConstantTranslateAnimator
- private lateinit var progressListener: TransitionProgressListener
private val viewsIdToRegister =
setOf(
@@ -46,17 +53,14 @@ class UnfoldConstantTranslateAnimatorTest : SysuiTestCase() {
UnfoldConstantTranslateAnimator(viewsIdToRegister, progressProvider)
animator.init(parent, MAX_TRANSLATION)
-
- verify(progressProvider).addCallback(progressListenerCaptor.capture())
- progressListener = progressListenerCaptor.value
}
@Test
fun onTransition_noMatchingIds() {
// GIVEN no views matching any ids
// WHEN the transition starts
- progressListener.onTransitionStarted()
- progressListener.onTransitionProgress(.1f)
+ progressProvider.onTransitionStarted()
+ progressProvider.onTransitionProgress(.1f)
// THEN nothing... no exceptions
}
@@ -86,22 +90,22 @@ class UnfoldConstantTranslateAnimatorTest : SysuiTestCase() {
// Compare values as ints because -0f != 0f
// WHEN the transition starts
- progressListener.onTransitionStarted()
- progressListener.onTransitionProgress(0f)
+ progressProvider.onTransitionStarted()
+ progressProvider.onTransitionProgress(0f)
list.forEach { (view, direction) ->
assertEquals((-MAX_TRANSLATION * direction).toInt(), view.translationX.toInt())
}
// WHEN the transition progresses, translation is updated
- progressListener.onTransitionProgress(.5f)
+ progressProvider.onTransitionProgress(.5f)
list.forEach { (view, direction) ->
assertEquals((-MAX_TRANSLATION / 2f * direction).toInt(), view.translationX.toInt())
}
// WHEN the transition ends, translation is completed
- progressListener.onTransitionProgress(1f)
- progressListener.onTransitionFinished()
+ progressProvider.onTransitionProgress(1f)
+ progressProvider.onTransitionFinished()
list.forEach { (view, _) -> assertEquals(0, view.translationX.toInt()) }
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/LSShadeTransitionLoggerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/LSShadeTransitionLoggerTest.kt
index 6971c63ed6d4..8cb530c355bd 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/LSShadeTransitionLoggerTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/LSShadeTransitionLoggerTest.kt
@@ -30,7 +30,7 @@ class LSShadeTransitionLoggerTest : SysuiTestCase() {
@Before
fun setup() {
logger = LSShadeTransitionLogger(
- LogBuffer("Test", 10, 10, mock()),
+ LogBuffer("Test", 10, mock()),
gestureLogger,
displayMetrics)
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/LockscreenShadeTransitionControllerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/LockscreenShadeTransitionControllerTest.kt
index 562c97017862..73e574eddd17 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/LockscreenShadeTransitionControllerTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/LockscreenShadeTransitionControllerTest.kt
@@ -130,8 +130,8 @@ class LockscreenShadeTransitionControllerTest : SysuiTestCase() {
whenever(statusbarStateController.state).thenReturn(StatusBarState.KEYGUARD)
whenever(nsslController.isInLockedDownShade).thenReturn(false)
whenever(qS.isFullyCollapsed).thenReturn(true)
- whenever(lockScreenUserManager.userAllowsPrivateNotificationsInPublic(anyInt())).thenReturn(
- true)
+ whenever(lockScreenUserManager.sensitiveNotifsNeedRedactionInPublic(anyInt()))
+ .thenReturn(false)
whenever(lockScreenUserManager.shouldShowLockscreenNotifications()).thenReturn(true)
whenever(lockScreenUserManager.isLockscreenPublicMode(anyInt())).thenReturn(true)
whenever(falsingCollector.shouldEnforceBouncer()).thenReturn(false)
@@ -207,8 +207,8 @@ class LockscreenShadeTransitionControllerTest : SysuiTestCase() {
@Test
fun testTriggeringBouncerWhenPrivateNotificationsArentAllowed() {
- whenever(lockScreenUserManager.userAllowsPrivateNotificationsInPublic(anyInt())).thenReturn(
- false)
+ whenever(lockScreenUserManager.sensitiveNotifsNeedRedactionInPublic(anyInt()))
+ .thenReturn(true)
transitionController.goToLockedShade(null)
verify(statusbarStateController, never()).setState(anyInt())
verify(statusbarStateController).setLeaveOpenOnKeyguardHide(true)
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationLockscreenUserManagerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationLockscreenUserManagerTest.java
index 7687d1204541..18937e784ed1 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationLockscreenUserManagerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationLockscreenUserManagerTest.java
@@ -53,11 +53,13 @@ import android.testing.TestableLooper;
import androidx.test.filters.SmallTest;
+import com.android.keyguard.KeyguardUpdateMonitor;
import com.android.systemui.Dependency;
import com.android.systemui.SysuiTestCase;
import com.android.systemui.broadcast.BroadcastDispatcher;
import com.android.systemui.dump.DumpManager;
import com.android.systemui.plugins.statusbar.StatusBarStateController;
+import com.android.systemui.recents.OverviewProxyService;
import com.android.systemui.statusbar.NotificationLockscreenUserManager.KeyguardNotificationSuppressor;
import com.android.systemui.statusbar.notification.NotificationEntryManager;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
@@ -106,6 +108,10 @@ public class NotificationLockscreenUserManagerTest extends SysuiTestCase {
private BroadcastDispatcher mBroadcastDispatcher;
@Mock
private KeyguardStateController mKeyguardStateController;
+ @Mock
+ private KeyguardUpdateMonitor mKeyguardUpdateMonitor;
+ @Mock
+ private OverviewProxyService mOverviewProxyService;
private UserInfo mCurrentUser;
private UserInfo mSecondaryUser;
@@ -119,7 +125,6 @@ public class NotificationLockscreenUserManagerTest extends SysuiTestCase {
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
- mDependency.injectTestDependency(NotificationEntryManager.class, mEntryManager);
int currentUserId = ActivityManager.getCurrentUser();
mSettings = new FakeSettings();
@@ -212,7 +217,7 @@ public class NotificationLockscreenUserManagerTest extends SysuiTestCase {
mLockscreenUserManager.getLockscreenSettingsObserverForTest().onChange(false);
// THEN current user's notification is redacted
- assertTrue(mLockscreenUserManager.needsRedaction(mCurrentUserNotif));
+ assertTrue(mLockscreenUserManager.notifNeedsRedactionInPublic(mCurrentUserNotif));
}
@Test
@@ -223,7 +228,7 @@ public class NotificationLockscreenUserManagerTest extends SysuiTestCase {
mLockscreenUserManager.getLockscreenSettingsObserverForTest().onChange(false);
// THEN current user's notification isn't redacted
- assertFalse(mLockscreenUserManager.needsRedaction(mCurrentUserNotif));
+ assertFalse(mLockscreenUserManager.notifNeedsRedactionInPublic(mCurrentUserNotif));
}
@Test
@@ -234,7 +239,7 @@ public class NotificationLockscreenUserManagerTest extends SysuiTestCase {
mLockscreenUserManager.getLockscreenSettingsObserverForTest().onChange(false);
// THEN work profile notification is redacted
- assertTrue(mLockscreenUserManager.needsRedaction(mWorkProfileNotif));
+ assertTrue(mLockscreenUserManager.notifNeedsRedactionInPublic(mWorkProfileNotif));
}
@Test
@@ -245,7 +250,7 @@ public class NotificationLockscreenUserManagerTest extends SysuiTestCase {
mLockscreenUserManager.getLockscreenSettingsObserverForTest().onChange(false);
// THEN work profile notification isn't redacted
- assertFalse(mLockscreenUserManager.needsRedaction(mWorkProfileNotif));
+ assertFalse(mLockscreenUserManager.notifNeedsRedactionInPublic(mWorkProfileNotif));
}
@Test
@@ -260,11 +265,11 @@ public class NotificationLockscreenUserManagerTest extends SysuiTestCase {
mLockscreenUserManager.getLockscreenSettingsObserverForTest().onChange(false);
// THEN the work profile notification doesn't need to be redacted
- assertFalse(mLockscreenUserManager.needsRedaction(mWorkProfileNotif));
+ assertFalse(mLockscreenUserManager.notifNeedsRedactionInPublic(mWorkProfileNotif));
// THEN the current user and secondary user notifications do need to be redacted
- assertTrue(mLockscreenUserManager.needsRedaction(mCurrentUserNotif));
- assertTrue(mLockscreenUserManager.needsRedaction(mSecondaryUserNotif));
+ assertTrue(mLockscreenUserManager.notifNeedsRedactionInPublic(mCurrentUserNotif));
+ assertTrue(mLockscreenUserManager.notifNeedsRedactionInPublic(mSecondaryUserNotif));
}
@Test
@@ -279,11 +284,11 @@ public class NotificationLockscreenUserManagerTest extends SysuiTestCase {
mLockscreenUserManager.getLockscreenSettingsObserverForTest().onChange(false);
// THEN the work profile notification needs to be redacted
- assertTrue(mLockscreenUserManager.needsRedaction(mWorkProfileNotif));
+ assertTrue(mLockscreenUserManager.notifNeedsRedactionInPublic(mWorkProfileNotif));
// THEN the current user and secondary user notifications don't need to be redacted
- assertFalse(mLockscreenUserManager.needsRedaction(mCurrentUserNotif));
- assertFalse(mLockscreenUserManager.needsRedaction(mSecondaryUserNotif));
+ assertFalse(mLockscreenUserManager.notifNeedsRedactionInPublic(mCurrentUserNotif));
+ assertFalse(mLockscreenUserManager.notifNeedsRedactionInPublic(mSecondaryUserNotif));
}
@Test
@@ -298,7 +303,7 @@ public class NotificationLockscreenUserManagerTest extends SysuiTestCase {
// THEN the secondary profile notification still needs to be redacted because the current
// user's setting takes precedence
- assertTrue(mLockscreenUserManager.needsRedaction(mSecondaryUserNotif));
+ assertTrue(mLockscreenUserManager.notifNeedsRedactionInPublic(mSecondaryUserNotif));
}
@Test
@@ -418,9 +423,12 @@ public class NotificationLockscreenUserManagerTest extends SysuiTestCase {
context,
mBroadcastDispatcher,
mDevicePolicyManager,
+ mKeyguardUpdateMonitor,
+ () -> mEntryManager,
+ () -> mOverviewProxyService,
mUserManager,
- (() -> mVisibilityProvider),
- (() -> mNotifCollection),
+ () -> mVisibilityProvider,
+ () -> mNotifCollection,
mClickNotifier,
NotificationLockscreenUserManagerTest.this.mKeyguardManager,
mStatusBarStateController,
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/DynamicPrivacyControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/DynamicPrivacyControllerTest.java
index 7d06abf5cd67..e43ae0d2b22a 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/DynamicPrivacyControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/DynamicPrivacyControllerTest.java
@@ -124,8 +124,8 @@ public class DynamicPrivacyControllerTest extends SysuiTestCase {
}
private void allowPrivateNotificationsInPublic(boolean allow) {
- when(mLockScreenUserManager.userAllowsPrivateNotificationsInPublic(anyInt())).thenReturn(
- allow);
+ when(mLockScreenUserManager.sensitiveNotifsNeedRedactionInPublic(anyInt())).thenReturn(
+ !allow);
}
@Test
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationEntryManagerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationEntryManagerTest.java
index 0fff5f5b47e5..16b0376ba1f9 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationEntryManagerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationEntryManagerTest.java
@@ -294,7 +294,8 @@ public class NotificationEntryManagerTest extends SysuiTestCase {
verify(mPresenter).updateNotificationViews(any());
verify(mEntryListener).onEntryRemoved(
- eq(mEntry), any(), eq(false) /* removedByUser */, eq(UNDEFINED_DISMISS_REASON));
+ argThat(matchEntryOnKey()), any(),
+ eq(false) /* removedByUser */, eq(UNDEFINED_DISMISS_REASON));
verify(mRow).setRemoved();
assertNull(mEntryManager.getActiveNotificationUnfiltered(mSbn.getKey()));
@@ -319,8 +320,8 @@ public class NotificationEntryManagerTest extends SysuiTestCase {
mEntryManager.removeNotification("not_a_real_key", mRankingMap, UNDEFINED_DISMISS_REASON);
- verify(mEntryListener, never()).onEntryRemoved(
- eq(mEntry), any(), eq(false) /* removedByUser */, eq(UNDEFINED_DISMISS_REASON));
+ verify(mEntryListener, never()).onEntryRemoved(argThat(matchEntryOnKey()), any(),
+ eq(false) /* removedByUser */, eq(UNDEFINED_DISMISS_REASON));
}
/** Regression test for b/201097913. */
@@ -333,10 +334,10 @@ public class NotificationEntryManagerTest extends SysuiTestCase {
// Verify that only the listener for the NEW pipeline is notified.
// Old pipeline:
verify(mEntryListener, never()).onEntryRemoved(
- argThat(matchEntryOnSbn()), any(), anyBoolean(), anyInt());
+ argThat(matchEntryOnKey()), any(), anyBoolean(), anyInt());
// New pipeline:
verify(mNotifCollectionListener).onEntryRemoved(
- argThat(matchEntryOnSbn()), anyInt());
+ argThat(matchEntryOnKey()), anyInt());
}
@Test
@@ -457,7 +458,7 @@ public class NotificationEntryManagerTest extends SysuiTestCase {
// THEN the notification is retained
assertNotNull(mEntryManager.getActiveNotificationUnfiltered(mSbn.getKey()));
verify(mEntryListener, never()).onEntryRemoved(
- eq(mEntry), any(), eq(false), eq(UNDEFINED_DISMISS_REASON));
+ argThat(matchEntryOnKey()), any(), eq(false), eq(UNDEFINED_DISMISS_REASON));
}
@Test
@@ -476,7 +477,7 @@ public class NotificationEntryManagerTest extends SysuiTestCase {
// THEN the notification is removed
assertNull(mEntryManager.getActiveNotificationUnfiltered(mSbn.getKey()));
verify(mEntryListener).onEntryRemoved(
- eq(mEntry), any(), eq(false), eq(UNDEFINED_DISMISS_REASON));
+ argThat(matchEntryOnKey()), any(), eq(false), eq(UNDEFINED_DISMISS_REASON));
}
@Test
@@ -541,7 +542,7 @@ public class NotificationEntryManagerTest extends SysuiTestCase {
// GIVEN interceptor that intercepts that entry
when(mRemoveInterceptor.onNotificationRemoveRequested(
- eq(mEntry.getKey()), eq(mEntry), anyInt()))
+ eq(mEntry.getKey()), argThat(matchEntryOnKey()), anyInt()))
.thenReturn(true);
// WHEN the notification is removed
@@ -549,7 +550,7 @@ public class NotificationEntryManagerTest extends SysuiTestCase {
// THEN the interceptor intercepts & the entry is not removed & no listeners are called
assertNotNull(mEntryManager.getActiveNotificationUnfiltered(mSbn.getKey()));
- verify(mEntryListener, never()).onEntryRemoved(eq(mEntry),
+ verify(mEntryListener, never()).onEntryRemoved(argThat(matchEntryOnKey()),
any(NotificationVisibility.class), anyBoolean(), eq(UNDEFINED_DISMISS_REASON));
}
@@ -560,7 +561,7 @@ public class NotificationEntryManagerTest extends SysuiTestCase {
// GIVEN interceptor that doesn't intercept
when(mRemoveInterceptor.onNotificationRemoveRequested(
- eq(mEntry.getKey()), eq(mEntry), anyInt()))
+ eq(mEntry.getKey()), argThat(matchEntryOnKey()), anyInt()))
.thenReturn(false);
// WHEN the notification is removed
@@ -568,7 +569,7 @@ public class NotificationEntryManagerTest extends SysuiTestCase {
// THEN the interceptor intercepts & the entry is not removed & no listeners are called
assertNull(mEntryManager.getActiveNotificationUnfiltered(mSbn.getKey()));
- verify(mEntryListener, atLeastOnce()).onEntryRemoved(eq(mEntry),
+ verify(mEntryListener, atLeastOnce()).onEntryRemoved(argThat(matchEntryOnKey()),
any(NotificationVisibility.class), anyBoolean(), eq(UNDEFINED_DISMISS_REASON));
}
@@ -663,9 +664,8 @@ public class NotificationEntryManagerTest extends SysuiTestCase {
PendingIntent.FLAG_IMMUTABLE)).build();
}
- // TODO(b/201321631): Update more tests to use this function instead of eq(mEntry).
- private ArgumentMatcher<NotificationEntry> matchEntryOnSbn() {
- return e -> e.getSbn().equals(mSbn);
+ private ArgumentMatcher<NotificationEntry> matchEntryOnKey() {
+ return e -> e.getKey().equals(mEntry.getKey());
}
private static class FakeNotificationLifetimeExtender implements NotificationLifetimeExtender {
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/NotifCollectionTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/NotifCollectionTest.java
index 706800940fd1..958d54230f1c 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/NotifCollectionTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/NotifCollectionTest.java
@@ -32,6 +32,8 @@ import static com.android.systemui.statusbar.notification.collection.Notificatio
import static com.android.systemui.statusbar.notification.collection.NotificationEntry.DismissState.NOT_DISMISSED;
import static com.android.systemui.statusbar.notification.collection.NotificationEntry.DismissState.PARENT_DISMISSED;
+import static com.google.common.truth.Truth.assertThat;
+
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
@@ -47,6 +49,7 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import static java.util.Collections.singletonList;
@@ -180,13 +183,14 @@ public class NotifCollectionTest extends SysuiTestCase {
@Test
public void testGetGroupSummary() {
- assertEquals(null, mCollection.getGroupSummary("group"));
- NotifEvent summary = mNoMan.postNotif(
- buildNotif(TEST_PACKAGE, 0)
- .setGroup(mContext, "group")
- .setGroupSummary(mContext, true));
+ final NotificationEntryBuilder entryBuilder = buildNotif(TEST_PACKAGE, 0)
+ .setGroup(mContext, "group")
+ .setGroupSummary(mContext, true);
+ final String groupKey = entryBuilder.build().getSbn().getGroupKey();
+ assertEquals(null, mCollection.getGroupSummary(groupKey));
+ NotifEvent summary = mNoMan.postNotif(entryBuilder);
- final NotificationEntry entry = mCollection.getGroupSummary("group");
+ final NotificationEntry entry = mCollection.getGroupSummary(groupKey);
assertEquals(summary.key, entry.getKey());
assertEquals(summary.sbn, entry.getSbn());
assertEquals(summary.ranking, entry.getRanking());
@@ -194,9 +198,9 @@ public class NotifCollectionTest extends SysuiTestCase {
@Test
public void testIsOnlyChildInGroup() {
- NotifEvent notif1 = mNoMan.postNotif(
- buildNotif(TEST_PACKAGE, 1)
- .setGroup(mContext, "group"));
+ final NotificationEntryBuilder entryBuilder = buildNotif(TEST_PACKAGE, 1)
+ .setGroup(mContext, "group");
+ NotifEvent notif1 = mNoMan.postNotif(entryBuilder);
final NotificationEntry entry = mCollection.getEntry(notif1.key);
assertTrue(mCollection.isOnlyChildInGroup(entry));
@@ -1488,6 +1492,55 @@ public class NotifCollectionTest extends SysuiTestCase {
}
@Test
+ public void testRegisterFutureDismissal() throws RemoteException {
+ // GIVEN a pipeline with one notification
+ NotifEvent notifEvent = mNoMan.postNotif(buildNotif(TEST_PACKAGE, 47, "myTag"));
+ NotificationEntry entry = requireNonNull(mCollection.getEntry(notifEvent.key));
+ clearInvocations(mCollectionListener);
+
+ // WHEN registering a future dismissal, nothing happens right away
+ final Runnable onDismiss = mCollection.registerFutureDismissal(entry, REASON_CLICK,
+ NotifCollectionTest::defaultStats);
+ verifyNoMoreInteractions(mCollectionListener);
+
+ // WHEN finally dismissing
+ onDismiss.run();
+ verify(mStatusBarService).onNotificationClear(any(), anyInt(), eq(notifEvent.key),
+ anyInt(), anyInt(), any());
+ verifyNoMoreInteractions(mStatusBarService);
+ verifyNoMoreInteractions(mCollectionListener);
+ }
+
+ @Test
+ public void testRegisterFutureDismissalWithRetractionAndRepost() {
+ // GIVEN a pipeline with one notification
+ NotifEvent notifEvent = mNoMan.postNotif(buildNotif(TEST_PACKAGE, 47, "myTag"));
+ NotificationEntry entry = requireNonNull(mCollection.getEntry(notifEvent.key));
+ clearInvocations(mCollectionListener);
+
+ // WHEN registering a future dismissal, nothing happens right away
+ final Runnable onDismiss = mCollection.registerFutureDismissal(entry, REASON_CLICK,
+ NotifCollectionTest::defaultStats);
+ verifyNoMoreInteractions(mCollectionListener);
+
+ // WHEN retracting the notification, and then reposting
+ mNoMan.retractNotif(notifEvent.sbn, REASON_CLICK);
+ mNoMan.postNotif(buildNotif(TEST_PACKAGE, 47, "myTag"));
+ clearInvocations(mCollectionListener);
+
+ // KNOWING that the entry in the collection is different now
+ assertThat(mCollection.getEntry(notifEvent.key)).isNotSameInstanceAs(entry);
+
+ // WHEN finally dismissing
+ onDismiss.run();
+
+ // VERIFY that nothing happens; the notification should not be removed
+ verifyNoMoreInteractions(mCollectionListener);
+ assertThat(mCollection.getEntry(notifEvent.key)).isNotNull();
+ verifyNoMoreInteractions(mStatusBarService);
+ }
+
+ @Test
public void testCannotDismissOngoingNotificationChildren() {
// GIVEN an ongoing notification
final NotificationEntry container = new NotificationEntryBuilder()
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/ShadeListBuilderTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/ShadeListBuilderTest.java
index 9ea1813377a0..4e7e79f2cb26 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/ShadeListBuilderTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/ShadeListBuilderTest.java
@@ -1528,6 +1528,34 @@ public class ShadeListBuilderTest extends SysuiTestCase {
}
@Test
+ public void testContiguousSections() {
+ mListBuilder.setSectioners(List.of(
+ new PackageSectioner("pkg", 1),
+ new PackageSectioner("pkg", 1),
+ new PackageSectioner("pkg", 3),
+ new PackageSectioner("pkg", 2)
+ ));
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void testNonContiguousSections() {
+ mListBuilder.setSectioners(List.of(
+ new PackageSectioner("pkg", 1),
+ new PackageSectioner("pkg", 1),
+ new PackageSectioner("pkg", 3),
+ new PackageSectioner("pkg", 1)
+ ));
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void testBucketZeroNotAllowed() {
+ mListBuilder.setSectioners(List.of(
+ new PackageSectioner("pkg", 0),
+ new PackageSectioner("pkg", 1)
+ ));
+ }
+
+ @Test
public void testStabilizeGroupsDelayedSummaryRendersAllNotifsTopLevel() {
// GIVEN group children posted without a summary
addGroupChild(0, PACKAGE_1, GROUP_1);
@@ -2189,7 +2217,11 @@ public class ShadeListBuilderTest extends SysuiTestCase {
}
PackageSectioner(String pkg) {
- super("PackageSection_" + pkg, 0);
+ this(pkg, 0);
+ }
+
+ PackageSectioner(String pkg, int bucket) {
+ super("PackageSection_" + pkg, bucket);
mPackages = List.of(pkg);
mComparator = null;
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/ActivityLaunchAnimCoordinatorTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/ActivityLaunchAnimCoordinatorTest.kt
deleted file mode 100644
index c6c043aafb20..000000000000
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/ActivityLaunchAnimCoordinatorTest.kt
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- * Copyright (C) 2022 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.systemui.statusbar.notification.collection.coordinator
-
-import androidx.test.filters.SmallTest
-import com.android.systemui.SysuiTestCase
-import com.android.systemui.statusbar.notification.collection.NotifPipeline
-import com.android.systemui.statusbar.notification.collection.NotificationEntry
-import com.android.systemui.statusbar.notification.collection.coordinator.dagger.CoordinatorScope
-import com.android.systemui.statusbar.notification.collection.notifcollection.NotifLifetimeExtender
-import com.android.systemui.statusbar.phone.NotifActivityLaunchEvents
-import com.android.systemui.util.mockito.mock
-import com.android.systemui.util.mockito.withArgCaptor
-import dagger.BindsInstance
-import dagger.Component
-import org.junit.Assert.assertFalse
-import org.junit.Assert.assertTrue
-import org.junit.Test
-import org.mockito.Mockito.never
-import org.mockito.Mockito.verify
-import org.mockito.Mockito.`when` as whenever
-
-@SmallTest
-class ActivityLaunchAnimCoordinatorTest : SysuiTestCase() {
-
- val activityLaunchEvents: NotifActivityLaunchEvents = mock()
- val pipeline: NotifPipeline = mock()
-
- val coordinator: ActivityLaunchAnimCoordinator =
- DaggerTestActivityStarterCoordinatorComponent
- .factory()
- .create(activityLaunchEvents)
- .coordinator
-
- @Test
- fun testNoLifetimeExtensionIfNoAssociatedActivityLaunch() {
- coordinator.attach(pipeline)
- val lifetimeExtender = withArgCaptor<NotifLifetimeExtender> {
- verify(pipeline).addNotificationLifetimeExtender(capture())
- }
- val fakeEntry = mock<NotificationEntry>().also {
- whenever(it.key).thenReturn("0")
- }
- assertFalse(lifetimeExtender.maybeExtendLifetime(fakeEntry, 0))
- }
-
- @Test
- fun testNoLifetimeExtensionIfAssociatedActivityLaunchAlreadyEnded() {
- coordinator.attach(pipeline)
- val lifetimeExtender = withArgCaptor<NotifLifetimeExtender> {
- verify(pipeline).addNotificationLifetimeExtender(capture())
- }
- val eventListener = withArgCaptor<NotifActivityLaunchEvents.Listener> {
- verify(activityLaunchEvents).registerListener(capture())
- }
- val fakeEntry = mock<NotificationEntry>().also {
- whenever(it.key).thenReturn("0")
- }
- eventListener.onStartLaunchNotifActivity(fakeEntry)
- eventListener.onFinishLaunchNotifActivity(fakeEntry)
- assertFalse(lifetimeExtender.maybeExtendLifetime(fakeEntry, 0))
- }
-
- @Test
- fun testLifetimeExtensionWhileActivityLaunchInProgress() {
- coordinator.attach(pipeline)
- val lifetimeExtender = withArgCaptor<NotifLifetimeExtender> {
- verify(pipeline).addNotificationLifetimeExtender(capture())
- }
- val eventListener = withArgCaptor<NotifActivityLaunchEvents.Listener> {
- verify(activityLaunchEvents).registerListener(capture())
- }
- val onEndLifetimeExtensionCallback =
- mock<NotifLifetimeExtender.OnEndLifetimeExtensionCallback>()
- lifetimeExtender.setCallback(onEndLifetimeExtensionCallback)
-
- val fakeEntry = mock<NotificationEntry>().also {
- whenever(it.key).thenReturn("0")
- }
- eventListener.onStartLaunchNotifActivity(fakeEntry)
- assertTrue(lifetimeExtender.maybeExtendLifetime(fakeEntry, 0))
-
- eventListener.onFinishLaunchNotifActivity(fakeEntry)
- verify(onEndLifetimeExtensionCallback).onEndLifetimeExtension(lifetimeExtender, fakeEntry)
- }
-
- @Test
- fun testCancelLifetimeExtensionDoesNotInvokeCallback() {
- coordinator.attach(pipeline)
- val lifetimeExtender = withArgCaptor<NotifLifetimeExtender> {
- verify(pipeline).addNotificationLifetimeExtender(capture())
- }
- val eventListener = withArgCaptor<NotifActivityLaunchEvents.Listener> {
- verify(activityLaunchEvents).registerListener(capture())
- }
- val onEndLifetimeExtensionCallback =
- mock<NotifLifetimeExtender.OnEndLifetimeExtensionCallback>()
- lifetimeExtender.setCallback(onEndLifetimeExtensionCallback)
-
- val fakeEntry = mock<NotificationEntry>().also {
- whenever(it.key).thenReturn("0")
- }
- eventListener.onStartLaunchNotifActivity(fakeEntry)
- assertTrue(lifetimeExtender.maybeExtendLifetime(fakeEntry, 0))
-
- lifetimeExtender.cancelLifetimeExtension(fakeEntry)
- eventListener.onFinishLaunchNotifActivity(fakeEntry)
- verify(onEndLifetimeExtensionCallback, never())
- .onEndLifetimeExtension(lifetimeExtender, fakeEntry)
- }
-}
-
-@CoordinatorScope
-@Component(modules = [ActivityLaunchAnimCoordinatorModule::class])
-interface TestActivityStarterCoordinatorComponent {
- val coordinator: ActivityLaunchAnimCoordinator
-
- @Component.Factory
- interface Factory {
- fun create(
- @BindsInstance activityLaunchEvents: NotifActivityLaunchEvents
- ): TestActivityStarterCoordinatorComponent
- }
-}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/RankingCoordinatorTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/RankingCoordinatorTest.java
index f4d8405a796e..5c2f5fa6bc1c 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/RankingCoordinatorTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/RankingCoordinatorTest.java
@@ -23,7 +23,6 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@@ -33,7 +32,6 @@ import android.app.Notification;
import android.app.NotificationManager;
import android.testing.AndroidTestingRunner;
-import androidx.annotation.Nullable;
import androidx.test.filters.SmallTest;
import com.android.systemui.SysuiTestCase;
@@ -41,7 +39,6 @@ import com.android.systemui.plugins.statusbar.StatusBarStateController;
import com.android.systemui.statusbar.RankingBuilder;
import com.android.systemui.statusbar.SbnBuilder;
import com.android.systemui.statusbar.notification.SectionClassifier;
-import com.android.systemui.statusbar.notification.collection.ListEntry;
import com.android.systemui.statusbar.notification.collection.NotifPipeline;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder;
@@ -49,7 +46,6 @@ import com.android.systemui.statusbar.notification.collection.listbuilder.plugga
import com.android.systemui.statusbar.notification.collection.listbuilder.pluggable.NotifSectioner;
import com.android.systemui.statusbar.notification.collection.provider.HighPriorityProvider;
import com.android.systemui.statusbar.notification.collection.render.NodeController;
-import com.android.systemui.statusbar.notification.collection.render.SectionHeaderController;
import org.junit.Before;
import org.junit.Test;
@@ -72,7 +68,6 @@ public class RankingCoordinatorTest extends SysuiTestCase {
@Mock private NotifPipeline mNotifPipeline;
@Mock private NodeController mAlertingHeaderController;
@Mock private NodeController mSilentNodeController;
- @Mock private SectionHeaderController mSilentHeaderController;
@Captor private ArgumentCaptor<NotifFilter> mNotifFilterCaptor;
@@ -94,7 +89,6 @@ public class RankingCoordinatorTest extends SysuiTestCase {
mHighPriorityProvider,
mSectionClassifier,
mAlertingHeaderController,
- mSilentHeaderController,
mSilentNodeController);
mEntry = spy(new NotificationEntryBuilder().build());
mEntry.setRanking(getRankingForUnfilteredNotif().build());
@@ -112,25 +106,6 @@ public class RankingCoordinatorTest extends SysuiTestCase {
}
@Test
- public void testSilentHeaderClearableChildrenUpdate() {
- ListEntry listEntry = new ListEntry(mEntry.getKey(), 0L) {
- @Nullable
- @Override
- public NotificationEntry getRepresentativeEntry() {
- return mEntry;
- }
- };
- setRankingAmbient(false);
- setSbnClearable(true);
- mSilentSectioner.onEntriesUpdated(Arrays.asList(listEntry));
- verify(mSilentHeaderController).setClearSectionEnabled(eq(true));
-
- setSbnClearable(false);
- mSilentSectioner.onEntriesUpdated(Arrays.asList(listEntry));
- verify(mSilentHeaderController).setClearSectionEnabled(eq(false));
- }
-
- @Test
public void testUnfilteredState() {
// GIVEN no suppressed visual effects + app not suspended
mEntry.setRanking(getRankingForUnfilteredNotif().build());
@@ -225,46 +200,6 @@ public class RankingCoordinatorTest extends SysuiTestCase {
assertInSection(mEntry, mSilentSectioner);
}
- @Test
- public void testClearableSilentSection() {
- when(mHighPriorityProvider.isHighPriority(mEntry)).thenReturn(false);
- setSbnClearable(true);
- setRankingAmbient(false);
- mSilentSectioner.onEntriesUpdated(Arrays.asList(mEntry));
- verify(mSilentHeaderController).setClearSectionEnabled(eq(true));
- }
-
- @Test
- public void testClearableMinimizedSection() {
- when(mHighPriorityProvider.isHighPriority(mEntry)).thenReturn(false);
- setSbnClearable(true);
- setRankingAmbient(true);
- mMinimizedSectioner.onEntriesUpdated(Arrays.asList(mEntry));
- verify(mSilentHeaderController).setClearSectionEnabled(eq(true));
- }
-
- @Test
- public void testNotClearableSilentSection() {
- setSbnClearable(false);
- when(mHighPriorityProvider.isHighPriority(mEntry)).thenReturn(false);
- setRankingAmbient(false);
- mSilentSectioner.onEntriesUpdated(Arrays.asList(mEntry));
- mMinimizedSectioner.onEntriesUpdated(Arrays.asList(mEntry));
- mAlertingSectioner.onEntriesUpdated(Arrays.asList(mEntry));
- verify(mSilentHeaderController, times(2)).setClearSectionEnabled(eq(false));
- }
-
- @Test
- public void testNotClearableMinimizedSection() {
- setSbnClearable(false);
- when(mHighPriorityProvider.isHighPriority(mEntry)).thenReturn(false);
- setRankingAmbient(true);
- mSilentSectioner.onEntriesUpdated(Arrays.asList(mEntry));
- mMinimizedSectioner.onEntriesUpdated(Arrays.asList(mEntry));
- mAlertingSectioner.onEntriesUpdated(Arrays.asList(mEntry));
- verify(mSilentHeaderController, times(2)).setClearSectionEnabled(eq(false));
- }
-
private void assertInSection(NotificationEntry entry, NotifSectioner section) {
for (NotifSectioner current: mSections) {
if (current == section) {
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/SensitiveContentCoordinatorTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/SensitiveContentCoordinatorTest.kt
deleted file mode 100644
index a2d8e3ddba24..000000000000
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/SensitiveContentCoordinatorTest.kt
+++ /dev/null
@@ -1,268 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.systemui.statusbar.notification.collection.coordinator
-
-import android.os.UserHandle
-import android.service.notification.StatusBarNotification
-import androidx.test.filters.SmallTest
-import com.android.keyguard.KeyguardUpdateMonitor
-import com.android.systemui.SysuiTestCase
-import com.android.systemui.plugins.statusbar.StatusBarStateController
-import com.android.systemui.statusbar.NotificationLockscreenUserManager
-import com.android.systemui.statusbar.StatusBarState
-import com.android.systemui.statusbar.notification.DynamicPrivacyController
-import com.android.systemui.statusbar.notification.collection.ListEntry
-import com.android.systemui.statusbar.notification.collection.NotifPipeline
-import com.android.systemui.statusbar.notification.collection.NotificationEntry
-import com.android.systemui.statusbar.notification.collection.coordinator.dagger.CoordinatorScope
-import com.android.systemui.statusbar.notification.collection.listbuilder.OnBeforeRenderListListener
-import com.android.systemui.statusbar.notification.collection.listbuilder.pluggable.Invalidator
-import com.android.systemui.statusbar.notification.collection.listbuilder.pluggable.Pluggable
-import com.android.systemui.statusbar.policy.KeyguardStateController
-import com.android.systemui.util.mockito.any
-import com.android.systemui.util.mockito.mock
-import com.android.systemui.util.mockito.withArgCaptor
-import dagger.BindsInstance
-import dagger.Component
-import org.junit.Test
-import org.mockito.Mockito.never
-import org.mockito.Mockito.verify
-import org.mockito.Mockito.`when` as whenever
-
-@SmallTest
-class SensitiveContentCoordinatorTest : SysuiTestCase() {
-
- val dynamicPrivacyController: DynamicPrivacyController = mock()
- val lockscreenUserManager: NotificationLockscreenUserManager = mock()
- val pipeline: NotifPipeline = mock()
- val keyguardUpdateMonitor: KeyguardUpdateMonitor = mock()
- val statusBarStateController: StatusBarStateController = mock()
- val keyguardStateController: KeyguardStateController = mock()
-
- val coordinator: SensitiveContentCoordinator =
- DaggerTestSensitiveContentCoordinatorComponent
- .factory()
- .create(
- dynamicPrivacyController,
- lockscreenUserManager,
- keyguardUpdateMonitor,
- statusBarStateController,
- keyguardStateController)
- .coordinator
-
- @Test
- fun onDynamicPrivacyChanged_invokeInvalidationListener() {
- coordinator.attach(pipeline)
- val invalidator = withArgCaptor<Invalidator> {
- verify(pipeline).addPreRenderInvalidator(capture())
- }
- val dynamicPrivacyListener = withArgCaptor<DynamicPrivacyController.Listener> {
- verify(dynamicPrivacyController).addListener(capture())
- }
-
- val invalidationListener = mock<Pluggable.PluggableListener<Invalidator>>()
- invalidator.setInvalidationListener(invalidationListener)
-
- dynamicPrivacyListener.onDynamicPrivacyChanged()
-
- verify(invalidationListener).onPluggableInvalidated(invalidator)
- }
-
- @Test
- fun onBeforeRenderList_deviceUnlocked_notifDoesNotNeedRedaction() {
- coordinator.attach(pipeline)
- val onBeforeRenderListListener = withArgCaptor<OnBeforeRenderListListener> {
- verify(pipeline).addOnBeforeRenderListListener(capture())
- }
-
- whenever(lockscreenUserManager.currentUserId).thenReturn(1)
- whenever(lockscreenUserManager.isLockscreenPublicMode(1)).thenReturn(false)
- whenever(lockscreenUserManager.userAllowsPrivateNotificationsInPublic(1)).thenReturn(true)
- whenever(dynamicPrivacyController.isDynamicallyUnlocked).thenReturn(false)
- val entry = fakeNotification(1, false)
-
- onBeforeRenderListListener.onBeforeRenderList(listOf(entry))
-
- verify(entry.representativeEntry!!).setSensitive(false, false)
- }
-
- @Test
- fun onBeforeRenderList_deviceUnlocked_notifWouldNeedRedaction() {
- coordinator.attach(pipeline)
- val onBeforeRenderListListener = withArgCaptor<OnBeforeRenderListListener> {
- verify(pipeline).addOnBeforeRenderListListener(capture())
- }
-
- whenever(lockscreenUserManager.currentUserId).thenReturn(1)
- whenever(lockscreenUserManager.isLockscreenPublicMode(1)).thenReturn(false)
- whenever(lockscreenUserManager.userAllowsPrivateNotificationsInPublic(1)).thenReturn(true)
- whenever(dynamicPrivacyController.isDynamicallyUnlocked).thenReturn(false)
- val entry = fakeNotification(1, true)
-
- onBeforeRenderListListener.onBeforeRenderList(listOf(entry))
-
- verify(entry.representativeEntry!!).setSensitive(false, false)
- }
-
- @Test
- fun onBeforeRenderList_deviceLocked_userAllowsPublicNotifs() {
- coordinator.attach(pipeline)
- val onBeforeRenderListListener = withArgCaptor<OnBeforeRenderListListener> {
- verify(pipeline).addOnBeforeRenderListListener(capture())
- }
-
- whenever(lockscreenUserManager.currentUserId).thenReturn(1)
- whenever(lockscreenUserManager.isLockscreenPublicMode(1)).thenReturn(true)
- whenever(lockscreenUserManager.userAllowsPrivateNotificationsInPublic(1)).thenReturn(true)
- whenever(dynamicPrivacyController.isDynamicallyUnlocked).thenReturn(false)
- val entry = fakeNotification(1, false)
-
- onBeforeRenderListListener.onBeforeRenderList(listOf(entry))
-
- verify(entry.representativeEntry!!).setSensitive(false, false)
- }
-
- @Test
- fun onBeforeRenderList_deviceLocked_userDisallowsPublicNotifs_notifDoesNotNeedRedaction() {
- coordinator.attach(pipeline)
- val onBeforeRenderListListener = withArgCaptor<OnBeforeRenderListListener> {
- verify(pipeline).addOnBeforeRenderListListener(capture())
- }
-
- whenever(lockscreenUserManager.currentUserId).thenReturn(1)
- whenever(lockscreenUserManager.isLockscreenPublicMode(1)).thenReturn(true)
- whenever(lockscreenUserManager.userAllowsPrivateNotificationsInPublic(1)).thenReturn(false)
- whenever(dynamicPrivacyController.isDynamicallyUnlocked).thenReturn(false)
- val entry = fakeNotification(1, false)
-
- onBeforeRenderListListener.onBeforeRenderList(listOf(entry))
-
- verify(entry.representativeEntry!!).setSensitive(false, true)
- }
-
- @Test
- fun onBeforeRenderList_deviceLocked_notifNeedsRedaction() {
- coordinator.attach(pipeline)
- val onBeforeRenderListListener = withArgCaptor<OnBeforeRenderListListener> {
- verify(pipeline).addOnBeforeRenderListListener(capture())
- }
-
- whenever(lockscreenUserManager.currentUserId).thenReturn(1)
- whenever(lockscreenUserManager.isLockscreenPublicMode(1)).thenReturn(true)
- whenever(lockscreenUserManager.userAllowsPrivateNotificationsInPublic(1)).thenReturn(false)
- whenever(dynamicPrivacyController.isDynamicallyUnlocked).thenReturn(false)
- val entry = fakeNotification(1, true)
-
- onBeforeRenderListListener.onBeforeRenderList(listOf(entry))
-
- verify(entry.representativeEntry!!).setSensitive(true, true)
- }
-
- @Test
- fun onBeforeRenderList_deviceDynamicallyUnlocked_notifNeedsRedaction() {
- coordinator.attach(pipeline)
- val onBeforeRenderListListener = withArgCaptor<OnBeforeRenderListListener> {
- verify(pipeline).addOnBeforeRenderListListener(capture())
- }
-
- whenever(lockscreenUserManager.currentUserId).thenReturn(1)
- whenever(lockscreenUserManager.isLockscreenPublicMode(1)).thenReturn(true)
- whenever(lockscreenUserManager.userAllowsPrivateNotificationsInPublic(1)).thenReturn(false)
- whenever(dynamicPrivacyController.isDynamicallyUnlocked).thenReturn(true)
- val entry = fakeNotification(1, true)
-
- onBeforeRenderListListener.onBeforeRenderList(listOf(entry))
-
- verify(entry.representativeEntry!!).setSensitive(false, true)
- }
-
- @Test
- fun onBeforeRenderList_deviceDynamicallyUnlocked_notifUserNeedsWorkChallenge() {
- coordinator.attach(pipeline)
- val onBeforeRenderListListener = withArgCaptor<OnBeforeRenderListListener> {
- verify(pipeline).addOnBeforeRenderListListener(capture())
- }
-
- whenever(lockscreenUserManager.currentUserId).thenReturn(1)
- whenever(lockscreenUserManager.isLockscreenPublicMode(1)).thenReturn(true)
- whenever(lockscreenUserManager.userAllowsPrivateNotificationsInPublic(1)).thenReturn(false)
- whenever(dynamicPrivacyController.isDynamicallyUnlocked).thenReturn(true)
- whenever(lockscreenUserManager.needsSeparateWorkChallenge(2)).thenReturn(true)
-
- val entry = fakeNotification(2, true)
-
- onBeforeRenderListListener.onBeforeRenderList(listOf(entry))
-
- verify(entry.representativeEntry!!).setSensitive(true, true)
- }
-
- @Test
- fun onBeforeRenderList_deviceDynamicallyUnlocked_deviceBiometricBypassingLockScreen() {
- coordinator.attach(pipeline)
- val onBeforeRenderListListener = withArgCaptor<OnBeforeRenderListListener> {
- verify(pipeline).addOnBeforeRenderListListener(capture())
- }
-
- whenever(lockscreenUserManager.currentUserId).thenReturn(1)
- whenever(lockscreenUserManager.isLockscreenPublicMode(1)).thenReturn(true)
- whenever(lockscreenUserManager.userAllowsPrivateNotificationsInPublic(1)).thenReturn(false)
- whenever(dynamicPrivacyController.isDynamicallyUnlocked).thenReturn(true)
- whenever(statusBarStateController.getState()).thenReturn(StatusBarState.KEYGUARD)
- whenever(keyguardUpdateMonitor.getUserUnlockedWithBiometricAndIsBypassing(any()))
- .thenReturn(true)
-
- val entry = fakeNotification(2, true)
-
- onBeforeRenderListListener.onBeforeRenderList(listOf(entry))
-
- verify(entry.representativeEntry!!, never()).setSensitive(any(), any())
- }
-
- private fun fakeNotification(notifUserId: Int, needsRedaction: Boolean): ListEntry {
- val mockUserHandle = mock<UserHandle>().apply {
- whenever(identifier).thenReturn(notifUserId)
- }
- val mockSbn: StatusBarNotification = mock<StatusBarNotification>().apply {
- whenever(user).thenReturn(mockUserHandle)
- }
- val mockEntry = mock<NotificationEntry>().apply {
- whenever(sbn).thenReturn(mockSbn)
- }
- whenever(lockscreenUserManager.needsRedaction(mockEntry)).thenReturn(needsRedaction)
- whenever(mockEntry.rowExists()).thenReturn(true)
- return object : ListEntry("key", 0) {
- override fun getRepresentativeEntry(): NotificationEntry = mockEntry
- }
- }
-}
-
-@CoordinatorScope
-@Component(modules = [SensitiveContentCoordinatorModule::class])
-interface TestSensitiveContentCoordinatorComponent {
- val coordinator: SensitiveContentCoordinator
-
- @Component.Factory
- interface Factory {
- fun create(
- @BindsInstance dynamicPrivacyController: DynamicPrivacyController,
- @BindsInstance lockscreenUserManager: NotificationLockscreenUserManager,
- @BindsInstance keyguardUpdateMonitor: KeyguardUpdateMonitor,
- @BindsInstance statusBarStateController: StatusBarStateController,
- @BindsInstance keyguardStateController: KeyguardStateController
- ): TestSensitiveContentCoordinatorComponent
- }
-} \ No newline at end of file
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/StackCoordinatorTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/StackCoordinatorTest.kt
index 70266e401f8a..cf2fc7c3a5fe 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/StackCoordinatorTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/StackCoordinatorTest.kt
@@ -15,6 +15,7 @@
*/
package com.android.systemui.statusbar.notification.collection.coordinator
+import android.os.UserHandle
import android.testing.AndroidTestingRunner
import android.testing.TestableLooper.RunWithLooper
import androidx.test.filters.SmallTest
@@ -43,6 +44,11 @@ import org.mockito.Mockito.`when` as whenever
@RunWith(AndroidTestingRunner::class)
@RunWithLooper
class StackCoordinatorTest : SysuiTestCase() {
+
+ companion object {
+ const val NOTIF_USER_ID = 0
+ }
+
private lateinit var coordinator: StackCoordinator
private lateinit var afterRenderListListener: OnAfterRenderListListener
@@ -61,7 +67,10 @@ class StackCoordinatorTest : SysuiTestCase() {
afterRenderListListener = withArgCaptor {
verify(pipeline).addOnAfterRenderListListener(capture())
}
- entry = NotificationEntryBuilder().setSection(section).build()
+ entry = NotificationEntryBuilder()
+ .setSection(section)
+ .setUser(UserHandle.of(NOTIF_USER_ID))
+ .build()
}
@Test
@@ -74,13 +83,31 @@ class StackCoordinatorTest : SysuiTestCase() {
fun testSetNotificationStats_clearableAlerting() {
whenever(section.bucket).thenReturn(BUCKET_ALERTING)
afterRenderListListener.onAfterRenderList(listOf(entry), stackController)
- verify(stackController).setNotifStats(NotifStats(1, false, true, false, false))
+ verify(stackController)
+ .setNotifStats(
+ NotifStats(
+ 1,
+ false,
+ true,
+ false,
+ false,
+ setOf(NOTIF_USER_ID),
+ emptySet()))
}
@Test
fun testSetNotificationStats_clearableSilent() {
whenever(section.bucket).thenReturn(BUCKET_SILENT)
afterRenderListListener.onAfterRenderList(listOf(entry), stackController)
- verify(stackController).setNotifStats(NotifStats(1, false, false, false, true))
+ verify(stackController)
+ .setNotifStats(
+ NotifStats(
+ 1,
+ false,
+ false,
+ false,
+ true,
+ emptySet(),
+ setOf(NOTIF_USER_ID)))
}
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/icon/IconManagerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/icon/IconManagerTest.kt
index b63e66f1ebe3..c7f7ec213b0c 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/icon/IconManagerTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/icon/IconManagerTest.kt
@@ -14,10 +14,10 @@
* limitations under the License.
*/
-package com.android.systemui.statusbar.notification.icon;
+package com.android.systemui.statusbar.notification.icon
-import android.app.ActivityManager;
-import android.app.Notification;
+import android.app.ActivityManager
+import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager.IMPORTANCE_DEFAULT
import android.app.Person
@@ -27,11 +27,12 @@ import android.graphics.drawable.Drawable
import android.graphics.drawable.Icon
import android.os.SystemClock
import android.os.UserHandle
-import android.testing.AndroidTestingRunner;
+import android.testing.AndroidTestingRunner
import androidx.test.InstrumentationRegistry
import androidx.test.filters.SmallTest
import com.android.systemui.SysuiTestCase
import com.android.systemui.controls.controller.AuxiliaryPersistenceWrapperTest.Companion.any
+import com.android.systemui.statusbar.NotificationLockscreenUserManager
import com.android.systemui.statusbar.notification.collection.NotificationEntry
import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder
import com.android.systemui.statusbar.notification.collection.notifcollection.CommonNotifCollection
@@ -40,7 +41,7 @@ import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
-import org.junit.runner.RunWith;
+import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.mockito.Mockito.anyInt
@@ -48,15 +49,14 @@ import org.mockito.MockitoAnnotations
@SmallTest
@RunWith(AndroidTestingRunner::class)
-class IconManagerTest: SysuiTestCase() {
+class IconManagerTest : SysuiTestCase() {
companion object {
- private const val TEST_PACKAGE_NAME = "test";
- private const val TEST_UID = 0;
+ private const val TEST_PACKAGE_NAME = "test"
+ private const val TEST_UID = 0
}
-
private var id = 0
- private val context = InstrumentationRegistry.getTargetContext();
+ private val context = InstrumentationRegistry.getTargetContext()
@Mock private lateinit var shortcut: ShortcutInfo
@Mock private lateinit var shortcutIc: Icon
@Mock private lateinit var messageIc: Icon
@@ -65,6 +65,7 @@ class IconManagerTest: SysuiTestCase() {
@Mock private lateinit var drawable: Drawable
@Mock private lateinit var row: ExpandableNotificationRow
+ @Mock private lateinit var notifLockscreenUserManager: NotificationLockscreenUserManager
@Mock private lateinit var notifCollection: CommonNotifCollection
@Mock private lateinit var launcherApps: LauncherApps
@@ -83,13 +84,16 @@ class IconManagerTest: SysuiTestCase() {
`when`(shortcut.icon).thenReturn(shortcutIc)
`when`(launcherApps.getShortcutIcon(shortcut)).thenReturn(shortcutIc)
+ `when`(notifLockscreenUserManager.sensitiveNotifsNeedRedactionInPublic(TEST_UID))
+ .thenReturn(true)
- iconManager = IconManager(notifCollection, launcherApps, iconBuilder)
+ iconManager =
+ IconManager(notifCollection, launcherApps, iconBuilder, notifLockscreenUserManager)
}
@Test
fun testCreateIcons_importantConversation_shortcutIcon() {
- val entry = notificationEntry(true, true, true)
+ val entry = notificationEntry()
entry?.channel?.isImportantConversation = true
entry?.let {
iconManager.createIcons(it)
@@ -99,7 +103,7 @@ class IconManagerTest: SysuiTestCase() {
@Test
fun testCreateIcons_importantConversation_messageIcon() {
- val entry = notificationEntry(false, true, true)
+ val entry = notificationEntry(hasShortcut = false)
entry?.channel?.isImportantConversation = true
entry?.let {
iconManager.createIcons(it)
@@ -109,7 +113,7 @@ class IconManagerTest: SysuiTestCase() {
@Test
fun testCreateIcons_importantConversation_largeIcon() {
- val entry = notificationEntry(false, false, true)
+ val entry = notificationEntry(hasShortcut = false, hasMessage = false)
entry?.channel?.isImportantConversation = true
entry?.let {
iconManager.createIcons(it)
@@ -119,7 +123,7 @@ class IconManagerTest: SysuiTestCase() {
@Test
fun testCreateIcons_importantConversation_smallIcon() {
- val entry = notificationEntry(false, false, false)
+ val entry = notificationEntry(hasShortcut = false, hasMessage = false, hasLargeIcon = false)
entry?.channel?.isImportantConversation = true
entry?.let {
iconManager.createIcons(it)
@@ -129,7 +133,7 @@ class IconManagerTest: SysuiTestCase() {
@Test
fun testCreateIcons_notImportantConversation() {
- val entry = notificationEntry(true, true, true)
+ val entry = notificationEntry()
entry?.let {
iconManager.createIcons(it)
}
@@ -138,8 +142,10 @@ class IconManagerTest: SysuiTestCase() {
@Test
fun testCreateIcons_sensitiveImportantConversation() {
- val entry = notificationEntry(true, false, false)
- entry?.setSensitive(true, true);
+ val entry = notificationEntry(
+ hasMessage = false,
+ hasLargeIcon = false,
+ hasSensitiveContent = true)
entry?.channel?.isImportantConversation = true
entry?.let {
iconManager.createIcons(it)
@@ -151,14 +157,17 @@ class IconManagerTest: SysuiTestCase() {
@Test
fun testUpdateIcons_sensitivityChange() {
- val entry = notificationEntry(true, false, false)
+ val entry = notificationEntry(
+ hasMessage = false,
+ hasLargeIcon = false,
+ hasSensitiveContent = true)
entry?.channel?.isImportantConversation = true
- entry?.setSensitive(true, true);
entry?.let {
iconManager.createIcons(it)
}
assertEquals(entry?.icons?.aodIcon?.sourceIcon, smallIc)
- entry?.setSensitive(false, false);
+ `when`(notifLockscreenUserManager.sensitiveNotifsNeedRedactionInPublic(TEST_UID))
+ .thenReturn(false)
entry?.let {
iconManager.updateIcons(it)
}
@@ -166,14 +175,19 @@ class IconManagerTest: SysuiTestCase() {
}
private fun notificationEntry(
- hasShortcut: Boolean,
- hasMessage: Boolean,
- hasLargeIcon: Boolean
+ hasShortcut: Boolean = true,
+ hasMessage: Boolean = true,
+ hasLargeIcon: Boolean = true,
+ hasSensitiveContent: Boolean = false
): NotificationEntry? {
val n = Notification.Builder(mContext, "id")
.setSmallIcon(smallIc)
.setContentTitle("Title")
.setContentText("Text")
+ .setVisibility(
+ if (hasSensitiveContent)
+ Notification.VISIBILITY_PRIVATE
+ else Notification.VISIBILITY_PUBLIC)
if (hasMessage) {
n.style = Notification.MessagingStyle("")
@@ -203,7 +217,6 @@ class IconManagerTest: SysuiTestCase() {
val entry = builder.build()
entry.row = row
- entry.setSensitive(false, true);
return entry
}
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRowTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRowTest.java
index 0f2e9bccc215..f5a0e2d48859 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRowTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRowTest.java
@@ -91,7 +91,7 @@ public class ExpandableNotificationRowTest extends SysuiTestCase {
@Test
public void testGroupSummaryNotShowingIconWhenPublic() {
- mGroupRow.setSensitive(true, true);
+ mGroupRow.setSensitive(true);
mGroupRow.setHideSensitiveForIntrinsicHeight(true);
assertTrue(mGroupRow.isSummaryWithChildren());
assertFalse(mGroupRow.isShowingIcon());
@@ -99,7 +99,7 @@ public class ExpandableNotificationRowTest extends SysuiTestCase {
@Test
public void testNotificationHeaderVisibleWhenAnimating() {
- mGroupRow.setSensitive(true, true);
+ mGroupRow.setSensitive(true);
mGroupRow.setHideSensitive(true, false, 0, 0);
mGroupRow.setHideSensitive(false, true, 0, 0);
assertEquals(View.VISIBLE, mGroupRow.getChildrenContainer().getVisibleWrapper()
@@ -130,7 +130,7 @@ public class ExpandableNotificationRowTest extends SysuiTestCase {
public void testIconColorShouldBeUpdatedWhenSensitive() throws Exception {
ExpandableNotificationRow row = spy(mNotificationTestHelper.createRow(
FLAG_CONTENT_VIEW_ALL));
- row.setSensitive(true, true);
+ row.setSensitive(true);
row.setHideSensitive(true, false, 0, 0);
verify(row).updateShelfIconColor();
}
@@ -214,7 +214,7 @@ public class ExpandableNotificationRowTest extends SysuiTestCase {
@Test
public void testFeedback_noHeader() {
// public notification is custom layout - no header
- mGroupRow.setSensitive(true, true);
+ mGroupRow.setSensitive(true);
mGroupRow.setOnFeedbackClickListener(null);
mGroupRow.setFeedbackIcon(null);
}
@@ -322,11 +322,22 @@ public class ExpandableNotificationRowTest extends SysuiTestCase {
ExpandableNotificationRow row =
mNotificationTestHelper.createRow(mNotificationTestHelper.createNotification());
row.getEntry().getChannel().setImportanceLockedByCriticalDeviceFunction(true);
+ row.getEntry().getChannel().setBlockable(false);
assertTrue(row.getIsNonblockable());
}
@Test
+ public void testGetIsNonblockable_criticalDeviceFunction_butBlockable() throws Exception {
+ ExpandableNotificationRow row =
+ mNotificationTestHelper.createRow(mNotificationTestHelper.createNotification());
+ row.getEntry().getChannel().setImportanceLockedByCriticalDeviceFunction(true);
+ row.getEntry().getChannel().setBlockable(true);
+
+ assertFalse(row.getIsNonblockable());
+ }
+
+ @Test
public void testCanDismissNoClear() throws Exception {
ExpandableNotificationRow row =
mNotificationTestHelper.createRow(mNotificationTestHelper.createNotification());
@@ -335,7 +346,7 @@ public class ExpandableNotificationRowTest extends SysuiTestCase {
.build();
row.performDismiss(false);
verify(mNotificationTestHelper.mOnUserInteractionCallback)
- .onDismiss(any(), anyInt(), any());
+ .registerFutureDismissal(any(), anyInt());
}
@Test
@@ -347,6 +358,6 @@ public class ExpandableNotificationRowTest extends SysuiTestCase {
.build();
row.performDismiss(false);
verify(mNotificationTestHelper.mOnUserInteractionCallback, never())
- .onDismiss(any(), anyInt(), any());
+ .registerFutureDismissal(any(), anyInt());
}
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationEntryManagerInflationTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationEntryManagerInflationTest.java
index 251ac7d250fe..a8557050dddb 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationEntryManagerInflationTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationEntryManagerInflationTest.java
@@ -78,7 +78,6 @@ import com.android.systemui.statusbar.notification.collection.legacy.Notificatio
import com.android.systemui.statusbar.notification.collection.provider.HighPriorityProvider;
import com.android.systemui.statusbar.notification.icon.IconBuilder;
import com.android.systemui.statusbar.notification.icon.IconManager;
-import com.android.systemui.statusbar.notification.interruption.NotificationInterruptStateProvider;
import com.android.systemui.statusbar.notification.logging.NotificationLogger;
import com.android.systemui.statusbar.notification.people.PeopleNotificationIdentifier;
import com.android.systemui.statusbar.notification.row.dagger.ExpandableNotificationRowComponent;
@@ -132,7 +131,6 @@ public class NotificationEntryManagerInflationTest extends SysuiTestCase {
@Mock private NotificationEntryListener mEntryListener;
@Mock private NotificationRowBinderImpl.BindRowCallback mBindCallback;
@Mock private HeadsUpManager mHeadsUpManager;
- @Mock private NotificationInterruptStateProvider mNotificationInterruptionStateProvider;
@Mock private NotificationLockscreenUserManager mLockscreenUserManager;
@Mock private NotificationGutsManager mGutsManager;
@Mock private NotificationRemoteInputManager mRemoteInputManager;
@@ -254,6 +252,7 @@ public class NotificationEntryManagerInflationTest extends SysuiTestCase {
.thenAnswer((Answer<ExpandableNotificationRowController>) invocation ->
new ExpandableNotificationRowController(
viewCaptor.getValue(),
+ mLockscreenUserManager,
mock(ActivatableNotificationViewController.class),
mock(RemoteInputViewSubcomponent.Factory.class),
mock(MetricsLogger.class),
@@ -300,7 +299,8 @@ public class NotificationEntryManagerInflationTest extends SysuiTestCase {
new IconManager(
mEntryManager,
mock(LauncherApps.class),
- new IconBuilder(mContext)),
+ new IconBuilder(mContext),
+ mLockscreenUserManager),
mock(LowPriorityInflationHelper.class),
mNotifPipelineFlags);
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationTestHelper.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationTestHelper.java
index 1ecb09bc8514..7a8b329bec64 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationTestHelper.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationTestHelper.java
@@ -23,8 +23,11 @@ import static android.app.NotificationManager.IMPORTANCE_HIGH;
import static com.android.systemui.statusbar.NotificationEntryHelper.modifyRanking;
import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
import android.annotation.Nullable;
import android.app.ActivityManager;
@@ -52,6 +55,7 @@ import com.android.systemui.dump.DumpManager;
import com.android.systemui.media.MediaFeatureFlag;
import com.android.systemui.media.dialog.MediaOutputDialogFactory;
import com.android.systemui.plugins.statusbar.StatusBarStateController;
+import com.android.systemui.statusbar.NotificationLockscreenUserManager;
import com.android.systemui.statusbar.NotificationMediaManager;
import com.android.systemui.statusbar.NotificationRemoteInputManager;
import com.android.systemui.statusbar.NotificationShadeWindowController;
@@ -120,6 +124,7 @@ public class NotificationTestHelper {
private StatusBarStateController mStatusBarStateController;
private final PeopleNotificationIdentifier mPeopleNotificationIdentifier;
public final OnUserInteractionCallback mOnUserInteractionCallback;
+ public final Runnable mFutureDismissalRunnable;
public NotificationTestHelper(
Context context,
@@ -152,7 +157,8 @@ public class NotificationTestHelper {
mIconManager = new IconManager(
mock(CommonNotifCollection.class),
mock(LauncherApps.class),
- new IconBuilder(mContext));
+ new IconBuilder(mContext),
+ mock(NotificationLockscreenUserManager.class));
NotificationContentInflater contentBinder = new NotificationContentInflater(
mock(NotifRemoteViewCache.class),
@@ -180,6 +186,9 @@ public class NotificationTestHelper {
mBindPipelineEntryListener = collectionListenerCaptor.getValue();
mPeopleNotificationIdentifier = mock(PeopleNotificationIdentifier.class);
mOnUserInteractionCallback = mock(OnUserInteractionCallback.class);
+ mFutureDismissalRunnable = mock(Runnable.class);
+ when(mOnUserInteractionCallback.registerFutureDismissal(any(), anyInt()))
+ .thenReturn(mFutureDismissalRunnable);
}
/**
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationShelfTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationShelfTest.kt
index 4270d72770dc..3f190367f284 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationShelfTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationShelfTest.kt
@@ -5,8 +5,9 @@ import android.testing.TestableLooper.RunWithLooper
import androidx.test.filters.SmallTest
import com.android.systemui.SysuiTestCase
import com.android.systemui.statusbar.NotificationShelf
-import junit.framework.Assert.assertFalse
-import junit.framework.Assert.assertTrue
+import com.android.systemui.statusbar.StatusBarIconView
+import com.android.systemui.statusbar.notification.row.ExpandableView
+import junit.framework.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@@ -143,6 +144,113 @@ class NotificationShelfTest : SysuiTestCase() {
assertFalse(isYBelowShelfInView)
}
+ @Test
+ fun getAmountInShelf_lastViewBelowShelf_completelyInShelf() {
+ val shelfClipStart = 0f
+ val viewStart = 1f
+
+ val expandableView = mock(ExpandableView::class.java)
+ whenever(expandableView.shelfIcon).thenReturn(mock(StatusBarIconView::class.java))
+ whenever(expandableView.translationY).thenReturn(viewStart)
+ whenever(expandableView.actualHeight).thenReturn(20)
+
+ whenever(expandableView.minHeight).thenReturn(20)
+ whenever(expandableView.shelfTransformationTarget).thenReturn(null) // use translationY
+ whenever(expandableView.isInShelf).thenReturn(true)
+
+ whenever(ambientState.isOnKeyguard).thenReturn(true)
+ whenever(ambientState.isExpansionChanging).thenReturn(false)
+ whenever(ambientState.isShadeExpanded).thenReturn(true)
+
+ val amountInShelf = shelf.getAmountInShelf(/* i= */ 0,
+ /* view= */ expandableView,
+ /* scrollingFast= */ false,
+ /* expandingAnimated= */ false,
+ /* isLastChild= */ true,
+ shelfClipStart)
+ assertEquals(1f, amountInShelf)
+ }
+
+ @Test
+ fun getAmountInShelf_lastViewAlmostBelowShelf_completelyInShelf() {
+ val viewStart = 0f
+ val shelfClipStart = 0.001f
+
+ val expandableView = mock(ExpandableView::class.java)
+ whenever(expandableView.shelfIcon).thenReturn(mock(StatusBarIconView::class.java))
+ whenever(expandableView.translationY).thenReturn(viewStart)
+ whenever(expandableView.actualHeight).thenReturn(20)
+
+ whenever(expandableView.minHeight).thenReturn(20)
+ whenever(expandableView.shelfTransformationTarget).thenReturn(null) // use translationY
+ whenever(expandableView.isInShelf).thenReturn(true)
+
+ whenever(ambientState.isOnKeyguard).thenReturn(true)
+ whenever(ambientState.isExpansionChanging).thenReturn(false)
+ whenever(ambientState.isShadeExpanded).thenReturn(true)
+
+ val amountInShelf = shelf.getAmountInShelf(/* i= */ 0,
+ /* view= */ expandableView,
+ /* scrollingFast= */ false,
+ /* expandingAnimated= */ false,
+ /* isLastChild= */ true,
+ shelfClipStart)
+ assertEquals(1f, amountInShelf)
+ }
+
+ @Test
+ fun getAmountInShelf_lastViewHalfClippedByShelf_halfInShelf() {
+ val viewStart = 0f
+ val shelfClipStart = 10f
+
+ val expandableView = mock(ExpandableView::class.java)
+ whenever(expandableView.shelfIcon).thenReturn(mock(StatusBarIconView::class.java))
+ whenever(expandableView.translationY).thenReturn(viewStart)
+ whenever(expandableView.actualHeight).thenReturn(25)
+
+ whenever(expandableView.minHeight).thenReturn(25)
+ whenever(expandableView.shelfTransformationTarget).thenReturn(null) // use translationY
+ whenever(expandableView.isInShelf).thenReturn(true)
+
+ whenever(ambientState.isOnKeyguard).thenReturn(true)
+ whenever(ambientState.isExpansionChanging).thenReturn(false)
+ whenever(ambientState.isShadeExpanded).thenReturn(true)
+
+ val amountInShelf = shelf.getAmountInShelf(/* i= */ 0,
+ /* view= */ expandableView,
+ /* scrollingFast= */ false,
+ /* expandingAnimated= */ false,
+ /* isLastChild= */ true,
+ shelfClipStart)
+ assertEquals(0.5f, amountInShelf)
+ }
+
+ @Test
+ fun getAmountInShelf_lastViewAboveShelf_notInShelf() {
+ val viewStart = 0f
+ val shelfClipStart = 15f
+
+ val expandableView = mock(ExpandableView::class.java)
+ whenever(expandableView.shelfIcon).thenReturn(mock(StatusBarIconView::class.java))
+ whenever(expandableView.translationY).thenReturn(viewStart)
+ whenever(expandableView.actualHeight).thenReturn(10)
+
+ whenever(expandableView.minHeight).thenReturn(10)
+ whenever(expandableView.shelfTransformationTarget).thenReturn(null) // use translationY
+ whenever(expandableView.isInShelf).thenReturn(false)
+
+ whenever(ambientState.isExpansionChanging).thenReturn(false)
+ whenever(ambientState.isOnKeyguard).thenReturn(true)
+
+ val amountInShelf = shelf.getAmountInShelf(/* i= */ 0,
+ /* view= */ expandableView,
+ /* scrollingFast= */ false,
+ /* expandingAnimated= */ false,
+ /* isLastChild= */ true,
+ shelfClipStart)
+ assertEquals(0f, amountInShelf)
+ }
+
private fun setFractionToShade(fraction: Float) {
whenever(ambientState.fractionToShade).thenReturn(fraction)
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutTest.java
index e8608fa76c06..63e0f53e093d 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutTest.java
@@ -31,6 +31,8 @@ import static junit.framework.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.ArgumentMatchers.anyFloat;
+import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.clearInvocations;
@@ -612,6 +614,12 @@ public class NotificationStackScrollLayoutTest extends SysuiTestCase {
assertTrue(mStackScroller.isInsideQsHeader(event2));
}
+ @Test
+ public void setFractionToShade_recomputesStackHeight() {
+ mStackScroller.setFractionToShade(1f);
+ verify(mNotificationStackSizeCalculator).computeHeight(any(), anyInt(), anyFloat());
+ }
+
private void setBarStateForTest(int state) {
// Can't inject this through the listener or we end up on the actual implementation
// rather than the mock because the spy just coppied the anonymous inner /shruggie.
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/HeadsUpAppearanceControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/HeadsUpAppearanceControllerTest.java
index ed22cd3c55fc..169c04c692e0 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/HeadsUpAppearanceControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/HeadsUpAppearanceControllerTest.java
@@ -36,6 +36,7 @@ import com.android.systemui.plugins.DarkIconDispatcher;
import com.android.systemui.plugins.statusbar.StatusBarStateController;
import com.android.systemui.statusbar.CommandQueue;
import com.android.systemui.statusbar.HeadsUpStatusBarView;
+import com.android.systemui.statusbar.NotificationLockscreenUserManager;
import com.android.systemui.statusbar.notification.NotificationWakeUpCoordinator;
import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
import com.android.systemui.statusbar.notification.row.NotificationTestHelper;
@@ -57,9 +58,12 @@ public class HeadsUpAppearanceControllerTest extends SysuiTestCase {
private final NotificationStackScrollLayoutController mStackScrollerController =
mock(NotificationStackScrollLayoutController.class);
- private final NotificationPanelViewController mPanelView =
+ private final NotificationPanelViewController mPanelViewController =
mock(NotificationPanelViewController.class);
private final DarkIconDispatcher mDarkIconDispatcher = mock(DarkIconDispatcher.class);
+ private final NotificationLockscreenUserManager mLockscreenUserManager =
+ mock(NotificationLockscreenUserManager.class);
+
private HeadsUpAppearanceController mHeadsUpAppearanceController;
private ExpandableNotificationRow mFirst;
private HeadsUpStatusBarView mHeadsUpStatusBarView;
@@ -93,12 +97,13 @@ public class HeadsUpAppearanceControllerTest extends SysuiTestCase {
mHeadsUpManager,
mStatusbarStateController,
mBypassController,
+ mLockscreenUserManager,
mWakeUpCoordinator,
mDarkIconDispatcher,
mKeyguardStateController,
mCommandQueue,
mStackScrollerController,
- mPanelView,
+ mPanelViewController,
mHeadsUpStatusBarView,
new Clock(mContext, null),
Optional.of(mOperatorNameView));
@@ -175,12 +180,13 @@ public class HeadsUpAppearanceControllerTest extends SysuiTestCase {
mHeadsUpManager,
mStatusbarStateController,
mBypassController,
+ mLockscreenUserManager,
mWakeUpCoordinator,
mDarkIconDispatcher,
mKeyguardStateController,
mCommandQueue,
mStackScrollerController,
- mPanelView,
+ mPanelViewController,
mHeadsUpStatusBarView,
new Clock(mContext, null),
Optional.empty());
@@ -193,15 +199,15 @@ public class HeadsUpAppearanceControllerTest extends SysuiTestCase {
public void testDestroy() {
reset(mHeadsUpManager);
reset(mDarkIconDispatcher);
- reset(mPanelView);
+ reset(mPanelViewController);
reset(mStackScrollerController);
mHeadsUpAppearanceController.onViewDetached();
verify(mHeadsUpManager).removeListener(any());
verify(mDarkIconDispatcher).removeDarkReceiver((DarkIconDispatcher.DarkReceiver) any());
- verify(mPanelView).removeTrackingHeadsUpListener(any());
- verify(mPanelView).setHeadsUpAppearanceController(isNull());
+ verify(mPanelViewController).removeTrackingHeadsUpListener(any());
+ verify(mPanelViewController).setHeadsUpAppearanceController(isNull());
verify(mStackScrollerController).removeOnExpandedHeightChangedListener(any());
}
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/KeyguardBouncerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/KeyguardBouncerTest.java
index f43c2a183465..9c02216722e2 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/KeyguardBouncerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/KeyguardBouncerTest.java
@@ -475,4 +475,19 @@ public class KeyguardBouncerTest extends SysuiTestCase {
mBouncer.setExpansion(bouncerHideAmount);
verify(callback, never()).onExpansionChanged(bouncerHideAmount);
}
+
+ @Test
+ public void testOnResumeCalledForFullscreenBouncerOnSecondShow() {
+ // GIVEN a security mode which requires fullscreen bouncer
+ when(mKeyguardSecurityModel.getSecurityMode(anyInt()))
+ .thenReturn(KeyguardSecurityModel.SecurityMode.SimPin);
+ mBouncer.show(true);
+
+ // WHEN a second call to show occurs, the bouncer will already by visible
+ reset(mKeyguardHostViewController);
+ mBouncer.show(true);
+
+ // THEN ensure the ViewController is told to resume
+ verify(mKeyguardHostViewController).onResume();
+ }
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/PhoneStatusBarViewControllerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/PhoneStatusBarViewControllerTest.kt
index 9ab88dc2d764..ba29e953c73d 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/PhoneStatusBarViewControllerTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/PhoneStatusBarViewControllerTest.kt
@@ -136,6 +136,7 @@ class PhoneStatusBarViewControllerTest : SysuiTestCase() {
private class UnfoldConfig : UnfoldTransitionConfig {
override var isEnabled: Boolean = false
override var isHingeAngleEnabled: Boolean = false
+ override val halfFoldedTimeoutMillis: Int = 0
}
private class TestTouchEventHandler : PhoneStatusBarView.TouchEventHandler {
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/ScrimControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/ScrimControllerTest.java
index dce520c0973d..5f8dda359563 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/ScrimControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/ScrimControllerTest.java
@@ -1490,6 +1490,13 @@ public class ScrimControllerTest extends SysuiTestCase {
assertAlphaAfterExpansion(mNotificationsScrim, 0f, expansion);
}
+ @Test
+ public void aodStateSetsFrontScrimToNotBlend() {
+ mScrimController.transitionTo(ScrimState.AOD);
+ Assert.assertFalse("Front scrim should not blend with main color",
+ mScrimInFront.shouldBlendWithMainColor());
+ }
+
private void assertAlphaAfterExpansion(ScrimView scrim, float expectedAlpha, float expansion) {
mScrimController.setRawPanelExpansionFraction(expansion);
finishAnimationsImmediately();
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarterTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarterTest.java
index fa867e2796f7..ecea14c6a522 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarterTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarterTest.java
@@ -85,7 +85,6 @@ import com.android.systemui.wmshell.BubblesManager;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.Mockito;
@@ -93,6 +92,7 @@ import org.mockito.MockitoAnnotations;
import org.mockito.stubbing.Answer;
import java.util.ArrayList;
+import java.util.List;
import java.util.Optional;
@SmallTest
@@ -141,12 +141,13 @@ public class StatusBarNotificationActivityStarterTest extends SysuiTestCase {
@Mock
private OnUserInteractionCallback mOnUserInteractionCallback;
@Mock
+ private Runnable mFutureDismissalRunnable;
+ @Mock
private StatusBarNotificationActivityStarter mNotificationActivityStarter;
@Mock
private ActivityLaunchAnimator mActivityLaunchAnimator;
@Mock
private InteractionJankMonitor mJankMonitor;
- private StatusBarNotificationActivityStarter.LaunchEventsEmitter mLaunchEventsEmitter;
private FakeExecutor mUiBgExecutor = new FakeExecutor(new FakeSystemClock());
private NotificationTestHelper mNotificationTestHelper;
private ExpandableNotificationRow mNotificationRow;
@@ -187,8 +188,8 @@ public class StatusBarNotificationActivityStarterTest extends SysuiTestCase {
when(mEntryManager.getVisibleNotifications()).thenReturn(mActiveNotifications);
when(mStatusBarStateController.getState()).thenReturn(StatusBarState.SHADE);
when(mNotifPipelineFlags.isNewPipelineEnabled()).thenReturn(false);
- when(mOnUserInteractionCallback.getGroupSummaryToDismiss(mNotificationRow.getEntry()))
- .thenReturn(null);
+ when(mOnUserInteractionCallback.registerFutureDismissal(eq(mNotificationRow.getEntry()),
+ anyInt())).thenReturn(mFutureDismissalRunnable);
when(mVisibilityProvider.obtain(anyString(), anyBoolean()))
.thenAnswer(invocation -> NotificationVisibility.obtain(
invocation.getArgument(0), 0, 1, false));
@@ -203,7 +204,6 @@ public class StatusBarNotificationActivityStarterTest extends SysuiTestCase {
NotificationListContainer.class),
headsUpManager,
mJankMonitor);
- mLaunchEventsEmitter = new StatusBarNotificationActivityStarter.LaunchEventsEmitter();
mNotificationActivityStarter =
new StatusBarNotificationActivityStarter(
getContext(),
@@ -239,8 +239,7 @@ public class StatusBarNotificationActivityStarterTest extends SysuiTestCase {
mock(NotificationPresenter.class),
mock(NotificationPanelViewController.class),
mActivityLaunchAnimator,
- notificationAnimationProvider,
- mLaunchEventsEmitter
+ notificationAnimationProvider
);
// set up dismissKeyguardThenExecute to synchronously invoke the OnDismissAction arg
@@ -264,16 +263,23 @@ public class StatusBarNotificationActivityStarterTest extends SysuiTestCase {
@Test
public void testOnNotificationClicked_keyGuardShowing()
throws PendingIntent.CanceledException, RemoteException {
+ // To get the order right, collect posted runnables and run them later
+ List<Runnable> runnables = new ArrayList<>();
+ doAnswer(answerVoid(r -> runnables.add((Runnable) r)))
+ .when(mHandler).post(any(Runnable.class));
// Given
- StatusBarNotification sbn = mNotificationRow.getEntry().getSbn();
- sbn.getNotification().contentIntent = mContentIntent;
- sbn.getNotification().flags |= Notification.FLAG_AUTO_CANCEL;
+ NotificationEntry entry = mNotificationRow.getEntry();
+ Notification notification = entry.getSbn().getNotification();
+ notification.contentIntent = mContentIntent;
+ notification.flags |= Notification.FLAG_AUTO_CANCEL;
when(mKeyguardStateController.isShowing()).thenReturn(true);
when(mCentralSurfaces.isOccluded()).thenReturn(true);
// When
- mNotificationActivityStarter.onNotificationClicked(sbn, mNotificationRow);
+ mNotificationActivityStarter.onNotificationClicked(entry, mNotificationRow);
+ // Run the collected runnables in fifo order, the way post() really does.
+ while (!runnables.isEmpty()) runnables.remove(0).run();
// Then
verify(mShadeController, atLeastOnce()).collapsePanel();
@@ -283,24 +289,27 @@ public class StatusBarNotificationActivityStarterTest extends SysuiTestCase {
verify(mAssistManager).hideAssist();
- InOrder orderVerifier = Mockito.inOrder(mClickNotifier, mOnUserInteractionCallback);
- orderVerifier.verify(mClickNotifier).onNotificationClick(
- eq(sbn.getKey()), any(NotificationVisibility.class));
+ InOrder orderVerifier = Mockito.inOrder(mClickNotifier, mOnUserInteractionCallback,
+ mFutureDismissalRunnable);
// Notification calls dismiss callback to remove notification due to FLAG_AUTO_CANCEL
- orderVerifier.verify(mOnUserInteractionCallback).onDismiss(mNotificationRow.getEntry(),
- REASON_CLICK, null);
+ orderVerifier.verify(mOnUserInteractionCallback)
+ .registerFutureDismissal(eq(entry), eq(REASON_CLICK));
+ orderVerifier.verify(mClickNotifier).onNotificationClick(
+ eq(entry.getKey()), any(NotificationVisibility.class));
+ orderVerifier.verify(mFutureDismissalRunnable).run();
}
@Test
public void testOnNotificationClicked_bubble_noContentIntent_noKeyGuard()
throws RemoteException {
- StatusBarNotification sbn = mBubbleNotificationRow.getEntry().getSbn();
+ NotificationEntry entry = mBubbleNotificationRow.getEntry();
+ StatusBarNotification sbn = entry.getSbn();
// Given
sbn.getNotification().contentIntent = null;
// When
- mNotificationActivityStarter.onNotificationClicked(sbn, mBubbleNotificationRow);
+ mNotificationActivityStarter.onNotificationClicked(entry, mBubbleNotificationRow);
// Then
verify(mBubblesManager).expandStackAndSelectBubble(eq(mBubbleNotificationRow.getEntry()));
@@ -311,20 +320,22 @@ public class StatusBarNotificationActivityStarterTest extends SysuiTestCase {
verify(mAssistManager).hideAssist();
verify(mClickNotifier).onNotificationClick(
- eq(sbn.getKey()), any(NotificationVisibility.class));
+ eq(entry.getKey()), any(NotificationVisibility.class));
// The content intent should NOT be sent on click.
verifyZeroInteractions(mContentIntent);
// Notification should not be cancelled.
- verify(mOnUserInteractionCallback, never()).onDismiss(eq(mNotificationRow.getEntry()),
- anyInt(), eq(null));
+ verify(mOnUserInteractionCallback, never())
+ .registerFutureDismissal(eq(mNotificationRow.getEntry()), anyInt());
+ verify(mFutureDismissalRunnable, never()).run();
}
@Test
public void testOnNotificationClicked_bubble_noContentIntent_keyGuardShowing()
throws RemoteException {
- StatusBarNotification sbn = mBubbleNotificationRow.getEntry().getSbn();
+ NotificationEntry entry = mBubbleNotificationRow.getEntry();
+ StatusBarNotification sbn = entry.getSbn();
// Given
sbn.getNotification().contentIntent = null;
@@ -332,7 +343,7 @@ public class StatusBarNotificationActivityStarterTest extends SysuiTestCase {
when(mCentralSurfaces.isOccluded()).thenReturn(true);
// When
- mNotificationActivityStarter.onNotificationClicked(sbn, mBubbleNotificationRow);
+ mNotificationActivityStarter.onNotificationClicked(entry, mBubbleNotificationRow);
// Then
verify(mBubblesManager).expandStackAndSelectBubble(eq(mBubbleNotificationRow.getEntry()));
@@ -342,7 +353,7 @@ public class StatusBarNotificationActivityStarterTest extends SysuiTestCase {
verify(mAssistManager).hideAssist();
verify(mClickNotifier).onNotificationClick(
- eq(sbn.getKey()), any(NotificationVisibility.class));
+ eq(entry.getKey()), any(NotificationVisibility.class));
// The content intent should NOT be sent on click.
verifyZeroInteractions(mContentIntent);
@@ -354,7 +365,8 @@ public class StatusBarNotificationActivityStarterTest extends SysuiTestCase {
@Test
public void testOnNotificationClicked_bubble_withContentIntent_keyGuardShowing()
throws RemoteException {
- StatusBarNotification sbn = mBubbleNotificationRow.getEntry().getSbn();
+ NotificationEntry entry = mBubbleNotificationRow.getEntry();
+ StatusBarNotification sbn = entry.getSbn();
// Given
sbn.getNotification().contentIntent = mContentIntent;
@@ -362,7 +374,7 @@ public class StatusBarNotificationActivityStarterTest extends SysuiTestCase {
when(mCentralSurfaces.isOccluded()).thenReturn(true);
// When
- mNotificationActivityStarter.onNotificationClicked(sbn, mBubbleNotificationRow);
+ mNotificationActivityStarter.onNotificationClicked(entry, mBubbleNotificationRow);
// Then
verify(mBubblesManager).expandStackAndSelectBubble(mBubbleNotificationRow.getEntry());
@@ -372,7 +384,7 @@ public class StatusBarNotificationActivityStarterTest extends SysuiTestCase {
verify(mAssistManager).hideAssist();
verify(mClickNotifier).onNotificationClick(
- eq(sbn.getKey()), any(NotificationVisibility.class));
+ eq(entry.getKey()), any(NotificationVisibility.class));
// The content intent should NOT be sent on click.
verify(mContentIntent).getIntent();
@@ -405,57 +417,4 @@ public class StatusBarNotificationActivityStarterTest extends SysuiTestCase {
// THEN display should try wake up for the full screen intent
verify(mCentralSurfaces).wakeUpForFullScreenIntent();
}
-
- @Test
- public void testNotifActivityStarterEventSourceStartEvent_onNotificationClicked() {
- NotifActivityLaunchEvents.Listener listener =
- mock(NotifActivityLaunchEvents.Listener.class);
- mLaunchEventsEmitter.registerListener(listener);
- mNotificationActivityStarter
- .onNotificationClicked(mNotificationRow.getEntry().getSbn(), mNotificationRow);
- verify(listener).onStartLaunchNotifActivity(mNotificationRow.getEntry());
- }
-
- @Test
- public void testNotifActivityStarterEventSourceFinishEvent_dismissKeyguardCancelled() {
- NotifActivityLaunchEvents.Listener listener =
- mock(NotifActivityLaunchEvents.Listener.class);
- mLaunchEventsEmitter.registerListener(listener);
- // set up dismissKeyguardThenExecute to synchronously invoke the cancel runnable arg
- doAnswer(answerVoid(
- (OnDismissAction dismissAction, Runnable cancel, Boolean afterKeyguardGone) ->
- cancel.run()))
- .when(mActivityStarter)
- .dismissKeyguardThenExecute(any(OnDismissAction.class), any(), anyBoolean());
- mNotificationActivityStarter
- .onNotificationClicked(mNotificationRow.getEntry().getSbn(), mNotificationRow);
- verify(listener).onFinishLaunchNotifActivity(mNotificationRow.getEntry());
- }
-
- @Test
- public void testNotifActivityStarterEventSourceFinishEvent_postPanelCollapse()
- throws Exception {
- NotifActivityLaunchEvents.Listener listener =
- mock(NotifActivityLaunchEvents.Listener.class);
- mLaunchEventsEmitter.registerListener(listener);
- mNotificationActivityStarter
- .onNotificationClicked(mNotificationRow.getEntry().getSbn(), mNotificationRow);
- ArgumentCaptor<ActivityLaunchAnimator.Controller> controllerCaptor =
- ArgumentCaptor.forClass(ActivityLaunchAnimator.Controller.class);
- verify(mActivityLaunchAnimator).startPendingIntentWithAnimation(
- controllerCaptor.capture(), anyBoolean(), any(), any());
- controllerCaptor.getValue().onIntentStarted(false);
- verify(listener).onFinishLaunchNotifActivity(mNotificationRow.getEntry());
- }
-
- @Test
- public void testNotifActivityStarterEventSourceFinishEvent_postPanelCollapse_noAnimate() {
- NotifActivityLaunchEvents.Listener listener =
- mock(NotifActivityLaunchEvents.Listener.class);
- mLaunchEventsEmitter.registerListener(listener);
- when(mCentralSurfaces.shouldAnimateLaunch(anyBoolean())).thenReturn(false);
- mNotificationActivityStarter
- .onNotificationClicked(mNotificationRow.getEntry().getSbn(), mNotificationRow);
- verify(listener).onFinishLaunchNotifActivity(mNotificationRow.getEntry());
- }
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/fragment/CollapsedStatusBarFragmentTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/fragment/CollapsedStatusBarFragmentTest.java
index 98397fb01b6b..6abc687f0ebb 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/fragment/CollapsedStatusBarFragmentTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/fragment/CollapsedStatusBarFragmentTest.java
@@ -379,7 +379,7 @@ public class CollapsedStatusBarFragmentTest extends SysuiBaseFragmentTest {
mCommandQueue,
mCarrierConfigTracker,
new CollapsedStatusBarFragmentLogger(
- new LogBuffer("TEST", 1, 1, mock(LogcatEchoTracker.class)),
+ new LogBuffer("TEST", 1, mock(LogcatEchoTracker.class)),
new DisableFlagsLogger()
),
mOperatorNameViewControllerFactory,
diff --git a/packages/SystemUI/tests/src/com/android/systemui/theme/ThemeOverlayControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/theme/ThemeOverlayControllerTest.java
index 3dfc94bcd5b6..68818f610fb7 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/theme/ThemeOverlayControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/theme/ThemeOverlayControllerTest.java
@@ -74,6 +74,8 @@ import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
+import java.util.Arrays;
+import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
@@ -345,7 +347,9 @@ public class ThemeOverlayControllerTest extends SysuiTestCase {
@Test
public void onSettingChanged_honorThemeStyle() {
when(mDeviceProvisionedController.isUserSetup(anyInt())).thenReturn(true);
- for (Style style : Style.values()) {
+ List<Style> validStyles = Arrays.asList(Style.EXPRESSIVE, Style.SPRITZ, Style.TONAL_SPOT,
+ Style.FRUIT_SALAD, Style.RAINBOW, Style.VIBRANT);
+ for (Style style : validStyles) {
reset(mSecureSettings);
String jsonString = "{\"android.theme.customization.system_palette\":\"A16B00\","
diff --git a/packages/SystemUI/tests/src/com/android/systemui/unfold/FoldStateLoggingProviderTest.kt b/packages/SystemUI/tests/src/com/android/systemui/unfold/FoldStateLoggingProviderTest.kt
index 8076b4eda883..39e4e6446d02 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/unfold/FoldStateLoggingProviderTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/unfold/FoldStateLoggingProviderTest.kt
@@ -25,28 +25,20 @@ import com.android.systemui.unfold.updates.FOLD_UPDATE_FINISH_FULL_OPEN
import com.android.systemui.unfold.updates.FOLD_UPDATE_FINISH_HALF_OPEN
import com.android.systemui.unfold.updates.FOLD_UPDATE_START_CLOSING
import com.android.systemui.unfold.updates.FOLD_UPDATE_START_OPENING
-import com.android.systemui.unfold.updates.FoldStateProvider
import com.android.systemui.unfold.updates.FoldStateProvider.FoldUpdate
+import com.android.systemui.unfold.util.TestFoldStateProvider
import com.android.systemui.util.time.FakeSystemClock
import com.google.common.truth.Truth.assertThat
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
-import org.mockito.ArgumentCaptor
-import org.mockito.Captor
-import org.mockito.Mock
-import org.mockito.Mockito.verify
import org.mockito.MockitoAnnotations
@RunWith(AndroidTestingRunner::class)
@SmallTest
class FoldStateLoggingProviderTest : SysuiTestCase() {
- @Captor
- private lateinit var foldUpdatesListener: ArgumentCaptor<FoldStateProvider.FoldUpdatesListener>
-
- @Mock private lateinit var foldStateProvider: FoldStateProvider
-
+ private val testFoldStateProvider = TestFoldStateProvider()
private val fakeClock = FakeSystemClock()
private lateinit var foldStateLoggingProvider: FoldStateLoggingProvider
@@ -65,12 +57,10 @@ class FoldStateLoggingProviderTest : SysuiTestCase() {
MockitoAnnotations.initMocks(this)
foldStateLoggingProvider =
- FoldStateLoggingProviderImpl(foldStateProvider, fakeClock).apply {
+ FoldStateLoggingProviderImpl(testFoldStateProvider, fakeClock).apply {
addCallback(foldStateLoggingListener)
init()
}
-
- verify(foldStateProvider).addCallback(foldUpdatesListener.capture())
}
@Test
@@ -183,10 +173,10 @@ class FoldStateLoggingProviderTest : SysuiTestCase() {
fun uninit_removesCallback() {
foldStateLoggingProvider.uninit()
- verify(foldStateProvider).removeCallback(foldUpdatesListener.value)
+ assertThat(testFoldStateProvider.hasListeners).isFalse()
}
private fun sendFoldUpdate(@FoldUpdate foldUpdate: Int) {
- foldUpdatesListener.value.onFoldUpdate(foldUpdate)
+ testFoldStateProvider.sendFoldUpdate(foldUpdate)
}
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/unfold/config/ResourceUnfoldTransitionConfigTest.kt b/packages/SystemUI/tests/src/com/android/systemui/unfold/config/ResourceUnfoldTransitionConfigTest.kt
new file mode 100644
index 000000000000..ab450e2506f9
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/unfold/config/ResourceUnfoldTransitionConfigTest.kt
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the
+ * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package com.android.systemui.unfold.config
+
+import android.testing.AndroidTestingRunner
+import androidx.test.filters.SmallTest
+import com.android.systemui.SysuiTestCase
+import com.google.common.truth.Truth.assertThat
+import org.junit.Test
+import org.junit.runner.RunWith
+
+
+/**
+ * A test that checks that we load correct resources in
+ * ResourceUnfoldTransitionConfig as we use strings there instead of R constants.
+ * Internal Android resource constants are not available in public APIs,
+ * so we can't use them there directly.
+ */
+@RunWith(AndroidTestingRunner::class)
+@SmallTest
+class ResourceUnfoldTransitionConfigTest : SysuiTestCase() {
+
+ private val config = ResourceUnfoldTransitionConfig()
+
+ @Test
+ fun testIsEnabled() {
+ assertThat(config.isEnabled).isEqualTo(mContext.resources
+ .getBoolean(com.android.internal.R.bool.config_unfoldTransitionEnabled))
+ }
+
+ @Test
+ fun testHingeAngleEnabled() {
+ assertThat(config.isHingeAngleEnabled).isEqualTo(mContext.resources
+ .getBoolean(com.android.internal.R.bool.config_unfoldTransitionHingeAngle))
+ }
+
+ @Test
+ fun testHalfFoldedTimeout() {
+ assertThat(config.halfFoldedTimeoutMillis).isEqualTo(mContext.resources
+ .getInteger(com.android.internal.R.integer.config_unfoldTransitionHalfFoldedTimeout))
+ }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/unfold/updates/DeviceFoldStateProviderTest.kt b/packages/SystemUI/tests/src/com/android/systemui/unfold/updates/DeviceFoldStateProviderTest.kt
index 1f1f88b07ea1..87fca1f23f1a 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/unfold/updates/DeviceFoldStateProviderTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/unfold/updates/DeviceFoldStateProviderTest.kt
@@ -16,82 +16,69 @@
package com.android.systemui.unfold.updates
-import android.app.ActivityManager
-import android.app.ActivityManager.RunningTaskInfo
-import android.app.WindowConfiguration.ACTIVITY_TYPE_HOME
-import android.app.WindowConfiguration.ACTIVITY_TYPE_STANDARD
-import android.app.WindowConfiguration.ActivityType
-import android.hardware.devicestate.DeviceStateManager
-import android.hardware.devicestate.DeviceStateManager.FoldStateListener
import android.os.Handler
import android.testing.AndroidTestingRunner
import androidx.core.util.Consumer
import androidx.test.filters.SmallTest
import com.android.systemui.SysuiTestCase
+import com.android.systemui.unfold.config.ResourceUnfoldTransitionConfig
+import com.android.systemui.unfold.config.UnfoldTransitionConfig
+import com.android.systemui.unfold.system.ActivityManagerActivityTypeProvider
+import com.android.systemui.unfold.updates.FoldProvider.FoldCallback
import com.android.systemui.unfold.updates.hinge.HingeAngleProvider
import com.android.systemui.unfold.updates.screen.ScreenStatusProvider
import com.android.systemui.unfold.updates.screen.ScreenStatusProvider.ScreenListener
-import com.android.systemui.unfold.util.FoldableDeviceStates
-import com.android.systemui.unfold.util.FoldableTestUtils
import com.android.systemui.util.mockito.any
import com.google.common.truth.Truth.assertThat
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
-import org.mockito.ArgumentCaptor
-import org.mockito.Captor
import org.mockito.Mock
-import org.mockito.Mockito.verify
-import org.mockito.Mockito.`when` as whenever
import org.mockito.MockitoAnnotations
+import java.util.concurrent.Executor
+import org.mockito.Mockito.`when` as whenever
@RunWith(AndroidTestingRunner::class)
@SmallTest
class DeviceFoldStateProviderTest : SysuiTestCase() {
- @Mock private lateinit var hingeAngleProvider: HingeAngleProvider
-
- @Mock private lateinit var screenStatusProvider: ScreenStatusProvider
-
- @Mock private lateinit var deviceStateManager: DeviceStateManager
-
- @Mock private lateinit var activityManager: ActivityManager
-
- @Mock private lateinit var handler: Handler
-
- @Captor private lateinit var foldStateListenerCaptor: ArgumentCaptor<FoldStateListener>
+ @Mock
+ private lateinit var activityTypeProvider: ActivityManagerActivityTypeProvider
- @Captor private lateinit var screenOnListenerCaptor: ArgumentCaptor<ScreenListener>
+ @Mock
+ private lateinit var handler: Handler
- @Captor private lateinit var hingeAngleCaptor: ArgumentCaptor<Consumer<Float>>
+ private val foldProvider = TestFoldProvider()
+ private val screenOnStatusProvider = TestScreenOnStatusProvider()
+ private val testHingeAngleProvider = TestHingeAngleProvider()
private lateinit var foldStateProvider: DeviceFoldStateProvider
private val foldUpdates: MutableList<Int> = arrayListOf()
private val hingeAngleUpdates: MutableList<Float> = arrayListOf()
- private lateinit var deviceStates: FoldableDeviceStates
-
private var scheduledRunnable: Runnable? = null
private var scheduledRunnableDelay: Long? = null
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
- overrideResource(
- com.android.internal.R.integer.config_unfoldTransitionHalfFoldedTimeout,
- HALF_OPENED_TIMEOUT_MILLIS.toInt())
- deviceStates = FoldableTestUtils.findDeviceStates(context)
+
+ val config = object : UnfoldTransitionConfig by ResourceUnfoldTransitionConfig() {
+ override val halfFoldedTimeoutMillis: Int
+ get() = HALF_OPENED_TIMEOUT_MILLIS.toInt()
+ }
foldStateProvider =
DeviceFoldStateProvider(
- context,
- hingeAngleProvider,
- screenStatusProvider,
- deviceStateManager,
- activityManager,
+ config,
+ testHingeAngleProvider,
+ screenOnStatusProvider,
+ foldProvider,
+ activityTypeProvider,
context.mainExecutor,
- handler)
+ handler
+ )
foldStateProvider.addCallback(
object : FoldStateProvider.FoldUpdatesListener {
@@ -105,10 +92,6 @@ class DeviceFoldStateProviderTest : SysuiTestCase() {
})
foldStateProvider.start()
- verify(deviceStateManager).registerCallback(any(), foldStateListenerCaptor.capture())
- verify(screenStatusProvider).addCallback(screenOnListenerCaptor.capture())
- verify(hingeAngleProvider).addCallback(hingeAngleCaptor.capture())
-
whenever(handler.postDelayed(any<Runnable>(), any())).then { invocationOnMock ->
scheduledRunnable = invocationOnMock.getArgument<Runnable>(0)
scheduledRunnableDelay = invocationOnMock.getArgument<Long>(1)
@@ -125,7 +108,7 @@ class DeviceFoldStateProviderTest : SysuiTestCase() {
}
// By default, we're on launcher.
- setupForegroundActivityType(ACTIVITY_TYPE_HOME)
+ setupForegroundActivityType(isHomeActivity = true)
}
@Test
@@ -146,14 +129,14 @@ class DeviceFoldStateProviderTest : SysuiTestCase() {
fun testOnFolded_stopsHingeAngleProvider() {
setFoldState(folded = true)
- verify(hingeAngleProvider).stop()
+ assertThat(testHingeAngleProvider.isStarted).isFalse()
}
@Test
fun testOnUnfolded_startsHingeAngleProvider() {
setFoldState(folded = false)
- verify(hingeAngleProvider).start()
+ assertThat(testHingeAngleProvider.isStarted).isTrue()
}
@Test
@@ -310,7 +293,7 @@ class DeviceFoldStateProviderTest : SysuiTestCase() {
@Test
fun startClosingEvent_whileNotOnLauncher_doesNotTriggerBeforeThreshold() {
- setupForegroundActivityType(ACTIVITY_TYPE_STANDARD)
+ setupForegroundActivityType(isHomeActivity = false)
sendHingeAngleEvent(180)
sendHingeAngleEvent(START_CLOSING_ON_APPS_THRESHOLD_DEGREES + 1)
@@ -319,8 +302,28 @@ class DeviceFoldStateProviderTest : SysuiTestCase() {
}
@Test
+ fun startClosingEvent_whileActivityTypeNotAvailable_triggerBeforeThreshold() {
+ setupForegroundActivityType(isHomeActivity = null)
+ sendHingeAngleEvent(180)
+
+ sendHingeAngleEvent(START_CLOSING_ON_APPS_THRESHOLD_DEGREES + 1)
+
+ assertThat(foldUpdates).containsExactly(FOLD_UPDATE_START_CLOSING)
+ }
+
+ @Test
+ fun startClosingEvent_whileOnLauncher_doesTriggerBeforeThreshold() {
+ setupForegroundActivityType(isHomeActivity = true)
+ sendHingeAngleEvent(180)
+
+ sendHingeAngleEvent(START_CLOSING_ON_APPS_THRESHOLD_DEGREES + 1)
+
+ assertThat(foldUpdates).containsExactly(FOLD_UPDATE_START_CLOSING)
+ }
+
+ @Test
fun startClosingEvent_whileNotOnLauncher_triggersAfterThreshold() {
- setupForegroundActivityType(ACTIVITY_TYPE_STANDARD)
+ setupForegroundActivityType(isHomeActivity = false)
sendHingeAngleEvent(START_CLOSING_ON_APPS_THRESHOLD_DEGREES)
sendHingeAngleEvent(START_CLOSING_ON_APPS_THRESHOLD_DEGREES - 1)
@@ -328,9 +331,8 @@ class DeviceFoldStateProviderTest : SysuiTestCase() {
assertThat(foldUpdates).containsExactly(FOLD_UPDATE_START_CLOSING)
}
- private fun setupForegroundActivityType(@ActivityType type: Int) {
- val taskInfo = RunningTaskInfo().apply { topActivityType = type }
- whenever(activityManager.getRunningTasks(1)).thenReturn(listOf(taskInfo))
+ private fun setupForegroundActivityType(isHomeActivity: Boolean?) {
+ whenever(activityTypeProvider.isHomeActivity).thenReturn(isHomeActivity)
}
private fun simulateTimeout(waitTime: Long = HALF_OPENED_TIMEOUT_MILLIS) {
@@ -348,16 +350,72 @@ class DeviceFoldStateProviderTest : SysuiTestCase() {
}
private fun setFoldState(folded: Boolean) {
- val state = if (folded) deviceStates.folded else deviceStates.unfolded
- foldStateListenerCaptor.value.onStateChanged(state)
+ foldProvider.notifyFolded(folded)
}
private fun fireScreenOnEvent() {
- screenOnListenerCaptor.value.onScreenTurnedOn()
+ screenOnStatusProvider.notifyScreenTurnedOn()
}
private fun sendHingeAngleEvent(angle: Int) {
- hingeAngleCaptor.value.accept(angle.toFloat())
+ testHingeAngleProvider.notifyAngle(angle.toFloat())
+ }
+
+ private class TestFoldProvider : FoldProvider {
+ private val callbacks = arrayListOf<FoldCallback>()
+
+ override fun registerCallback(callback: FoldCallback, executor: Executor) {
+ callbacks += callback
+ }
+
+ override fun unregisterCallback(callback: FoldCallback) {
+ callbacks -= callback
+ }
+
+ fun notifyFolded(isFolded: Boolean) {
+ callbacks.forEach { it.onFoldUpdated(isFolded) }
+ }
+ }
+
+ private class TestScreenOnStatusProvider : ScreenStatusProvider {
+ private val callbacks = arrayListOf<ScreenListener>()
+
+ override fun addCallback(listener: ScreenListener) {
+ callbacks += listener
+ }
+
+ override fun removeCallback(listener: ScreenListener) {
+ callbacks -= listener
+ }
+
+ fun notifyScreenTurnedOn() {
+ callbacks.forEach { it.onScreenTurnedOn() }
+ }
+ }
+
+ private class TestHingeAngleProvider : HingeAngleProvider {
+ private val callbacks = arrayListOf<Consumer<Float>>()
+ var isStarted: Boolean = false
+
+ override fun start() {
+ isStarted = true;
+ }
+
+ override fun stop() {
+ isStarted = false;
+ }
+
+ override fun addCallback(listener: Consumer<Float>) {
+ callbacks += listener
+ }
+
+ override fun removeCallback(listener: Consumer<Float>) {
+ callbacks -= listener
+ }
+
+ fun notifyAngle(angle: Float) {
+ callbacks.forEach { it.accept(angle) }
+ }
}
companion object {
diff --git a/packages/SystemUI/tests/src/com/android/systemui/unfold/util/NaturalRotationUnfoldProgressProviderTest.kt b/packages/SystemUI/tests/src/com/android/systemui/unfold/util/NaturalRotationUnfoldProgressProviderTest.kt
index a3f17aa5ba55..b2cedbf8d606 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/unfold/util/NaturalRotationUnfoldProgressProviderTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/unfold/util/NaturalRotationUnfoldProgressProviderTest.kt
@@ -20,18 +20,18 @@ import android.view.IRotationWatcher
import android.view.IWindowManager
import android.view.Surface
import androidx.test.filters.SmallTest
-import com.android.systemui.unfold.UnfoldTransitionProgressProvider
+import com.android.systemui.SysuiTestCase
+import com.android.systemui.unfold.TestUnfoldTransitionProvider
import com.android.systemui.unfold.UnfoldTransitionProgressProvider.TransitionProgressListener
import com.android.systemui.util.mockito.any
-import com.android.systemui.SysuiTestCase
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.ArgumentCaptor
import org.mockito.Mock
-import org.mockito.Mockito.verify
import org.mockito.Mockito.clearInvocations
import org.mockito.Mockito.never
+import org.mockito.Mockito.verify
import org.mockito.MockitoAnnotations
@RunWith(AndroidTestingRunner::class)
@@ -41,16 +41,13 @@ class NaturalRotationUnfoldProgressProviderTest : SysuiTestCase() {
@Mock
lateinit var windowManager: IWindowManager
- @Mock
- lateinit var sourceProvider: UnfoldTransitionProgressProvider
+ private val sourceProvider = TestUnfoldTransitionProvider()
@Mock
lateinit var transitionListener: TransitionProgressListener
lateinit var progressProvider: NaturalRotationUnfoldProgressProvider
- private val sourceProviderListenerCaptor =
- ArgumentCaptor.forClass(TransitionProgressListener::class.java)
private val rotationWatcherCaptor =
ArgumentCaptor.forClass(IRotationWatcher.Stub::class.java)
@@ -66,7 +63,6 @@ class NaturalRotationUnfoldProgressProviderTest : SysuiTestCase() {
progressProvider.init()
- verify(sourceProvider).addCallback(sourceProviderListenerCaptor.capture())
verify(windowManager).watchRotation(rotationWatcherCaptor.capture(), any())
progressProvider.addCallback(transitionListener)
@@ -76,7 +72,7 @@ class NaturalRotationUnfoldProgressProviderTest : SysuiTestCase() {
fun testNaturalRotation0_sendTransitionStartedEvent_eventReceived() {
onRotationChanged(Surface.ROTATION_0)
- source.onTransitionStarted()
+ sourceProvider.onTransitionStarted()
verify(transitionListener).onTransitionStarted()
}
@@ -85,7 +81,7 @@ class NaturalRotationUnfoldProgressProviderTest : SysuiTestCase() {
fun testNaturalRotation0_sendTransitionProgressEvent_eventReceived() {
onRotationChanged(Surface.ROTATION_0)
- source.onTransitionProgress(0.5f)
+ sourceProvider.onTransitionProgress(0.5f)
verify(transitionListener).onTransitionProgress(0.5f)
}
@@ -94,7 +90,7 @@ class NaturalRotationUnfoldProgressProviderTest : SysuiTestCase() {
fun testNotNaturalRotation90_sendTransitionStartedEvent_eventNotReceived() {
onRotationChanged(Surface.ROTATION_90)
- source.onTransitionStarted()
+ sourceProvider.onTransitionStarted()
verify(transitionListener, never()).onTransitionStarted()
}
@@ -103,7 +99,7 @@ class NaturalRotationUnfoldProgressProviderTest : SysuiTestCase() {
fun testNaturalRotation90_sendTransitionProgressEvent_eventNotReceived() {
onRotationChanged(Surface.ROTATION_90)
- source.onTransitionProgress(0.5f)
+ sourceProvider.onTransitionProgress(0.5f)
verify(transitionListener, never()).onTransitionProgress(0.5f)
}
@@ -111,7 +107,7 @@ class NaturalRotationUnfoldProgressProviderTest : SysuiTestCase() {
@Test
fun testRotationBecameUnnaturalDuringTransition_sendsTransitionFinishedEvent() {
onRotationChanged(Surface.ROTATION_0)
- source.onTransitionStarted()
+ sourceProvider.onTransitionStarted()
clearInvocations(transitionListener)
onRotationChanged(Surface.ROTATION_90)
@@ -122,7 +118,7 @@ class NaturalRotationUnfoldProgressProviderTest : SysuiTestCase() {
@Test
fun testRotationBecameNaturalDuringTransition_sendsTransitionStartedEvent() {
onRotationChanged(Surface.ROTATION_90)
- source.onTransitionStarted()
+ sourceProvider.onTransitionStarted()
clearInvocations(transitionListener)
onRotationChanged(Surface.ROTATION_0)
@@ -133,7 +129,4 @@ class NaturalRotationUnfoldProgressProviderTest : SysuiTestCase() {
private fun onRotationChanged(rotation: Int) {
rotationWatcherCaptor.value.onRotationChanged(rotation)
}
-
- private val source: TransitionProgressListener
- get() = sourceProviderListenerCaptor.value
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/unfold/util/ScaleAwareUnfoldProgressProviderTest.kt b/packages/SystemUI/tests/src/com/android/systemui/unfold/util/ScaleAwareUnfoldProgressProviderTest.kt
index db7a85166807..fc2a78a5ee7f 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/unfold/util/ScaleAwareUnfoldProgressProviderTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/unfold/util/ScaleAwareUnfoldProgressProviderTest.kt
@@ -21,6 +21,7 @@ import android.database.ContentObserver
import android.testing.AndroidTestingRunner
import androidx.test.filters.SmallTest
import com.android.systemui.SysuiTestCase
+import com.android.systemui.unfold.TestUnfoldTransitionProvider
import com.android.systemui.unfold.UnfoldTransitionProgressProvider
import com.android.systemui.unfold.UnfoldTransitionProgressProvider.TransitionProgressListener
import com.android.systemui.util.mockito.any
@@ -41,15 +42,11 @@ class ScaleAwareUnfoldProgressProviderTest : SysuiTestCase() {
lateinit var contentResolver: ContentResolver
@Mock
- lateinit var sourceProvider: UnfoldTransitionProgressProvider
-
- @Mock
lateinit var sinkProvider: TransitionProgressListener
- lateinit var progressProvider: ScaleAwareTransitionProgressProvider
+ private val sourceProvider = TestUnfoldTransitionProvider()
- private val sourceProviderListenerCaptor =
- ArgumentCaptor.forClass(TransitionProgressListener::class.java)
+ lateinit var progressProvider: ScaleAwareTransitionProgressProvider
private val animatorDurationScaleListenerCaptor =
ArgumentCaptor.forClass(ContentObserver::class.java)
@@ -63,7 +60,6 @@ class ScaleAwareUnfoldProgressProviderTest : SysuiTestCase() {
contentResolver
)
- verify(sourceProvider).addCallback(sourceProviderListenerCaptor.capture())
verify(contentResolver).registerContentObserver(any(), any(),
animatorDurationScaleListenerCaptor.capture())
@@ -74,7 +70,7 @@ class ScaleAwareUnfoldProgressProviderTest : SysuiTestCase() {
fun onTransitionStarted_animationsEnabled_eventReceived() {
setAnimationsEnabled(true)
- source.onTransitionStarted()
+ sourceProvider.onTransitionStarted()
verify(sinkProvider).onTransitionStarted()
}
@@ -83,7 +79,7 @@ class ScaleAwareUnfoldProgressProviderTest : SysuiTestCase() {
fun onTransitionStarted_animationsNotEnabled_eventNotReceived() {
setAnimationsEnabled(false)
- source.onTransitionStarted()
+ sourceProvider.onTransitionStarted()
verifyNoMoreInteractions(sinkProvider)
}
@@ -92,7 +88,7 @@ class ScaleAwareUnfoldProgressProviderTest : SysuiTestCase() {
fun onTransitionEnd_animationsEnabled_eventReceived() {
setAnimationsEnabled(true)
- source.onTransitionFinished()
+ sourceProvider.onTransitionFinished()
verify(sinkProvider).onTransitionFinished()
}
@@ -101,7 +97,7 @@ class ScaleAwareUnfoldProgressProviderTest : SysuiTestCase() {
fun onTransitionEnd_animationsNotEnabled_eventNotReceived() {
setAnimationsEnabled(false)
- source.onTransitionFinished()
+ sourceProvider.onTransitionFinished()
verifyNoMoreInteractions(sinkProvider)
}
@@ -110,7 +106,7 @@ class ScaleAwareUnfoldProgressProviderTest : SysuiTestCase() {
fun onTransitionProgress_animationsEnabled_eventReceived() {
setAnimationsEnabled(true)
- source.onTransitionProgress(42f)
+ sourceProvider.onTransitionProgress(42f)
verify(sinkProvider).onTransitionProgress(42f)
}
@@ -119,7 +115,7 @@ class ScaleAwareUnfoldProgressProviderTest : SysuiTestCase() {
fun onTransitionProgress_animationsNotEnabled_eventNotReceived() {
setAnimationsEnabled(false)
- source.onTransitionProgress(42f)
+ sourceProvider.onTransitionProgress(42f)
verifyNoMoreInteractions(sinkProvider)
}
@@ -133,7 +129,4 @@ class ScaleAwareUnfoldProgressProviderTest : SysuiTestCase() {
ValueAnimator.setDurationScale(durationScale)
animatorDurationScaleListenerCaptor.value.dispatchChange(/* selfChange= */false)
}
-
- private val source: TransitionProgressListener
- get() = sourceProviderListenerCaptor.value
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/unfold/util/TestFoldStateProvider.kt b/packages/SystemUI/tests/src/com/android/systemui/unfold/util/TestFoldStateProvider.kt
index 8f851ec60981..a064e8c81076 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/unfold/util/TestFoldStateProvider.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/unfold/util/TestFoldStateProvider.kt
@@ -24,6 +24,8 @@ import com.android.systemui.unfold.updates.FoldStateProvider.FoldUpdatesListener
class TestFoldStateProvider : FoldStateProvider {
private val listeners: MutableList<FoldUpdatesListener> = arrayListOf()
+ val hasListeners: Boolean
+ get() = listeners.isNotEmpty()
override fun start() {
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/util/ChannelsTest.java b/packages/SystemUI/tests/src/com/android/systemui/util/NotificationChannelsTest.java
index c7bcdefdc4c3..900d7928fb44 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/util/ChannelsTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/util/NotificationChannelsTest.java
@@ -28,7 +28,6 @@ import android.util.ArraySet;
import androidx.test.runner.AndroidJUnit4;
import com.android.systemui.SysuiTestCase;
-import com.android.systemui.util.NotificationChannels;
import org.junit.Before;
import org.junit.Test;
@@ -41,7 +40,7 @@ import java.util.Set;
@SmallTest
@RunWith(AndroidJUnit4.class)
-public class ChannelsTest extends SysuiTestCase {
+public class NotificationChannelsTest extends SysuiTestCase {
private final NotificationManager mMockNotificationManager = mock(NotificationManager.class);
@Before
@@ -55,9 +54,10 @@ public class ChannelsTest extends SysuiTestCase {
NotificationChannels.ALERTS,
NotificationChannels.SCREENSHOTS_HEADSUP,
NotificationChannels.STORAGE,
- NotificationChannels.GENERAL,
+ NotificationChannels.INSTANT,
NotificationChannels.BATTERY,
- NotificationChannels.HINTS
+ NotificationChannels.HINTS,
+ NotificationChannels.SETUP
));
NotificationChannels.createAll(mContext);
ArgumentCaptor<List> captor = ArgumentCaptor.forClass(List.class);
@@ -67,4 +67,11 @@ public class ChannelsTest extends SysuiTestCase {
list.forEach((chan) -> assertTrue(ALL_CHANNELS.contains(chan.getId())));
}
+ @Test
+ public void testChannelCleanup() {
+ new NotificationChannels(mContext).start();
+ ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
+ verify(mMockNotificationManager).deleteNotificationChannel(captor.capture());
+ assertEquals(NotificationChannels.GENERAL, captor.getValue());
+ }
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/util/collection/RingBufferTest.kt b/packages/SystemUI/tests/src/com/android/systemui/util/collection/RingBufferTest.kt
new file mode 100644
index 000000000000..5e09b81da4e8
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/util/collection/RingBufferTest.kt
@@ -0,0 +1,131 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.util.collection
+
+import android.testing.AndroidTestingRunner
+import androidx.test.filters.SmallTest
+import com.android.systemui.SysuiTestCase
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertSame
+import org.junit.Assert.assertThrows
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.mockito.MockitoAnnotations
+
+@SmallTest
+@RunWith(AndroidTestingRunner::class)
+class RingBufferTest : SysuiTestCase() {
+
+ private val buffer = RingBuffer(5) { TestElement() }
+
+ private val history = mutableListOf<TestElement>()
+
+ @Before
+ fun setUp() {
+ MockitoAnnotations.initMocks(this)
+ }
+
+ @Test
+ fun testBarelyFillBuffer() {
+ fillBuffer(5)
+
+ assertEquals(0, buffer[0].id)
+ assertEquals(1, buffer[1].id)
+ assertEquals(2, buffer[2].id)
+ assertEquals(3, buffer[3].id)
+ assertEquals(4, buffer[4].id)
+ }
+
+ @Test
+ fun testPartiallyFillBuffer() {
+ fillBuffer(3)
+
+ assertEquals(3, buffer.size)
+
+ assertEquals(0, buffer[0].id)
+ assertEquals(1, buffer[1].id)
+ assertEquals(2, buffer[2].id)
+
+ assertThrows(IndexOutOfBoundsException::class.java) { buffer[3] }
+ assertThrows(IndexOutOfBoundsException::class.java) { buffer[4] }
+ }
+
+ @Test
+ fun testSpinBuffer() {
+ fillBuffer(277)
+
+ assertEquals(272, buffer[0].id)
+ assertEquals(273, buffer[1].id)
+ assertEquals(274, buffer[2].id)
+ assertEquals(275, buffer[3].id)
+ assertEquals(276, buffer[4].id)
+ assertThrows(IndexOutOfBoundsException::class.java) { buffer[5] }
+
+ assertEquals(5, buffer.size)
+ }
+
+ @Test
+ fun testElementsAreRecycled() {
+ fillBuffer(23)
+
+ assertSame(history[4], buffer[1])
+ assertSame(history[9], buffer[1])
+ assertSame(history[14], buffer[1])
+ assertSame(history[19], buffer[1])
+ }
+
+ @Test
+ fun testIterator() {
+ fillBuffer(13)
+
+ val iterator = buffer.iterator()
+
+ for (i in 0 until 5) {
+ assertEquals(history[8 + i], iterator.next())
+ }
+ assertFalse(iterator.hasNext())
+ assertThrows(NoSuchElementException::class.java) { iterator.next() }
+ }
+
+ @Test
+ fun testForEach() {
+ fillBuffer(13)
+ var i = 8
+
+ buffer.forEach {
+ assertEquals(history[i], it)
+ i++
+ }
+ assertEquals(13, i)
+ }
+
+ private fun fillBuffer(count: Int) {
+ for (i in 0 until count) {
+ val elem = buffer.advance()
+ elem.id = history.size
+ history.add(elem)
+ }
+ }
+}
+
+private class TestElement(var id: Int = 0) {
+ override fun toString(): String {
+ return "{TestElement $id}"
+ }
+} \ No newline at end of file
diff --git a/packages/SystemUI/tests/src/com/android/systemui/volume/VolumeDialogImplTest.java b/packages/SystemUI/tests/src/com/android/systemui/volume/VolumeDialogImplTest.java
index 949345662e79..312db2d7066a 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/volume/VolumeDialogImplTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/volume/VolumeDialogImplTest.java
@@ -38,6 +38,7 @@ import android.view.accessibility.AccessibilityManager;
import androidx.test.filters.SmallTest;
+import com.android.internal.jank.InteractionJankMonitor;
import com.android.systemui.Prefs;
import com.android.systemui.R;
import com.android.systemui.SysuiTestCase;
@@ -85,6 +86,8 @@ public class VolumeDialogImplTest extends SysuiTestCase {
MediaOutputDialogFactory mMediaOutputDialogFactory;
@Mock
ActivityStarter mActivityStarter;
+ @Mock
+ InteractionJankMonitor mInteractionJankMonitor;
@Before
public void setup() throws Exception {
@@ -99,7 +102,8 @@ public class VolumeDialogImplTest extends SysuiTestCase {
mDeviceProvisionedController,
mConfigurationController,
mMediaOutputDialogFactory,
- mActivityStarter);
+ mActivityStarter,
+ mInteractionJankMonitor);
mDialog.init(0, null);
State state = createShellState();
mDialog.onStateChangedH(state);
diff --git a/packages/SystemUI/tests/src/com/android/systemui/wallet/controller/QuickAccessWalletControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/wallet/controller/QuickAccessWalletControllerTest.java
index de2efc71b3a9..8e4f184f560e 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/wallet/controller/QuickAccessWalletControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/wallet/controller/QuickAccessWalletControllerTest.java
@@ -100,7 +100,6 @@ public class QuickAccessWalletControllerTest extends SysuiTestCase {
mContext,
MoreExecutors.directExecutor(),
MoreExecutors.directExecutor(),
- MoreExecutors.directExecutor(),
mSecureSettings,
mQuickAccessWalletClient,
mClock);
diff --git a/packages/SystemUI/tests/src/com/android/systemui/wmshell/TestableBubbleController.java b/packages/SystemUI/tests/src/com/android/systemui/wmshell/TestableBubbleController.java
index 9646edf6756a..9ca6bb0af8d5 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/wmshell/TestableBubbleController.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/wmshell/TestableBubbleController.java
@@ -69,7 +69,7 @@ public class TestableBubbleController extends BubbleController {
statusBarService, windowManager, windowManagerShellWrapper, launcherApps,
bubbleLogger, taskStackListener, shellTaskOrganizer, positioner, displayController,
oneHandedOptional, dragAndDropController, shellMainExecutor, shellMainHandler,
- taskViewTransitions, syncQueue);
+ new SyncExecutor(), taskViewTransitions, syncQueue);
setInflateSynchronously(true);
initialize();
}
diff --git a/packages/SystemUI/unfold/Android.bp b/packages/SystemUI/unfold/Android.bp
new file mode 100644
index 000000000000..108295b90e58
--- /dev/null
+++ b/packages/SystemUI/unfold/Android.bp
@@ -0,0 +1,39 @@
+// Copyright (C) 2022 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package {
+ // See: http://go/android-license-faq
+ // A large-scale-change added 'default_applicable_licenses' to import
+ // all of the 'license_kinds' from "frameworks_base_packages_SystemUI_license"
+ // to get the below license kinds:
+ // SPDX-license-identifier-Apache-2.0
+ default_applicable_licenses: ["frameworks_base_packages_SystemUI_license"],
+}
+
+android_library {
+ name: "SystemUIUnfoldLib",
+ srcs: [
+ "src/**/*.java",
+ "src/**/*.kt",
+ "src/**/*.aidl",
+ ],
+ static_libs: [
+ "androidx.dynamicanimation_dynamicanimation",
+ "dagger2",
+ "jsr330",
+ ],
+ java_version: "1.8",
+ min_sdk_version: "current",
+ plugins: ["dagger2-compiler"],
+}
diff --git a/packages/SystemUI/unfold/AndroidManifest.xml b/packages/SystemUI/unfold/AndroidManifest.xml
new file mode 100644
index 000000000000..ee8afe1aff5b
--- /dev/null
+++ b/packages/SystemUI/unfold/AndroidManifest.xml
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ Copyright (C) 2017 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ package="com.android.systemui.unfold">
+
+
+</manifest>
diff --git a/packages/SystemUI/unfold/lint-baseline.xml b/packages/SystemUI/unfold/lint-baseline.xml
new file mode 100644
index 000000000000..449ed2e60853
--- /dev/null
+++ b/packages/SystemUI/unfold/lint-baseline.xml
@@ -0,0 +1,3 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<issues format="6" by="lint 7.1.0-dev" type="baseline" client="" name="" variant="all" version="7.1.0-dev">
+</issues>
diff --git a/packages/SystemUI/shared/src/com/android/systemui/unfold/UnfoldSharedComponent.kt b/packages/SystemUI/unfold/src/com/android/systemui/unfold/UnfoldSharedComponent.kt
index 9e5aeb84b624..a5ec0a454412 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/unfold/UnfoldSharedComponent.kt
+++ b/packages/SystemUI/unfold/src/com/android/systemui/unfold/UnfoldSharedComponent.kt
@@ -16,16 +16,16 @@
package com.android.systemui.unfold
-import android.app.ActivityManager
import android.content.ContentResolver
import android.content.Context
import android.hardware.SensorManager
-import android.hardware.devicestate.DeviceStateManager
import android.os.Handler
-import com.android.systemui.dagger.qualifiers.Main
-import com.android.systemui.dagger.qualifiers.UiBackground
import com.android.systemui.unfold.config.UnfoldTransitionConfig
+import com.android.systemui.unfold.dagger.UnfoldBackground
+import com.android.systemui.unfold.dagger.UnfoldMain
+import com.android.systemui.unfold.updates.FoldProvider
import com.android.systemui.unfold.updates.screen.ScreenStatusProvider
+import com.android.systemui.unfold.util.CurrentActivityTypeProvider
import com.android.systemui.unfold.util.UnfoldTransitionATracePrefix
import dagger.BindsInstance
import dagger.Component
@@ -51,12 +51,12 @@ internal interface UnfoldSharedComponent {
@BindsInstance context: Context,
@BindsInstance config: UnfoldTransitionConfig,
@BindsInstance screenStatusProvider: ScreenStatusProvider,
- @BindsInstance deviceStateManager: DeviceStateManager,
- @BindsInstance activityManager: ActivityManager,
+ @BindsInstance foldProvider: FoldProvider,
+ @BindsInstance activityTypeProvider: CurrentActivityTypeProvider,
@BindsInstance sensorManager: SensorManager,
- @BindsInstance @Main handler: Handler,
- @BindsInstance @Main executor: Executor,
- @BindsInstance @UiBackground backgroundExecutor: Executor,
+ @BindsInstance @UnfoldMain handler: Handler,
+ @BindsInstance @UnfoldMain executor: Executor,
+ @BindsInstance @UnfoldBackground backgroundExecutor: Executor,
@BindsInstance @UnfoldTransitionATracePrefix tracingTagPrefix: String,
@BindsInstance contentResolver: ContentResolver = context.contentResolver
): UnfoldSharedComponent
diff --git a/packages/SystemUI/shared/src/com/android/systemui/unfold/UnfoldSharedModule.kt b/packages/SystemUI/unfold/src/com/android/systemui/unfold/UnfoldSharedModule.kt
index c612995241ef..8f4ee4dc9838 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/unfold/UnfoldSharedModule.kt
+++ b/packages/SystemUI/unfold/src/com/android/systemui/unfold/UnfoldSharedModule.kt
@@ -17,8 +17,8 @@
package com.android.systemui.unfold
import android.hardware.SensorManager
-import com.android.systemui.dagger.qualifiers.UiBackground
import com.android.systemui.unfold.config.UnfoldTransitionConfig
+import com.android.systemui.unfold.dagger.UnfoldBackground
import com.android.systemui.unfold.progress.FixedTimingTransitionProgressProvider
import com.android.systemui.unfold.progress.PhysicsBasedUnfoldTransitionProgressProvider
import com.android.systemui.unfold.updates.DeviceFoldStateProvider
@@ -70,7 +70,7 @@ class UnfoldSharedModule {
fun hingeAngleProvider(
config: UnfoldTransitionConfig,
sensorManager: SensorManager,
- @UiBackground executor: Executor
+ @UnfoldBackground executor: Executor
): HingeAngleProvider =
if (config.isHingeAngleEnabled) {
HingeSensorAngleProvider(sensorManager, executor)
diff --git a/packages/SystemUI/shared/src/com/android/systemui/unfold/UnfoldTransitionFactory.kt b/packages/SystemUI/unfold/src/com/android/systemui/unfold/UnfoldTransitionFactory.kt
index cc56007c431a..402dd8474bc4 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/unfold/UnfoldTransitionFactory.kt
+++ b/packages/SystemUI/unfold/src/com/android/systemui/unfold/UnfoldTransitionFactory.kt
@@ -17,14 +17,13 @@
package com.android.systemui.unfold
-import android.app.ActivityManager
import android.content.Context
import android.hardware.SensorManager
-import android.hardware.devicestate.DeviceStateManager
import android.os.Handler
-import com.android.systemui.unfold.config.ResourceUnfoldTransitionConfig
import com.android.systemui.unfold.config.UnfoldTransitionConfig
+import com.android.systemui.unfold.updates.FoldProvider
import com.android.systemui.unfold.updates.screen.ScreenStatusProvider
+import com.android.systemui.unfold.util.CurrentActivityTypeProvider
import java.util.concurrent.Executor
/**
@@ -39,8 +38,8 @@ fun createUnfoldTransitionProgressProvider(
context: Context,
config: UnfoldTransitionConfig,
screenStatusProvider: ScreenStatusProvider,
- deviceStateManager: DeviceStateManager,
- activityManager: ActivityManager,
+ foldProvider: FoldProvider,
+ activityTypeProvider: CurrentActivityTypeProvider,
sensorManager: SensorManager,
mainHandler: Handler,
mainExecutor: Executor,
@@ -52,8 +51,8 @@ fun createUnfoldTransitionProgressProvider(
context,
config,
screenStatusProvider,
- deviceStateManager,
- activityManager,
+ foldProvider,
+ activityTypeProvider,
sensorManager,
mainHandler,
mainExecutor,
@@ -64,5 +63,3 @@ fun createUnfoldTransitionProgressProvider(
?: throw IllegalStateException(
"Trying to create " +
"UnfoldTransitionProgressProvider when the transition is disabled")
-
-fun createConfig(context: Context): UnfoldTransitionConfig = ResourceUnfoldTransitionConfig(context)
diff --git a/packages/SystemUI/shared/src/com/android/systemui/unfold/UnfoldTransitionProgressProvider.kt b/packages/SystemUI/unfold/src/com/android/systemui/unfold/UnfoldTransitionProgressProvider.kt
index 409dc95ab131..d54481c72bfd 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/unfold/UnfoldTransitionProgressProvider.kt
+++ b/packages/SystemUI/unfold/src/com/android/systemui/unfold/UnfoldTransitionProgressProvider.kt
@@ -15,9 +15,9 @@
*/
package com.android.systemui.unfold
-import android.annotation.FloatRange
-import com.android.systemui.statusbar.policy.CallbackController
+import androidx.annotation.FloatRange
import com.android.systemui.unfold.UnfoldTransitionProgressProvider.TransitionProgressListener
+import com.android.systemui.unfold.util.CallbackController
/**
* Interface that allows to receive unfold transition progress updates.
diff --git a/packages/SystemUI/unfold/src/com/android/systemui/unfold/compat/ScreenSizeFoldProvider.kt b/packages/SystemUI/unfold/src/com/android/systemui/unfold/compat/ScreenSizeFoldProvider.kt
new file mode 100644
index 000000000000..2044f05664d0
--- /dev/null
+++ b/packages/SystemUI/unfold/src/com/android/systemui/unfold/compat/ScreenSizeFoldProvider.kt
@@ -0,0 +1,56 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the
+ * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package com.android.systemui.unfold.compat
+
+import android.content.Context
+import android.content.res.Configuration
+import com.android.systemui.unfold.updates.FoldProvider
+import com.android.systemui.unfold.updates.FoldProvider.FoldCallback
+import java.util.concurrent.Executor
+
+/**
+ * Fold provider that notifies about fold state based on the screen size
+ * It could be used when no activity context is available
+ * TODO(b/232369816): use Jetpack WM library when non-activity contexts supported b/169740873
+ */
+class ScreenSizeFoldProvider(private val context: Context) : FoldProvider {
+
+ private var callbacks: MutableList<FoldCallback> = arrayListOf()
+ private var lastWidth: Int = 0
+
+ override fun registerCallback(callback: FoldCallback, executor: Executor) {
+ callbacks += callback
+ onConfigurationChange(context.resources.configuration)
+ }
+
+ override fun unregisterCallback(callback: FoldCallback) {
+ callbacks -= callback
+ }
+
+ fun onConfigurationChange(newConfig: Configuration) {
+ if (lastWidth == newConfig.smallestScreenWidthDp) {
+ return
+ }
+
+ if (newConfig.smallestScreenWidthDp > INNER_SCREEN_SMALLEST_SCREEN_WIDTH_THRESHOLD_DP) {
+ callbacks.forEach { it.onFoldUpdated(false) }
+ } else {
+ callbacks.forEach { it.onFoldUpdated(true) }
+ }
+ lastWidth = newConfig.smallestScreenWidthDp
+ }
+}
+
+private const val INNER_SCREEN_SMALLEST_SCREEN_WIDTH_THRESHOLD_DP = 600
diff --git a/packages/SystemUI/unfold/src/com/android/systemui/unfold/compat/SizeScreenStatusProvider.kt b/packages/SystemUI/unfold/src/com/android/systemui/unfold/compat/SizeScreenStatusProvider.kt
new file mode 100644
index 000000000000..c405f3110297
--- /dev/null
+++ b/packages/SystemUI/unfold/src/com/android/systemui/unfold/compat/SizeScreenStatusProvider.kt
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the
+ * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package com.android.systemui.unfold.compat
+
+import com.android.systemui.unfold.updates.FoldProvider
+import com.android.systemui.unfold.updates.screen.ScreenStatusProvider
+import com.android.systemui.unfold.updates.screen.ScreenStatusProvider.ScreenListener
+import java.util.concurrent.Executor
+
+class SizeScreenStatusProvider(
+ private val foldProvider: FoldProvider,
+ private val executor: Executor
+) : ScreenStatusProvider {
+
+ private val listeners: MutableList<ScreenListener> = arrayListOf()
+ private val callback = object : FoldProvider.FoldCallback {
+ override fun onFoldUpdated(isFolded: Boolean) {
+ if (!isFolded) {
+ listeners.forEach { it.onScreenTurnedOn() }
+ }
+ }
+ }
+
+ fun start() {
+ foldProvider.registerCallback(
+ callback,
+ executor
+ )
+ }
+
+ fun stop() {
+ foldProvider.unregisterCallback(callback)
+ }
+
+ override fun addCallback(listener: ScreenListener) {
+ listeners.add(listener)
+ }
+
+ override fun removeCallback(listener: ScreenListener) {
+ listeners.remove(listener)
+ }
+}
diff --git a/packages/SystemUI/unfold/src/com/android/systemui/unfold/config/ResourceUnfoldTransitionConfig.kt b/packages/SystemUI/unfold/src/com/android/systemui/unfold/config/ResourceUnfoldTransitionConfig.kt
new file mode 100644
index 000000000000..c51372975a67
--- /dev/null
+++ b/packages/SystemUI/unfold/src/com/android/systemui/unfold/config/ResourceUnfoldTransitionConfig.kt
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the
+ * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package com.android.systemui.unfold.config
+
+import android.content.res.Resources
+import javax.inject.Inject
+import javax.inject.Singleton
+
+@Singleton
+class ResourceUnfoldTransitionConfig @Inject constructor() : UnfoldTransitionConfig {
+
+ override val isEnabled: Boolean by lazy {
+ val id = Resources.getSystem()
+ .getIdentifier("config_unfoldTransitionEnabled", "bool", "android")
+ Resources.getSystem().getBoolean(id)
+ }
+
+ override val isHingeAngleEnabled: Boolean by lazy {
+ val id = Resources.getSystem()
+ .getIdentifier("config_unfoldTransitionHingeAngle", "bool", "android")
+ Resources.getSystem().getBoolean(id)
+ }
+
+ override val halfFoldedTimeoutMillis: Int by lazy {
+ val id = Resources.getSystem()
+ .getIdentifier("config_unfoldTransitionHalfFoldedTimeout", "integer", "android")
+ Resources.getSystem().getInteger(id)
+ }
+}
diff --git a/packages/SystemUI/shared/src/com/android/systemui/unfold/config/UnfoldTransitionConfig.kt b/packages/SystemUI/unfold/src/com/android/systemui/unfold/config/UnfoldTransitionConfig.kt
index 5b187b3486c6..765e862aa00d 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/unfold/config/UnfoldTransitionConfig.kt
+++ b/packages/SystemUI/unfold/src/com/android/systemui/unfold/config/UnfoldTransitionConfig.kt
@@ -18,4 +18,5 @@ package com.android.systemui.unfold.config
interface UnfoldTransitionConfig {
val isEnabled: Boolean
val isHingeAngleEnabled: Boolean
+ val halfFoldedTimeoutMillis: Int
}
diff --git a/packages/SystemUI/unfold/src/com/android/systemui/unfold/dagger/UnfoldBackground.kt b/packages/SystemUI/unfold/src/com/android/systemui/unfold/dagger/UnfoldBackground.kt
new file mode 100644
index 000000000000..60747954dac3
--- /dev/null
+++ b/packages/SystemUI/unfold/src/com/android/systemui/unfold/dagger/UnfoldBackground.kt
@@ -0,0 +1,25 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the
+ * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package com.android.systemui.unfold.dagger
+
+import javax.inject.Qualifier
+
+/**
+ * Alternative to [UiBackground] qualifier annotation in unfold module.
+ * It is needed as we can't depend on SystemUI code in this module.
+ */
+@Qualifier
+@Retention(AnnotationRetention.RUNTIME)
+annotation class UnfoldBackground
diff --git a/packages/SystemUI/unfold/src/com/android/systemui/unfold/dagger/UnfoldMain.kt b/packages/SystemUI/unfold/src/com/android/systemui/unfold/dagger/UnfoldMain.kt
new file mode 100644
index 000000000000..5553690fb562
--- /dev/null
+++ b/packages/SystemUI/unfold/src/com/android/systemui/unfold/dagger/UnfoldMain.kt
@@ -0,0 +1,25 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the
+ * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package com.android.systemui.unfold.dagger
+
+import javax.inject.Qualifier
+
+/**
+ * Alternative to [Main] qualifier annotation in unfold module.
+ * It is needed as we can't depend on SystemUI code in this module.
+ */
+@Qualifier
+@Retention(AnnotationRetention.RUNTIME)
+annotation class UnfoldMain
diff --git a/packages/SystemUI/shared/src/com/android/systemui/unfold/progress/FixedTimingTransitionProgressProvider.kt b/packages/SystemUI/unfold/src/com/android/systemui/unfold/progress/FixedTimingTransitionProgressProvider.kt
index 4c85b055aeae..4c85b055aeae 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/unfold/progress/FixedTimingTransitionProgressProvider.kt
+++ b/packages/SystemUI/unfold/src/com/android/systemui/unfold/progress/FixedTimingTransitionProgressProvider.kt
diff --git a/packages/SystemUI/shared/src/com/android/systemui/unfold/progress/PhysicsBasedUnfoldTransitionProgressProvider.kt b/packages/SystemUI/unfold/src/com/android/systemui/unfold/progress/PhysicsBasedUnfoldTransitionProgressProvider.kt
index 04d920cb15d5..2ab28c65f32f 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/unfold/progress/PhysicsBasedUnfoldTransitionProgressProvider.kt
+++ b/packages/SystemUI/unfold/src/com/android/systemui/unfold/progress/PhysicsBasedUnfoldTransitionProgressProvider.kt
@@ -16,7 +16,6 @@
package com.android.systemui.unfold.progress
import android.util.Log
-import android.util.MathUtils.saturate
import androidx.dynamicanimation.animation.DynamicAnimation
import androidx.dynamicanimation.animation.FloatPropertyCompat
import androidx.dynamicanimation.animation.SpringAnimation
@@ -70,6 +69,9 @@ class PhysicsBasedUnfoldTransitionProgressProvider(
springAnimation.animateToFinalPosition(progress)
}
+ private fun saturate(amount: Float, low: Float = 0f, high: Float = 1f): Float =
+ if (amount < low) low else if (amount > high) high else amount
+
override fun onFoldUpdate(@FoldUpdate update: Int) {
when (update) {
FOLD_UPDATE_UNFOLDED_SCREEN_AVAILABLE -> {
diff --git a/packages/SystemUI/shared/src/com/android/systemui/unfold/updates/DeviceFoldStateProvider.kt b/packages/SystemUI/unfold/src/com/android/systemui/unfold/updates/DeviceFoldStateProvider.kt
index 14581ccd5c0a..e8038fd7dfa6 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/unfold/updates/DeviceFoldStateProvider.kt
+++ b/packages/SystemUI/unfold/src/com/android/systemui/unfold/updates/DeviceFoldStateProvider.kt
@@ -15,46 +15,46 @@
*/
package com.android.systemui.unfold.updates
-import android.annotation.FloatRange
-import android.app.ActivityManager
-import android.app.WindowConfiguration.ACTIVITY_TYPE_HOME
-import android.content.Context
-import android.hardware.devicestate.DeviceStateManager
import android.os.Handler
import android.util.Log
+import androidx.annotation.FloatRange
import androidx.annotation.VisibleForTesting
import androidx.core.util.Consumer
-import com.android.systemui.dagger.qualifiers.Main
+import com.android.systemui.unfold.config.UnfoldTransitionConfig
+import com.android.systemui.unfold.dagger.UnfoldMain
import com.android.systemui.unfold.updates.FoldStateProvider.FoldUpdate
import com.android.systemui.unfold.updates.FoldStateProvider.FoldUpdatesListener
import com.android.systemui.unfold.updates.hinge.FULLY_CLOSED_DEGREES
import com.android.systemui.unfold.updates.hinge.FULLY_OPEN_DEGREES
import com.android.systemui.unfold.updates.hinge.HingeAngleProvider
import com.android.systemui.unfold.updates.screen.ScreenStatusProvider
+import com.android.systemui.unfold.util.CurrentActivityTypeProvider
import java.util.concurrent.Executor
import javax.inject.Inject
class DeviceFoldStateProvider
@Inject
constructor(
- context: Context,
+ config: UnfoldTransitionConfig,
private val hingeAngleProvider: HingeAngleProvider,
private val screenStatusProvider: ScreenStatusProvider,
- private val deviceStateManager: DeviceStateManager,
- private val activityManager: ActivityManager,
- @Main private val mainExecutor: Executor,
- @Main private val handler: Handler
+ private val foldProvider: FoldProvider,
+ private val activityTypeProvider: CurrentActivityTypeProvider,
+ @UnfoldMain private val mainExecutor: Executor,
+ @UnfoldMain private val handler: Handler
) : FoldStateProvider {
private val outputListeners: MutableList<FoldUpdatesListener> = mutableListOf()
- @FoldUpdate private var lastFoldUpdate: Int? = null
+ @FoldUpdate
+ private var lastFoldUpdate: Int? = null
- @FloatRange(from = 0.0, to = 180.0) private var lastHingeAngle: Float = 0f
+ @FloatRange(from = 0.0, to = 180.0)
+ private var lastHingeAngle: Float = 0f
private val hingeAngleListener = HingeAngleListener()
private val screenListener = ScreenStatusListener()
- private val foldStateListener = FoldStateListener(context)
+ private val foldStateListener = FoldStateListener()
private val timeoutRunnable = TimeoutRunnable()
/**
@@ -62,22 +62,20 @@ constructor(
* [FOLD_UPDATE_START_CLOSING] or [FOLD_UPDATE_START_OPENING] event, if an end state is not
* reached.
*/
- private val halfOpenedTimeoutMillis: Int =
- context.resources.getInteger(
- com.android.internal.R.integer.config_unfoldTransitionHalfFoldedTimeout)
+ private val halfOpenedTimeoutMillis: Int = config.halfFoldedTimeoutMillis
private var isFolded = false
private var isUnfoldHandled = true
override fun start() {
- deviceStateManager.registerCallback(mainExecutor, foldStateListener)
+ foldProvider.registerCallback(foldStateListener, mainExecutor)
screenStatusProvider.addCallback(screenListener)
hingeAngleProvider.addCallback(hingeAngleListener)
}
override fun stop() {
screenStatusProvider.removeCallback(screenListener)
- deviceStateManager.unregisterCallback(foldStateListener)
+ foldProvider.unregisterCallback(foldStateListener)
hingeAngleProvider.removeCallback(hingeAngleListener)
hingeAngleProvider.stop()
}
@@ -92,13 +90,13 @@ constructor(
override val isFinishedOpening: Boolean
get() = !isFolded &&
- (lastFoldUpdate == FOLD_UPDATE_FINISH_FULL_OPEN ||
- lastFoldUpdate == FOLD_UPDATE_FINISH_HALF_OPEN)
+ (lastFoldUpdate == FOLD_UPDATE_FINISH_FULL_OPEN ||
+ lastFoldUpdate == FOLD_UPDATE_FINISH_HALF_OPEN)
private val isTransitionInProgress: Boolean
get() =
lastFoldUpdate == FOLD_UPDATE_START_OPENING ||
- lastFoldUpdate == FOLD_UPDATE_START_CLOSING
+ lastFoldUpdate == FOLD_UPDATE_START_CLOSING
private fun onHingeAngle(angle: Float) {
if (DEBUG) {
@@ -136,39 +134,36 @@ constructor(
* apps that support table-top/HALF_FOLDED mode. Only for launcher, there is no threshold.
*/
private fun getClosingThreshold(): Int? {
- val activityType =
- activityManager.getRunningTasks(/* maxNum= */ 1)?.getOrNull(0)?.topActivityType
- ?: return null
+ val isHomeActivity = activityTypeProvider.isHomeActivity ?: return null
if (DEBUG) {
- Log.d(TAG, "activityType=" + activityType)
+ Log.d(TAG, "isHomeActivity=$isHomeActivity")
}
- return if (activityType == ACTIVITY_TYPE_HOME) {
+ return if (isHomeActivity) {
null
} else {
START_CLOSING_ON_APPS_THRESHOLD_DEGREES
}
}
- private inner class FoldStateListener(context: Context) :
- DeviceStateManager.FoldStateListener(
- context,
- { folded: Boolean ->
- isFolded = folded
- lastHingeAngle = FULLY_CLOSED_DEGREES
-
- if (folded) {
- hingeAngleProvider.stop()
- notifyFoldUpdate(FOLD_UPDATE_FINISH_CLOSED)
- cancelTimeout()
- isUnfoldHandled = false
- } else {
- notifyFoldUpdate(FOLD_UPDATE_START_OPENING)
- rescheduleAbortAnimationTimeout()
- hingeAngleProvider.start()
- }
- })
+ private inner class FoldStateListener : FoldProvider.FoldCallback {
+ override fun onFoldUpdated(isFolded: Boolean) {
+ this@DeviceFoldStateProvider.isFolded = isFolded
+ lastHingeAngle = FULLY_CLOSED_DEGREES
+
+ if (isFolded) {
+ hingeAngleProvider.stop()
+ notifyFoldUpdate(FOLD_UPDATE_FINISH_CLOSED)
+ cancelTimeout()
+ isUnfoldHandled = false
+ } else {
+ notifyFoldUpdate(FOLD_UPDATE_START_OPENING)
+ rescheduleAbortAnimationTimeout()
+ hingeAngleProvider.start()
+ }
+ }
+ }
private fun notifyFoldUpdate(@FoldUpdate update: Int) {
if (DEBUG) {
@@ -234,7 +229,9 @@ private const val TAG = "DeviceFoldProvider"
private const val DEBUG = false
/** Threshold after which we consider the device fully unfolded. */
-@VisibleForTesting const val FULLY_OPEN_THRESHOLD_DEGREES = 15f
+@VisibleForTesting
+const val FULLY_OPEN_THRESHOLD_DEGREES = 15f
/** Fold animation on top of apps only when the angle exceeds this threshold. */
-@VisibleForTesting const val START_CLOSING_ON_APPS_THRESHOLD_DEGREES = 60
+@VisibleForTesting
+const val START_CLOSING_ON_APPS_THRESHOLD_DEGREES = 60
diff --git a/packages/SystemUI/unfold/src/com/android/systemui/unfold/updates/FoldProvider.kt b/packages/SystemUI/unfold/src/com/android/systemui/unfold/updates/FoldProvider.kt
new file mode 100644
index 000000000000..6e87beeb295f
--- /dev/null
+++ b/packages/SystemUI/unfold/src/com/android/systemui/unfold/updates/FoldProvider.kt
@@ -0,0 +1,26 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the
+ * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package com.android.systemui.unfold.updates
+
+import java.util.concurrent.Executor
+
+interface FoldProvider {
+ fun registerCallback(callback: FoldCallback, executor: Executor)
+ fun unregisterCallback(callback: FoldCallback)
+
+ interface FoldCallback {
+ fun onFoldUpdated(isFolded: Boolean)
+ }
+}
diff --git a/packages/SystemUI/shared/src/com/android/systemui/unfold/updates/FoldStateProvider.kt b/packages/SystemUI/unfold/src/com/android/systemui/unfold/updates/FoldStateProvider.kt
index 14a3a70fc6b0..c7a8bf336777 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/unfold/updates/FoldStateProvider.kt
+++ b/packages/SystemUI/unfold/src/com/android/systemui/unfold/updates/FoldStateProvider.kt
@@ -15,10 +15,10 @@
*/
package com.android.systemui.unfold.updates
-import android.annotation.FloatRange
-import android.annotation.IntDef
-import com.android.systemui.statusbar.policy.CallbackController
+import androidx.annotation.FloatRange
+import androidx.annotation.IntDef
import com.android.systemui.unfold.updates.FoldStateProvider.FoldUpdatesListener
+import com.android.systemui.unfold.util.CallbackController
/**
* Allows to subscribe to main events related to fold/unfold process such as hinge angle update,
@@ -36,7 +36,6 @@ interface FoldStateProvider : CallbackController<FoldUpdatesListener> {
}
@IntDef(
- prefix = ["FOLD_UPDATE_"],
value =
[
FOLD_UPDATE_START_OPENING,
diff --git a/packages/SystemUI/unfold/src/com/android/systemui/unfold/updates/hinge/EmptyHingeAngleProvider.kt b/packages/SystemUI/unfold/src/com/android/systemui/unfold/updates/hinge/EmptyHingeAngleProvider.kt
new file mode 100644
index 000000000000..e985506bd989
--- /dev/null
+++ b/packages/SystemUI/unfold/src/com/android/systemui/unfold/updates/hinge/EmptyHingeAngleProvider.kt
@@ -0,0 +1,27 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the
+ * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package com.android.systemui.unfold.updates.hinge
+
+import androidx.core.util.Consumer
+
+internal object EmptyHingeAngleProvider : HingeAngleProvider {
+ override fun start() {}
+
+ override fun stop() {}
+
+ override fun removeCallback(listener: Consumer<Float>) {}
+
+ override fun addCallback(listener: Consumer<Float>) {}
+}
diff --git a/packages/SystemUI/unfold/src/com/android/systemui/unfold/updates/hinge/HingeAngleProvider.kt b/packages/SystemUI/unfold/src/com/android/systemui/unfold/updates/hinge/HingeAngleProvider.kt
new file mode 100644
index 000000000000..e464c3f81546
--- /dev/null
+++ b/packages/SystemUI/unfold/src/com/android/systemui/unfold/updates/hinge/HingeAngleProvider.kt
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the
+ * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package com.android.systemui.unfold.updates.hinge
+
+import androidx.core.util.Consumer
+import com.android.systemui.unfold.util.CallbackController
+
+/**
+ * Emits device hinge angle values (angle between two integral parts of the device).
+ *
+ * The hinge angle could be from 0 to 360 degrees inclusive. For foldable devices usually 0
+ * corresponds to fully closed (folded) state and 180 degrees corresponds to fully open (flat)
+ * state.
+ */
+interface HingeAngleProvider : CallbackController<Consumer<Float>> {
+ fun start()
+ fun stop()
+}
+
+const val FULLY_OPEN_DEGREES = 180f
+const val FULLY_CLOSED_DEGREES = 0f
diff --git a/packages/SystemUI/shared/src/com/android/systemui/unfold/updates/hinge/HingeSensorAngleProvider.kt b/packages/SystemUI/unfold/src/com/android/systemui/unfold/updates/hinge/HingeSensorAngleProvider.kt
index c93412b53817..3fc5d610dc2d 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/unfold/updates/hinge/HingeSensorAngleProvider.kt
+++ b/packages/SystemUI/unfold/src/com/android/systemui/unfold/updates/hinge/HingeSensorAngleProvider.kt
@@ -1,3 +1,17 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the
+ * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
package com.android.systemui.unfold.updates.hinge
import android.hardware.Sensor
diff --git a/packages/SystemUI/shared/src/com/android/systemui/unfold/updates/screen/ScreenStatusProvider.kt b/packages/SystemUI/unfold/src/com/android/systemui/unfold/updates/screen/ScreenStatusProvider.kt
index 668c69442cac..d95e050474de 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/unfold/updates/screen/ScreenStatusProvider.kt
+++ b/packages/SystemUI/unfold/src/com/android/systemui/unfold/updates/screen/ScreenStatusProvider.kt
@@ -15,8 +15,8 @@
*/
package com.android.systemui.unfold.updates.screen
-import com.android.systemui.statusbar.policy.CallbackController
import com.android.systemui.unfold.updates.screen.ScreenStatusProvider.ScreenListener
+import com.android.systemui.unfold.util.CallbackController
interface ScreenStatusProvider : CallbackController<ScreenListener> {
diff --git a/packages/SystemUI/shared/src/com/android/systemui/unfold/util/ATraceLoggerTransitionProgressListener.kt b/packages/SystemUI/unfold/src/com/android/systemui/unfold/util/ATraceLoggerTransitionProgressListener.kt
index 1574c8d37ab1..d8bc01804f14 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/unfold/util/ATraceLoggerTransitionProgressListener.kt
+++ b/packages/SystemUI/unfold/src/com/android/systemui/unfold/util/ATraceLoggerTransitionProgressListener.kt
@@ -1,3 +1,17 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the
+ * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
package com.android.systemui.unfold.util
import android.os.Trace
diff --git a/packages/SystemUI/unfold/src/com/android/systemui/unfold/util/CallbackController.kt b/packages/SystemUI/unfold/src/com/android/systemui/unfold/util/CallbackController.kt
new file mode 100644
index 000000000000..46ad534722cd
--- /dev/null
+++ b/packages/SystemUI/unfold/src/com/android/systemui/unfold/util/CallbackController.kt
@@ -0,0 +1,20 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the
+ * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package com.android.systemui.unfold.util
+
+interface CallbackController<T> {
+ fun addCallback(listener: T)
+ fun removeCallback(listener: T)
+}
diff --git a/packages/SystemUI/unfold/src/com/android/systemui/unfold/util/CurrentActivityTypeProvider.kt b/packages/SystemUI/unfold/src/com/android/systemui/unfold/util/CurrentActivityTypeProvider.kt
new file mode 100644
index 000000000000..d0e6cdc9a3c6
--- /dev/null
+++ b/packages/SystemUI/unfold/src/com/android/systemui/unfold/util/CurrentActivityTypeProvider.kt
@@ -0,0 +1,22 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the
+ * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package com.android.systemui.unfold.util
+
+interface CurrentActivityTypeProvider {
+ val isHomeActivity: Boolean?
+}
+
+class EmptyCurrentActivityTypeProvider(override val isHomeActivity: Boolean? = null) :
+ CurrentActivityTypeProvider
diff --git a/packages/SystemUI/shared/src/com/android/systemui/unfold/util/ScaleAwareTransitionProgressProvider.kt b/packages/SystemUI/unfold/src/com/android/systemui/unfold/util/ScaleAwareTransitionProgressProvider.kt
index dfe87921dd42..5c92b3499835 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/unfold/util/ScaleAwareTransitionProgressProvider.kt
+++ b/packages/SystemUI/unfold/src/com/android/systemui/unfold/util/ScaleAwareTransitionProgressProvider.kt
@@ -1,3 +1,17 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the
+ * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
package com.android.systemui.unfold.util
import android.animation.ValueAnimator
diff --git a/packages/SystemUI/shared/src/com/android/systemui/unfold/util/ScopedUnfoldTransitionProgressProvider.kt b/packages/SystemUI/unfold/src/com/android/systemui/unfold/util/ScopedUnfoldTransitionProgressProvider.kt
index 8491f832b740..8491f832b740 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/unfold/util/ScopedUnfoldTransitionProgressProvider.kt
+++ b/packages/SystemUI/unfold/src/com/android/systemui/unfold/util/ScopedUnfoldTransitionProgressProvider.kt
diff --git a/packages/overlays/NavigationBarModeGesturalOverlay/res/values/dimens.xml b/packages/overlays/NavigationBarModeGesturalOverlay/res/values/dimens.xml
index ac1f0226be52..674bc749bc11 100644
--- a/packages/overlays/NavigationBarModeGesturalOverlay/res/values/dimens.xml
+++ b/packages/overlays/NavigationBarModeGesturalOverlay/res/values/dimens.xml
@@ -18,11 +18,11 @@
-->
<resources>
<!-- Height of the bottom navigation / system bar. -->
- <dimen name="navigation_bar_height">16dp</dimen>
+ <dimen name="navigation_bar_height">24dp</dimen>
<!-- Height of the bottom navigation bar in portrait; often the same as @dimen/navigation_bar_height -->
- <dimen name="navigation_bar_height_landscape">16dp</dimen>
+ <dimen name="navigation_bar_height_landscape">24dp</dimen>
<!-- Width of the navigation bar when it is placed vertically on the screen -->
- <dimen name="navigation_bar_width">16dp</dimen>
+ <dimen name="navigation_bar_width">24dp</dimen>
<!-- Height of the bottom navigation / system bar. -->
<dimen name="navigation_bar_frame_height">48dp</dimen>
<!-- The height of the bottom navigation gesture area. -->
diff --git a/packages/overlays/NavigationBarModeGesturalOverlayExtraWideBack/res/values/dimens.xml b/packages/overlays/NavigationBarModeGesturalOverlayExtraWideBack/res/values/dimens.xml
index ac1f0226be52..674bc749bc11 100644
--- a/packages/overlays/NavigationBarModeGesturalOverlayExtraWideBack/res/values/dimens.xml
+++ b/packages/overlays/NavigationBarModeGesturalOverlayExtraWideBack/res/values/dimens.xml
@@ -18,11 +18,11 @@
-->
<resources>
<!-- Height of the bottom navigation / system bar. -->
- <dimen name="navigation_bar_height">16dp</dimen>
+ <dimen name="navigation_bar_height">24dp</dimen>
<!-- Height of the bottom navigation bar in portrait; often the same as @dimen/navigation_bar_height -->
- <dimen name="navigation_bar_height_landscape">16dp</dimen>
+ <dimen name="navigation_bar_height_landscape">24dp</dimen>
<!-- Width of the navigation bar when it is placed vertically on the screen -->
- <dimen name="navigation_bar_width">16dp</dimen>
+ <dimen name="navigation_bar_width">24dp</dimen>
<!-- Height of the bottom navigation / system bar. -->
<dimen name="navigation_bar_frame_height">48dp</dimen>
<!-- The height of the bottom navigation gesture area. -->
diff --git a/packages/overlays/NavigationBarModeGesturalOverlayNarrowBack/res/values/dimens.xml b/packages/overlays/NavigationBarModeGesturalOverlayNarrowBack/res/values/dimens.xml
index ac1f0226be52..674bc749bc11 100644
--- a/packages/overlays/NavigationBarModeGesturalOverlayNarrowBack/res/values/dimens.xml
+++ b/packages/overlays/NavigationBarModeGesturalOverlayNarrowBack/res/values/dimens.xml
@@ -18,11 +18,11 @@
-->
<resources>
<!-- Height of the bottom navigation / system bar. -->
- <dimen name="navigation_bar_height">16dp</dimen>
+ <dimen name="navigation_bar_height">24dp</dimen>
<!-- Height of the bottom navigation bar in portrait; often the same as @dimen/navigation_bar_height -->
- <dimen name="navigation_bar_height_landscape">16dp</dimen>
+ <dimen name="navigation_bar_height_landscape">24dp</dimen>
<!-- Width of the navigation bar when it is placed vertically on the screen -->
- <dimen name="navigation_bar_width">16dp</dimen>
+ <dimen name="navigation_bar_width">24dp</dimen>
<!-- Height of the bottom navigation / system bar. -->
<dimen name="navigation_bar_frame_height">48dp</dimen>
<!-- The height of the bottom navigation gesture area. -->
diff --git a/packages/overlays/NavigationBarModeGesturalOverlayWideBack/res/values/dimens.xml b/packages/overlays/NavigationBarModeGesturalOverlayWideBack/res/values/dimens.xml
index ac1f0226be52..674bc749bc11 100644
--- a/packages/overlays/NavigationBarModeGesturalOverlayWideBack/res/values/dimens.xml
+++ b/packages/overlays/NavigationBarModeGesturalOverlayWideBack/res/values/dimens.xml
@@ -18,11 +18,11 @@
-->
<resources>
<!-- Height of the bottom navigation / system bar. -->
- <dimen name="navigation_bar_height">16dp</dimen>
+ <dimen name="navigation_bar_height">24dp</dimen>
<!-- Height of the bottom navigation bar in portrait; often the same as @dimen/navigation_bar_height -->
- <dimen name="navigation_bar_height_landscape">16dp</dimen>
+ <dimen name="navigation_bar_height_landscape">24dp</dimen>
<!-- Width of the navigation bar when it is placed vertically on the screen -->
- <dimen name="navigation_bar_width">16dp</dimen>
+ <dimen name="navigation_bar_width">24dp</dimen>
<!-- Height of the bottom navigation / system bar. -->
<dimen name="navigation_bar_frame_height">48dp</dimen>
<!-- The height of the bottom navigation gesture area. -->
diff --git a/services/autofill/java/com/android/server/autofill/Session.java b/services/autofill/java/com/android/server/autofill/Session.java
index 6d3620fa2ee6..ca0a7806898c 100644
--- a/services/autofill/java/com/android/server/autofill/Session.java
+++ b/services/autofill/java/com/android/server/autofill/Session.java
@@ -1965,15 +1965,6 @@ final class Session implements RemoteFillService.FillServiceCallbacks, ViewState
}
}
}
- final AutofillId[] fieldClassificationIds = lastResponse.getFieldClassificationIds();
-
- if (!hasAtLeastOneDataset && fieldClassificationIds == null) {
- if (sVerbose) {
- Slog.v(TAG, "logContextCommittedLocked(): skipped (no datasets nor fields "
- + "classification ids)");
- }
- return;
- }
for (int i = 0; i < mViewStates.size(); i++) {
final ViewState viewState = mViewStates.valueAt(i);
@@ -2022,6 +2013,7 @@ final class Session implements RemoteFillService.FillServiceCallbacks, ViewState
}
continue;
}
+
// Check if value match a dataset.
if (hasAtLeastOneDataset) {
for (int j = 0; j < responseCount; j++) {
@@ -2078,7 +2070,6 @@ final class Session implements RemoteFillService.FillServiceCallbacks, ViewState
} // else
} // for j
}
-
} // else
} // else
}
diff --git a/services/backup/backuplib/java/com/android/server/backup/transport/TransportStatusCallback.java b/services/backup/backuplib/java/com/android/server/backup/transport/TransportStatusCallback.java
index bc5cb0250d56..99526b7ef0d1 100644
--- a/services/backup/backuplib/java/com/android/server/backup/transport/TransportStatusCallback.java
+++ b/services/backup/backuplib/java/com/android/server/backup/transport/TransportStatusCallback.java
@@ -26,7 +26,7 @@ import com.android.internal.backup.ITransportStatusCallback;
public class TransportStatusCallback extends ITransportStatusCallback.Stub {
private static final String TAG = "TransportStatusCallback";
- private static final int TIMEOUT_MILLIS = 600 * 1000; // 10 minutes.
+ private static final int TIMEOUT_MILLIS = 300 * 1000; // 5 minutes.
private static final int OPERATION_STATUS_DEFAULT = 0;
private final int mOperationTimeout;
diff --git a/services/companion/java/com/android/server/companion/AssociationRequestsProcessor.java b/services/companion/java/com/android/server/companion/AssociationRequestsProcessor.java
index 7a5fa628f645..570e4e6fdc3d 100644
--- a/services/companion/java/com/android/server/companion/AssociationRequestsProcessor.java
+++ b/services/companion/java/com/android/server/companion/AssociationRequestsProcessor.java
@@ -182,7 +182,7 @@ class AssociationRequestsProcessor {
// 2b.1. Populate the request with required info.
request.setPackageName(packageName);
request.setUserId(userId);
- request.setSkipPrompt(mayAssociateWithoutPrompt(request, packageName, userId));
+ request.setSkipPrompt(mayAssociateWithoutPrompt(packageName, userId));
// 2b.2. Prepare extras and create an Intent.
final Bundle extras = new Bundle();
@@ -321,18 +321,7 @@ class AssociationRequestsProcessor {
}
};
- private boolean mayAssociateWithoutPrompt(@NonNull AssociationRequest request,
- @NonNull String packageName, @UserIdInt int userId) {
- final String deviceProfile = request.getDeviceProfile();
- if (deviceProfile != null) {
- final boolean isRoleHolder = Binder.withCleanCallingIdentity(
- () -> isRoleHolder(mContext, userId, packageName, deviceProfile));
- if (isRoleHolder) {
- // Don't need to collect user's consent since app already holds the role.
- return true;
- }
- }
-
+ private boolean mayAssociateWithoutPrompt(@NonNull String packageName, @UserIdInt int userId) {
// Below we check if the requesting package is allowlisted (usually by the OEM) for creating
// CDM associations without user confirmation (prompt).
// For this we'll check to config arrays:
diff --git a/services/companion/java/com/android/server/companion/CompanionDeviceManagerService.java b/services/companion/java/com/android/server/companion/CompanionDeviceManagerService.java
index 9b2554fdbb3c..0bfe2825bdd5 100644
--- a/services/companion/java/com/android/server/companion/CompanionDeviceManagerService.java
+++ b/services/companion/java/com/android/server/companion/CompanionDeviceManagerService.java
@@ -78,6 +78,7 @@ import android.os.RemoteException;
import android.os.ResultReceiver;
import android.os.ServiceManager;
import android.os.ShellCallback;
+import android.os.SystemProperties;
import android.os.UserHandle;
import android.os.UserManager;
import android.util.ArraySet;
@@ -121,8 +122,10 @@ public class CompanionDeviceManagerService extends SystemService {
private static final String PREF_FILE_NAME = "companion_device_preferences.xml";
private static final String PREF_KEY_AUTO_REVOKE_GRANTS_DONE = "auto_revoke_grants_done";
+ private static final String SYS_PROP_DEBUG_REMOVAL_TIME_WINDOW =
+ "debug.cdm.cdmservice.removal_time_window";
- private static final long ASSOCIATION_CLEAN_UP_TIME_WINDOW = DAYS.toMillis(3 * 30); // 3 months
+ private static final long ASSOCIATION_REMOVAL_TIME_WINDOW_DEFAULT = DAYS.toMillis(90);
private PersistentDataStore mPersistentStore;
private final PersistUserStateHandler mUserPersistenceHandler;
@@ -211,8 +214,8 @@ public class CompanionDeviceManagerService extends SystemService {
mPackageMonitor.register(context, FgThread.get().getLooper(), UserHandle.ALL, true);
mDevicePresenceMonitor.init(context);
} else if (phase == PHASE_BOOT_COMPLETED) {
- // Run the Association CleanUp job service daily.
- AssociationCleanUpService.schedule(getContext());
+ // Run the Inactive Association Removal job service daily.
+ InactiveAssociationsRemovalService.schedule(getContext());
}
}
@@ -410,17 +413,20 @@ public class CompanionDeviceManagerService extends SystemService {
mCompanionAppController.onPackagesChanged(userId);
}
- // Revoke associations if the selfManaged companion device does not connect for 3
- // months for specific profile.
- private void associationCleanUp(String profile) {
+ // Revoke associations if the selfManaged companion device does not connect for 3 months.
+ void removeInactiveSelfManagedAssociations() {
+ final long currentTime = System.currentTimeMillis();
+ long removalWindow = SystemProperties.getLong(SYS_PROP_DEBUG_REMOVAL_TIME_WINDOW, -1);
+ if (removalWindow <= 0) {
+ // 0 or negative values indicate that the sysprop was never set or should be ignored.
+ removalWindow = ASSOCIATION_REMOVAL_TIME_WINDOW_DEFAULT;
+ }
+
for (AssociationInfo ai : mAssociationStore.getAssociations()) {
- if (ai.isSelfManaged()
- && profile.equals(ai.getDeviceProfile())
- && System.currentTimeMillis() - ai.getLastTimeConnectedMs()
- >= ASSOCIATION_CLEAN_UP_TIME_WINDOW) {
- Slog.i(TAG, "Removing the association for associationId: "
- + ai.getId()
- + " due to the device does not connect for 3 months.");
+ if (!ai.isSelfManaged()) continue;
+ final boolean isInactive = currentTime - ai.getLastTimeConnectedMs() >= removalWindow;
+ if (isInactive) {
+ Slog.i(TAG, "Removing inactive self-managed association: " + ai.getId());
disassociateInternal(ai.getId());
}
}
@@ -649,6 +655,12 @@ public class CompanionDeviceManagerService extends SystemService {
private void registerDevicePresenceListenerActive(String packageName, String deviceAddress,
boolean active) throws RemoteException {
+ if (DEBUG) {
+ Log.i(TAG, "registerDevicePresenceListenerActive()"
+ + " active=" + active
+ + " deviceAddress=" + deviceAddress);
+ }
+
getContext().enforceCallingOrSelfPermission(
android.Manifest.permission.REQUEST_OBSERVE_COMPANION_DEVICE_PRESENCE,
"[un]registerDevicePresenceListenerService");
@@ -664,6 +676,12 @@ public class CompanionDeviceManagerService extends SystemService {
+ " for user " + userId));
}
+ // If already at specified state, then no-op.
+ if (active == association.isNotifyOnDeviceNearby()) {
+ if (DEBUG) Log.d(TAG, "Device presence listener is already at desired state.");
+ return;
+ }
+
// AssociationInfo class is immutable: create a new AssociationInfo object with updated
// flag.
association = AssociationInfo.builder(association)
@@ -674,7 +692,17 @@ public class CompanionDeviceManagerService extends SystemService {
// an application sets/unsets the mNotifyOnDeviceNearby flag.
mAssociationStore.updateAssociation(association);
- // TODO(b/218615198): correctly handle the case when the device is currently present.
+ // If device is already present, then trigger callback.
+ if (active && mDevicePresenceMonitor.isDevicePresent(association.getId())) {
+ if (DEBUG) Log.d(TAG, "Device is already present. Triggering callback.");
+ onDeviceAppearedInternal(association.getId());
+ }
+
+ // If last listener is unregistered, then unbind application.
+ if (!active && !shouldBindPackage(userId, packageName)) {
+ if (DEBUG) Log.d(TAG, "Last listener unregistered. Unbinding application.");
+ mCompanionAppController.unbindCompanionApplication(userId, packageName);
+ }
}
@Override
@@ -1056,10 +1084,10 @@ public class CompanionDeviceManagerService extends SystemService {
return ArrayUtils.contains(array, a) || ArrayUtils.contains(array, b);
}
- private class LocalService extends CompanionDeviceManagerServiceInternal {
+ private class LocalService implements CompanionDeviceManagerServiceInternal {
@Override
- public void associationCleanUp(String profile) {
- CompanionDeviceManagerService.this.associationCleanUp(profile);
+ public void removeInactiveSelfManagedAssociations() {
+ CompanionDeviceManagerService.this.removeInactiveSelfManagedAssociations();
}
}
diff --git a/services/companion/java/com/android/server/companion/CompanionDeviceManagerServiceInternal.java b/services/companion/java/com/android/server/companion/CompanionDeviceManagerServiceInternal.java
index 326fefe1f8ea..36492407d463 100644
--- a/services/companion/java/com/android/server/companion/CompanionDeviceManagerServiceInternal.java
+++ b/services/companion/java/com/android/server/companion/CompanionDeviceManagerServiceInternal.java
@@ -18,12 +18,10 @@ package com.android.server.companion;
/**
* Companion Device Manager Local System Service Interface.
- *
- * @hide Only for use within the system server.
*/
-public abstract class CompanionDeviceManagerServiceInternal {
+interface CompanionDeviceManagerServiceInternal {
/**
- * @see CompanionDeviceManagerService#associationCleanUp
+ * @see CompanionDeviceManagerService#removeInactiveSelfManagedAssociations
*/
- public abstract void associationCleanUp(String profile);
+ void removeInactiveSelfManagedAssociations();
}
diff --git a/services/companion/java/com/android/server/companion/CompanionDeviceShellCommand.java b/services/companion/java/com/android/server/companion/CompanionDeviceShellCommand.java
index 6a19a42723c5..434d283b3f8a 100644
--- a/services/companion/java/com/android/server/companion/CompanionDeviceShellCommand.java
+++ b/services/companion/java/com/android/server/companion/CompanionDeviceShellCommand.java
@@ -17,6 +17,7 @@
package com.android.server.companion;
import android.companion.AssociationInfo;
+import android.os.Binder;
import android.os.ShellCommand;
import android.util.Log;
import android.util.Slog;
@@ -96,6 +97,16 @@ class CompanionDeviceShellCommand extends ShellCommand {
mDevicePresenceMonitor.simulateDeviceDisappeared(associationId);
break;
+ case "remove-inactive-associations": {
+ // This command should trigger the same "clean-up" job as performed by the
+ // InactiveAssociationsRemovalService JobService. However, since the
+ // InactiveAssociationsRemovalService run as system, we want to run this
+ // as system (not as shell/root) as well.
+ Binder.withCleanCallingIdentity(
+ mService::removeInactiveSelfManagedAssociations);
+ }
+ break;
+
default:
return handleDefaultCommands(cmd);
}
@@ -142,6 +153,12 @@ class CompanionDeviceShellCommand extends ShellCommand {
pw.println(" invoked for the same device (same ASSOCIATION_ID) no longer than");
pw.println(" 60 seconds ago.");
pw.println(" USE FOR DEBUGGING AND/OR TESTING PURPOSES ONLY.");
+
+ pw.println(" remove-inactive-associations");
+ pw.println(" Remove self-managed associations that have not been active ");
+ pw.println(" for a long time (90 days or as configured via ");
+ pw.println(" \"debug.cdm.cdmservice.cleanup_time_window\" system property). ");
+ pw.println(" USE FOR DEBUGGING AND/OR TESTING PURPOSES ONLY.");
}
private int getNextIntArgRequired() {
diff --git a/services/companion/java/com/android/server/companion/AssociationCleanUpService.java b/services/companion/java/com/android/server/companion/InactiveAssociationsRemovalService.java
index 55246e14d592..3482863032f9 100644
--- a/services/companion/java/com/android/server/companion/AssociationCleanUpService.java
+++ b/services/companion/java/com/android/server/companion/InactiveAssociationsRemovalService.java
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2021 The Android Open Source Project
+ * Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -24,10 +24,8 @@ import android.app.job.JobInfo;
import android.app.job.JobParameters;
import android.app.job.JobScheduler;
import android.app.job.JobService;
-import android.companion.AssociationRequest;
import android.content.ComponentName;
import android.content.Context;
-import android.os.AsyncTask;
import android.util.Slog;
import com.android.server.LocalServices;
@@ -37,26 +35,24 @@ import com.android.server.LocalServices;
* The job will be executed only if the device is charging and in idle mode due to the application
* will be killed if association/role are revoked.
*/
-public class AssociationCleanUpService extends JobService {
- private static final int JOB_ID = AssociationCleanUpService.class.hashCode();
+public class InactiveAssociationsRemovalService extends JobService {
+ private static final int JOB_ID = InactiveAssociationsRemovalService.class.hashCode();
private static final long ONE_DAY_INTERVAL = DAYS.toMillis(1);
@Override
public boolean onStartJob(final JobParameters params) {
- Slog.i(TAG, "Execute the Association CleanUp job");
- // Special policy for APP_STREAMING role that need to revoke associations if the device
- // does not connect for 3 months.
- AsyncTask.execute(() -> {
- LocalServices.getService(CompanionDeviceManagerServiceInternal.class)
- .associationCleanUp(AssociationRequest.DEVICE_PROFILE_APP_STREAMING);
- jobFinished(params, false);
- });
+ Slog.i(TAG, "Execute the Association Removal job");
+ // Special policy for selfManaged that need to revoke associations if the device
+ // does not connect for 90 days.
+ LocalServices.getService(CompanionDeviceManagerServiceInternal.class)
+ .removeInactiveSelfManagedAssociations();
+ jobFinished(params, false);
return true;
}
@Override
public boolean onStopJob(final JobParameters params) {
- Slog.i(TAG, "Association cleanup job stopped; id=" + params.getJobId()
+ Slog.i(TAG, "Association removal job stopped; id=" + params.getJobId()
+ ", reason="
+ JobParameters.getInternalReasonCodeDescription(
params.getInternalStopReasonCode()));
@@ -64,10 +60,10 @@ public class AssociationCleanUpService extends JobService {
}
static void schedule(Context context) {
- Slog.i(TAG, "Scheduling the Association Cleanup job");
+ Slog.i(TAG, "Scheduling the Association Removal job");
final JobScheduler jobScheduler = context.getSystemService(JobScheduler.class);
final JobInfo job = new JobInfo.Builder(JOB_ID,
- new ComponentName(context, AssociationCleanUpService.class))
+ new ComponentName(context, InactiveAssociationsRemovalService.class))
.setRequiresCharging(true)
.setRequiresDeviceIdle(true)
.setPeriodic(ONE_DAY_INTERVAL)
@@ -75,3 +71,4 @@ public class AssociationCleanUpService extends JobService {
jobScheduler.schedule(job);
}
}
+
diff --git a/services/companion/java/com/android/server/companion/virtual/InputController.java b/services/companion/java/com/android/server/companion/virtual/InputController.java
index 80182d26003d..dc7573e20438 100644
--- a/services/companion/java/com/android/server/companion/virtual/InputController.java
+++ b/services/companion/java/com/android/server/companion/virtual/InputController.java
@@ -37,6 +37,7 @@ import android.util.ArrayMap;
import android.util.Slog;
import android.view.Display;
import android.view.InputDevice;
+import android.view.WindowManager;
import com.android.internal.annotations.GuardedBy;
import com.android.internal.annotations.VisibleForTesting;
@@ -83,22 +84,26 @@ class InputController {
private final NativeWrapper mNativeWrapper;
private final DisplayManagerInternal mDisplayManagerInternal;
private final InputManagerInternal mInputManagerInternal;
+ private final WindowManager mWindowManager;
private final DeviceCreationThreadVerifier mThreadVerifier;
- InputController(@NonNull Object lock, @NonNull Handler handler) {
- this(lock, new NativeWrapper(), handler,
+ InputController(@NonNull Object lock, @NonNull Handler handler,
+ @NonNull WindowManager windowManager) {
+ this(lock, new NativeWrapper(), handler, windowManager,
// Verify that virtual devices are not created on the handler thread.
() -> !handler.getLooper().isCurrentThread());
}
@VisibleForTesting
InputController(@NonNull Object lock, @NonNull NativeWrapper nativeWrapper,
- @NonNull Handler handler, @NonNull DeviceCreationThreadVerifier threadVerifier) {
+ @NonNull Handler handler, @NonNull WindowManager windowManager,
+ @NonNull DeviceCreationThreadVerifier threadVerifier) {
mLock = lock;
mHandler = handler;
mNativeWrapper = nativeWrapper;
mDisplayManagerInternal = LocalServices.getService(DisplayManagerInternal.class);
mInputManagerInternal = LocalServices.getService(InputManagerInternal.class);
+ mWindowManager = windowManager;
mThreadVerifier = threadVerifier;
}
@@ -209,6 +214,15 @@ class InputController {
mInputManagerInternal.setDisplayEligibilityForPointerCapture(displayId, isEligible);
}
+ void setLocalIme(int displayId) {
+ // WM throws a SecurityException if the display is untrusted.
+ if ((mDisplayManagerInternal.getDisplayInfo(displayId).flags & Display.FLAG_TRUSTED)
+ == Display.FLAG_TRUSTED) {
+ mWindowManager.setDisplayImePolicy(displayId,
+ WindowManager.DISPLAY_IME_POLICY_LOCAL);
+ }
+ }
+
@GuardedBy("mLock")
private void updateActivePointerDisplayIdLocked() {
InputDeviceDescriptor mostRecentlyCreatedMouse = null;
diff --git a/services/companion/java/com/android/server/companion/virtual/VirtualDeviceImpl.java b/services/companion/java/com/android/server/companion/virtual/VirtualDeviceImpl.java
index 9802b9783da2..638b3aeef544 100644
--- a/services/companion/java/com/android/server/companion/virtual/VirtualDeviceImpl.java
+++ b/services/companion/java/com/android/server/companion/virtual/VirtualDeviceImpl.java
@@ -62,6 +62,7 @@ import android.util.ArraySet;
import android.util.Slog;
import android.util.SparseArray;
import android.view.Display;
+import android.view.WindowManager;
import android.widget.Toast;
import android.window.DisplayWindowPolicyController;
@@ -167,7 +168,9 @@ final class VirtualDeviceImpl extends IVirtualDevice.Stub
mParams = params;
if (inputController == null) {
mInputController = new InputController(
- mVirtualDeviceLock, context.getMainThreadHandler());
+ mVirtualDeviceLock,
+ context.getMainThreadHandler(),
+ context.getSystemService(WindowManager.class));
} else {
mInputController = inputController;
}
@@ -537,6 +540,7 @@ final class VirtualDeviceImpl extends IVirtualDevice.Stub
mInputController.setPointerAcceleration(1f, displayId);
mInputController.setDisplayEligibilityForPointerCapture(/* isEligible= */ false,
displayId);
+ mInputController.setLocalIme(displayId);
// Since we're being called in the middle of the display being created, we post a
// task to grab the wakelock instead of doing it synchronously here, to avoid
diff --git a/services/contentcapture/java/com/android/server/contentcapture/ContentCaptureManagerService.java b/services/contentcapture/java/com/android/server/contentcapture/ContentCaptureManagerService.java
index 61d784ecb5f3..ad6e7dbebae9 100644
--- a/services/contentcapture/java/com/android/server/contentcapture/ContentCaptureManagerService.java
+++ b/services/contentcapture/java/com/android/server/contentcapture/ContentCaptureManagerService.java
@@ -730,7 +730,7 @@ public final class ContentCaptureManagerService extends
String serviceName = mServiceNameResolver.getServiceName(userId);
ContentCaptureMetricsLogger.writeServiceEvent(
EVENT__DATA_SHARE_ERROR_CONCURRENT_REQUEST,
- serviceName, request.getPackageName());
+ serviceName);
clientAdapter.error(
ContentCaptureManager.DATA_SHARE_ERROR_CONCURRENT_REQUEST);
} catch (RemoteException e) {
@@ -1303,8 +1303,7 @@ public final class ContentCaptureManagerService extends
private void logServiceEvent(int eventType) {
int userId = UserHandle.getCallingUserId();
String serviceName = mParentService.mServiceNameResolver.getServiceName(userId);
- ContentCaptureMetricsLogger.writeServiceEvent(eventType, serviceName,
- mDataShareRequest.getPackageName());
+ ContentCaptureMetricsLogger.writeServiceEvent(eventType, serviceName);
}
}
}
diff --git a/services/contentcapture/java/com/android/server/contentcapture/ContentCaptureMetricsLogger.java b/services/contentcapture/java/com/android/server/contentcapture/ContentCaptureMetricsLogger.java
index 7ea4eff3381c..10bec64936b3 100644
--- a/services/contentcapture/java/com/android/server/contentcapture/ContentCaptureMetricsLogger.java
+++ b/services/contentcapture/java/com/android/server/contentcapture/ContentCaptureMetricsLogger.java
@@ -34,72 +34,47 @@ public final class ContentCaptureMetricsLogger {
}
/** @hide */
- public static void writeServiceEvent(int eventType, @NonNull String serviceName,
- @Nullable String targetPackage) {
+ public static void writeServiceEvent(int eventType, @NonNull String serviceName) {
+ // we should not logging the application package name
FrameworkStatsLog.write(FrameworkStatsLog.CONTENT_CAPTURE_SERVICE_EVENTS, eventType,
- serviceName, targetPackage);
- }
-
- /** @hide */
- public static void writeServiceEvent(int eventType, @NonNull ComponentName service,
- @Nullable ComponentName target) {
- writeServiceEvent(eventType, ComponentName.flattenToShortString(service),
- ComponentName.flattenToShortString(target));
- }
-
- /** @hide */
- public static void writeServiceEvent(int eventType, @NonNull ComponentName service,
- @Nullable String targetPackage) {
- writeServiceEvent(eventType, ComponentName.flattenToShortString(service), targetPackage);
+ serviceName, /* componentName= */ null, 0, 0);
}
/** @hide */
public static void writeServiceEvent(int eventType, @NonNull ComponentName service) {
- writeServiceEvent(eventType, ComponentName.flattenToShortString(service), null);
+ writeServiceEvent(eventType, ComponentName.flattenToShortString(service));
}
/** @hide */
public static void writeSetWhitelistEvent(@Nullable ComponentName service,
@Nullable List<String> packages, @Nullable List<ComponentName> activities) {
final String serviceName = ComponentName.flattenToShortString(service);
- StringBuilder stringBuilder = new StringBuilder();
- if (packages != null && packages.size() > 0) {
- final int size = packages.size();
- stringBuilder.append(packages.get(0));
- for (int i = 1; i < size; i++) {
- stringBuilder.append(" ");
- stringBuilder.append(packages.get(i));
- }
- }
- if (activities != null && activities.size() > 0) {
- stringBuilder.append(" ");
- stringBuilder.append(activities.get(0).flattenToShortString());
- final int size = activities.size();
- for (int i = 1; i < size; i++) {
- stringBuilder.append(" ");
- stringBuilder.append(activities.get(i).flattenToShortString());
- }
- }
+ int packageCount = packages != null ? packages.size() : 0;
+ int activityCount = activities != null ? activities.size() : 0;
+ // we should not logging the application package name
+ // log the allow list package and activity count instead
FrameworkStatsLog.write(FrameworkStatsLog.CONTENT_CAPTURE_SERVICE_EVENTS,
FrameworkStatsLog.CONTENT_CAPTURE_SERVICE_EVENTS__EVENT__SET_WHITELIST,
- serviceName, stringBuilder.toString());
+ serviceName, /* allowListStr= */ null, packageCount, activityCount);
}
/** @hide */
public static void writeSessionEvent(int sessionId, int event, int flags,
- @NonNull ComponentName service, @Nullable ComponentName app, boolean isChildSession) {
+ @NonNull ComponentName service, boolean isChildSession) {
+ // we should not logging the application package name
FrameworkStatsLog.write(FrameworkStatsLog.CONTENT_CAPTURE_SESSION_EVENTS, sessionId, event,
flags, ComponentName.flattenToShortString(service),
- ComponentName.flattenToShortString(app), isChildSession);
+ /* componentName= */ null, isChildSession);
}
/** @hide */
public static void writeSessionFlush(int sessionId, @NonNull ComponentName service,
- @Nullable ComponentName app, @NonNull FlushMetrics fm,
- @NonNull ContentCaptureOptions options, int flushReason) {
+ @NonNull FlushMetrics fm, @NonNull ContentCaptureOptions options,
+ int flushReason) {
+ // we should not logging the application package name
FrameworkStatsLog.write(FrameworkStatsLog.CONTENT_CAPTURE_FLUSHED, sessionId,
ComponentName.flattenToShortString(service),
- ComponentName.flattenToShortString(app), fm.sessionStarted, fm.sessionFinished,
+ /* componentName= */ null, fm.sessionStarted, fm.sessionFinished,
fm.viewAppearedCount, fm.viewDisappearedCount, fm.viewTextChangedCount,
options.maxBufferSize, options.idleFlushingFrequencyMs,
options.textChangeFlushingFrequencyMs, flushReason);
diff --git a/services/contentcapture/java/com/android/server/contentcapture/ContentCapturePerUserService.java b/services/contentcapture/java/com/android/server/contentcapture/ContentCapturePerUserService.java
index 822a42bf50cf..9bc1cee2aa05 100644
--- a/services/contentcapture/java/com/android/server/contentcapture/ContentCapturePerUserService.java
+++ b/services/contentcapture/java/com/android/server/contentcapture/ContentCapturePerUserService.java
@@ -330,7 +330,7 @@ final class ContentCapturePerUserService
writeSessionEvent(sessionId,
FrameworkStatsLog.CONTENT_CAPTURE_SESSION_EVENTS__EVENT__SESSION_NOT_CREATED,
STATE_DISABLED | STATE_NO_SERVICE, serviceComponentName,
- componentName, /* isChildSession= */ false);
+ /* isChildSession= */ false);
return;
}
if (serviceComponentName == null) {
@@ -354,7 +354,7 @@ final class ContentCapturePerUserService
writeSessionEvent(sessionId,
FrameworkStatsLog.CONTENT_CAPTURE_SESSION_EVENTS__EVENT__SESSION_NOT_CREATED,
STATE_DISABLED | STATE_NOT_WHITELISTED, serviceComponentName,
- componentName, /* isChildSession= */ false);
+ /* isChildSession= */ false);
return;
}
@@ -368,7 +368,7 @@ final class ContentCapturePerUserService
writeSessionEvent(sessionId,
FrameworkStatsLog.CONTENT_CAPTURE_SESSION_EVENTS__EVENT__SESSION_NOT_CREATED,
STATE_DISABLED | STATE_DUPLICATED_ID,
- serviceComponentName, componentName, /* isChildSession= */ false);
+ serviceComponentName, /* isChildSession= */ false);
return;
}
@@ -385,7 +385,7 @@ final class ContentCapturePerUserService
writeSessionEvent(sessionId,
FrameworkStatsLog.CONTENT_CAPTURE_SESSION_EVENTS__EVENT__SESSION_NOT_CREATED,
STATE_DISABLED | STATE_NO_SERVICE, serviceComponentName,
- componentName, /* isChildSession= */ false);
+ /* isChildSession= */ false);
return;
}
@@ -740,7 +740,7 @@ final class ContentCapturePerUserService
@Override
public void writeSessionFlush(int sessionId, ComponentName app, FlushMetrics flushMetrics,
ContentCaptureOptions options, int flushReason) {
- ContentCaptureMetricsLogger.writeSessionFlush(sessionId, getServiceComponentName(), app,
+ ContentCaptureMetricsLogger.writeSessionFlush(sessionId, getServiceComponentName(),
flushMetrics, options, flushReason);
}
diff --git a/services/contentcapture/java/com/android/server/contentcapture/RemoteContentCaptureService.java b/services/contentcapture/java/com/android/server/contentcapture/RemoteContentCaptureService.java
index 08e6a0550f69..1efe55aa0767 100644
--- a/services/contentcapture/java/com/android/server/contentcapture/RemoteContentCaptureService.java
+++ b/services/contentcapture/java/com/android/server/contentcapture/RemoteContentCaptureService.java
@@ -119,8 +119,7 @@ final class RemoteContentCaptureService
// Metrics logging.
writeSessionEvent(sessionId,
FrameworkStatsLog.CONTENT_CAPTURE_SESSION_EVENTS__EVENT__ON_SESSION_STARTED,
- initialState, getComponentName(), context.getActivityComponent(),
- /* is_child_session= */ false);
+ initialState, getComponentName(), /* is_child_session= */ false);
}
/**
@@ -132,8 +131,7 @@ final class RemoteContentCaptureService
// Metrics logging.
writeSessionEvent(sessionId,
FrameworkStatsLog.CONTENT_CAPTURE_SESSION_EVENTS__EVENT__ON_SESSION_FINISHED,
- /* flags= */ 0, getComponentName(), /* app= */ null,
- /* is_child_session= */ false);
+ /* flags= */ 0, getComponentName(), /* is_child_session= */ false);
}
/**
@@ -158,7 +156,7 @@ final class RemoteContentCaptureService
scheduleAsyncRequest((s) -> s.onDataShared(request, dataShareCallback));
writeServiceEvent(
FrameworkStatsLog.CONTENT_CAPTURE_SERVICE_EVENTS__EVENT__ON_DATA_SHARE_REQUEST,
- mComponentName, request.getPackageName());
+ mComponentName);
}
/**
diff --git a/services/core/java/android/content/pm/PackageManagerInternal.java b/services/core/java/android/content/pm/PackageManagerInternal.java
index 06f698efde2b..ed6110086089 100644
--- a/services/core/java/android/content/pm/PackageManagerInternal.java
+++ b/services/core/java/android/content/pm/PackageManagerInternal.java
@@ -334,10 +334,14 @@ public abstract class PackageManagerInternal {
/**
* Retrieve all receivers that can handle a broadcast of the given intent.
+ * @param filterCallingUid The results will be filtered in the context of this UID instead
+ * of the calling UID.
+ * @param forSend true if the invocation is intended for sending broadcasts. The value
+ * of this parameter affects how packages are filtered.
*/
public abstract List<ResolveInfo> queryIntentReceivers(Intent intent,
String resolvedType, @PackageManager.ResolveInfoFlagsBits long flags,
- int filterCallingUid, int userId);
+ int filterCallingUid, int userId, boolean forSend);
/**
* Retrieve all services that can be performed for the given intent.
@@ -371,10 +375,10 @@ public abstract class PackageManagerInternal {
int deviceOwnerUserId, String deviceOwner, SparseArray<String> profileOwners);
/**
- * Called by Owners to set the package names protected by the device owner.
+ * Marks packages as protected for a given user or all users in case of USER_ALL.
*/
- public abstract void setDeviceOwnerProtectedPackages(
- String deviceOwnerPackageName, List<String> packageNames);
+ public abstract void setOwnerProtectedPackages(
+ @UserIdInt int userId, @NonNull List<String> packageNames);
/**
* Returns {@code true} if a given package can't be wiped. Otherwise, returns {@code false}.
diff --git a/services/core/java/com/android/server/StorageManagerService.java b/services/core/java/com/android/server/StorageManagerService.java
index bc40170d39b7..5eec6e58e925 100644
--- a/services/core/java/com/android/server/StorageManagerService.java
+++ b/services/core/java/com/android/server/StorageManagerService.java
@@ -3880,9 +3880,12 @@ class StorageManagerService extends IStorageManager.Stub
match = vol.isVisibleForWrite(userId)
|| (includeSharedProfile && vol.isVisibleForWrite(userIdSharingMedia));
} else {
+ // Return both read only and write only volumes. When includeSharedProfile is
+ // true, all the volumes of userIdSharingMedia should be returned when queried
+ // from the user it shares media with
match = vol.isVisibleForUser(userId)
|| (!vol.isVisible() && includeInvisible && vol.getPath() != null)
- || (includeSharedProfile && vol.isVisibleForRead(userIdSharingMedia));
+ || (includeSharedProfile && vol.isVisibleForUser(userIdSharingMedia));
}
if (!match) continue;
diff --git a/services/core/java/com/android/server/TelephonyRegistry.java b/services/core/java/com/android/server/TelephonyRegistry.java
index 1033aea4b09f..7a52af61a196 100644
--- a/services/core/java/com/android/server/TelephonyRegistry.java
+++ b/services/core/java/com/android/server/TelephonyRegistry.java
@@ -3066,42 +3066,88 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
Binder.restoreCallingIdentity(ident);
}
+ // Send the broadcast exactly once to all possible disjoint sets of apps.
+ // If the location master switch is on, broadcast the ServiceState 4 times:
+ // - Full ServiceState sent to apps with ACCESS_FINE_LOCATION and READ_PHONE_STATE
+ // - Full ServiceState sent to apps with ACCESS_FINE_LOCATION and
+ // READ_PRIVILEGED_PHONE_STATE but not READ_PHONE_STATE
+ // - Sanitized ServiceState sent to apps with READ_PHONE_STATE but not ACCESS_FINE_LOCATION
+ // - Sanitized ServiceState sent to apps with READ_PRIVILEGED_PHONE_STATE but neither
+ // READ_PHONE_STATE nor ACCESS_FINE_LOCATION
+ // If the location master switch is off, broadcast the ServiceState multiple times:
+ // - Full ServiceState sent to all apps permitted to bypass the location master switch if
+ // they have either READ_PHONE_STATE or READ_PRIVILEGED_PHONE_STATE
+ // - Sanitized ServiceState sent to all other apps with READ_PHONE_STATE
+ // - Sanitized ServiceState sent to all other apps with READ_PRIVILEGED_PHONE_STATE but not
+ // READ_PHONE_STATE
+ if (Binder.withCleanCallingIdentity(() ->
+ LocationAccessPolicy.isLocationModeEnabled(mContext, mContext.getUserId()))) {
+ Intent fullIntent = createServiceStateIntent(state, subId, phoneId, false);
+ mContext.createContextAsUser(UserHandle.ALL, 0).sendBroadcastMultiplePermissions(
+ fullIntent,
+ new String[]{Manifest.permission.READ_PHONE_STATE,
+ Manifest.permission.ACCESS_FINE_LOCATION});
+ mContext.createContextAsUser(UserHandle.ALL, 0).sendBroadcastMultiplePermissions(
+ fullIntent,
+ new String[]{Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
+ Manifest.permission.ACCESS_FINE_LOCATION},
+ new String[]{Manifest.permission.READ_PHONE_STATE});
+
+ Intent sanitizedIntent = createServiceStateIntent(state, subId, phoneId, true);
+ mContext.createContextAsUser(UserHandle.ALL, 0).sendBroadcastMultiplePermissions(
+ sanitizedIntent,
+ new String[]{Manifest.permission.READ_PHONE_STATE},
+ new String[]{Manifest.permission.ACCESS_FINE_LOCATION});
+ mContext.createContextAsUser(UserHandle.ALL, 0).sendBroadcastMultiplePermissions(
+ sanitizedIntent,
+ new String[]{Manifest.permission.READ_PRIVILEGED_PHONE_STATE},
+ new String[]{Manifest.permission.READ_PHONE_STATE,
+ Manifest.permission.ACCESS_FINE_LOCATION});
+ } else {
+ String[] locationBypassPackages = Binder.withCleanCallingIdentity(() ->
+ LocationAccessPolicy.getLocationBypassPackages(mContext));
+ for (String locationBypassPackage : locationBypassPackages) {
+ Intent fullIntent = createServiceStateIntent(state, subId, phoneId, false);
+ fullIntent.setPackage(locationBypassPackage);
+ mContext.createContextAsUser(UserHandle.ALL, 0).sendBroadcastMultiplePermissions(
+ fullIntent,
+ new String[]{Manifest.permission.READ_PHONE_STATE});
+ mContext.createContextAsUser(UserHandle.ALL, 0).sendBroadcastMultiplePermissions(
+ fullIntent,
+ new String[]{Manifest.permission.READ_PRIVILEGED_PHONE_STATE},
+ new String[]{Manifest.permission.READ_PHONE_STATE});
+ }
+
+ Intent sanitizedIntent = createServiceStateIntent(state, subId, phoneId, true);
+ mContext.createContextAsUser(UserHandle.ALL, 0).sendBroadcastMultiplePermissions(
+ sanitizedIntent,
+ new String[]{Manifest.permission.READ_PHONE_STATE},
+ new String[]{/* no excluded permissions */},
+ locationBypassPackages);
+ mContext.createContextAsUser(UserHandle.ALL, 0).sendBroadcastMultiplePermissions(
+ sanitizedIntent,
+ new String[]{Manifest.permission.READ_PRIVILEGED_PHONE_STATE},
+ new String[]{Manifest.permission.READ_PHONE_STATE},
+ locationBypassPackages);
+ }
+ }
+
+ private Intent createServiceStateIntent(ServiceState state, int subId, int phoneId,
+ boolean sanitizeLocation) {
Intent intent = new Intent(Intent.ACTION_SERVICE_STATE);
intent.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Bundle data = new Bundle();
- state.fillInNotifierBundle(data);
+ if (sanitizeLocation) {
+ state.createLocationInfoSanitizedCopy(true).fillInNotifierBundle(data);
+ } else {
+ state.fillInNotifierBundle(data);
+ }
intent.putExtras(data);
- // Pass the subscription along with the intent.
intent.putExtra(PHONE_CONSTANTS_SUBSCRIPTION_KEY, subId);
intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, subId);
intent.putExtra(PHONE_CONSTANTS_SLOT_KEY, phoneId);
intent.putExtra(SubscriptionManager.EXTRA_SLOT_INDEX, phoneId);
-
- // Send the broadcast twice -- once for all apps with READ_PHONE_STATE, then again
- // for all apps with READ_PRIVILEGED_PHONE_STATE but not READ_PHONE_STATE.
- // Do this again twice, the first time for apps with ACCESS_FINE_LOCATION, then again with
- // the location-sanitized service state for all apps without ACCESS_FINE_LOCATION.
- // This ensures that any app holding either READ_PRIVILEGED_PHONE_STATE or READ_PHONE_STATE
- // get this broadcast exactly once, and we are not exposing location without permission.
- mContext.createContextAsUser(UserHandle.ALL, 0).sendBroadcastMultiplePermissions(intent,
- new String[] {Manifest.permission.READ_PHONE_STATE,
- Manifest.permission.ACCESS_FINE_LOCATION});
- mContext.createContextAsUser(UserHandle.ALL, 0).sendBroadcastMultiplePermissions(intent,
- new String[] {Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
- Manifest.permission.ACCESS_FINE_LOCATION},
- new String[] {Manifest.permission.READ_PHONE_STATE});
-
- // Replace bundle with location-sanitized ServiceState
- data = new Bundle();
- state.createLocationInfoSanitizedCopy(true).fillInNotifierBundle(data);
- intent.putExtras(data);
- mContext.createContextAsUser(UserHandle.ALL, 0).sendBroadcastMultiplePermissions(intent,
- new String[] {Manifest.permission.READ_PHONE_STATE},
- new String[] {Manifest.permission.ACCESS_FINE_LOCATION});
- mContext.createContextAsUser(UserHandle.ALL, 0).sendBroadcastMultiplePermissions(intent,
- new String[] {Manifest.permission.READ_PRIVILEGED_PHONE_STATE},
- new String[] {Manifest.permission.READ_PHONE_STATE,
- Manifest.permission.ACCESS_FINE_LOCATION});
+ return intent;
}
private void broadcastSignalStrengthChanged(SignalStrength signalStrength, int phoneId,
diff --git a/services/core/java/com/android/server/VpnManagerService.java b/services/core/java/com/android/server/VpnManagerService.java
index c1d8e7bf3dc0..d3ef6bed46a0 100644
--- a/services/core/java/com/android/server/VpnManagerService.java
+++ b/services/core/java/com/android/server/VpnManagerService.java
@@ -880,6 +880,38 @@ public class VpnManagerService extends IVpnManager.Stub {
}
}
+ @Override
+ public boolean setAppExclusionList(int userId, String vpnPackage, List<String> excludedApps) {
+ enforceSettingsPermission();
+ enforceCrossUserPermission(userId);
+
+ synchronized (mVpns) {
+ final Vpn vpn = mVpns.get(userId);
+ if (vpn != null) {
+ return vpn.setAppExclusionList(vpnPackage, excludedApps);
+ } else {
+ logw("User " + userId + " has no Vpn configuration");
+ throw new IllegalStateException(
+ "VPN for user " + userId + " not ready yet. Skipping setting the list");
+ }
+ }
+ }
+
+ @Override
+ public List<String> getAppExclusionList(int userId, String vpnPackage) {
+ enforceSettingsPermission();
+ enforceCrossUserPermission(userId);
+
+ synchronized (mVpns) {
+ final Vpn vpn = mVpns.get(userId);
+ if (vpn != null) {
+ return vpn.getAppExclusionList(vpnPackage);
+ } else {
+ logw("User " + userId + " has no Vpn configuration");
+ return null;
+ }
+ }
+ }
@Override
public void factoryReset() {
diff --git a/services/core/java/com/android/server/Watchdog.java b/services/core/java/com/android/server/Watchdog.java
index fbf648278543..c678a67e5bd3 100644
--- a/services/core/java/com/android/server/Watchdog.java
+++ b/services/core/java/com/android/server/Watchdog.java
@@ -19,6 +19,8 @@ package com.android.server;
import static com.android.server.Watchdog.HandlerCheckerAndTimeout.withCustomTimeout;
import static com.android.server.Watchdog.HandlerCheckerAndTimeout.withDefaultTimeout;
+import android.annotation.NonNull;
+import android.annotation.Nullable;
import android.app.IActivityController;
import android.content.BroadcastReceiver;
import android.content.Context;
@@ -43,6 +45,7 @@ import android.os.SystemProperties;
import android.os.UserHandle;
import android.provider.Settings;
import android.sysprop.WatchdogProperties;
+import android.util.Dumpable;
import android.util.EventLog;
import android.util.Log;
import android.util.Slog;
@@ -63,6 +66,7 @@ import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
+import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
@@ -76,7 +80,7 @@ import java.util.concurrent.TimeUnit;
/**
* This class calls its monitor every minute. Killing this process if they don't return
**/
-public class Watchdog {
+public class Watchdog implements Dumpable {
static final String TAG = "Watchdog";
/** Debug flag. */
@@ -1028,4 +1032,10 @@ public class Watchdog {
}
doSysRq('c');
}
+
+ @Override
+ public void dump(@NonNull PrintWriter pw, @Nullable String[] args) {
+ pw.print("WatchdogTimeoutMillis=");
+ pw.println(mWatchdogTimeoutMillis);
+ }
}
diff --git a/services/core/java/com/android/server/am/ActiveServices.java b/services/core/java/com/android/server/am/ActiveServices.java
index 6fa3bc8e0669..48b3d0e106d3 100644
--- a/services/core/java/com/android/server/am/ActiveServices.java
+++ b/services/core/java/com/android/server/am/ActiveServices.java
@@ -6476,10 +6476,16 @@ public final class ActiveServices {
}
if (ret == REASON_DENIED) {
- final boolean isAllowedPackage =
- mAllowListWhileInUsePermissionInFgs.contains(callingPackage);
- if (isAllowedPackage) {
- ret = REASON_ALLOWLISTED_PACKAGE;
+ if (verifyPackage(callingPackage, callingUid)) {
+ final boolean isAllowedPackage =
+ mAllowListWhileInUsePermissionInFgs.contains(callingPackage);
+ if (isAllowedPackage) {
+ ret = REASON_ALLOWLISTED_PACKAGE;
+ }
+ } else {
+ EventLog.writeEvent(0x534e4554, "215003903", callingUid,
+ "callingPackage:" + callingPackage + " does not belong to callingUid:"
+ + callingUid);
}
}
@@ -6593,12 +6599,11 @@ public final class ActiveServices {
}
final int uidState = mAm.getUidStateLocked(callingUid);
- int callerTargetSdkVersion = INVALID_UID;
+ int callerTargetSdkVersion = -1;
try {
- ApplicationInfo ai = mAm.mContext.getPackageManager().getApplicationInfoAsUser(
- callingPackage, PackageManager.MATCH_KNOWN_PACKAGES, userId);
- callerTargetSdkVersion = ai.targetSdkVersion;
- } catch (PackageManager.NameNotFoundException e) {
+ callerTargetSdkVersion = mAm.mContext.getPackageManager()
+ .getTargetSdkVersion(callingPackage);
+ } catch (PackageManager.NameNotFoundException ignored) {
}
final String debugInfo =
"[callingPackage: " + callingPackage
@@ -6883,4 +6888,19 @@ public final class ActiveServices {
/* allowBackgroundActivityStarts */ false)
!= REASON_DENIED;
}
+
+ /**
+ * Checks if a given packageName belongs to a given uid.
+ * @param packageName the package of the caller
+ * @param uid the uid of the caller
+ * @return true or false
+ */
+ private boolean verifyPackage(String packageName, int uid) {
+ if (uid == ROOT_UID || uid == SYSTEM_UID) {
+ //System and Root are always allowed
+ return true;
+ }
+ return mAm.getPackageManagerInternal().isSameApp(packageName, uid,
+ UserHandle.getUserId(uid));
+ }
}
diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java
index b2fd6263fe68..355fe3249b20 100644
--- a/services/core/java/com/android/server/am/ActivityManagerService.java
+++ b/services/core/java/com/android/server/am/ActivityManagerService.java
@@ -1530,6 +1530,8 @@ public class ActivityManagerService extends IActivityManager.Stub
// Encapsulates the global setting "hidden_api_blacklist_exemptions"
final HiddenApiSettings mHiddenApiBlacklist;
+ final SdkSandboxSettings mSdkSandboxSettings;
+
private final PlatformCompat mPlatformCompat;
PackageManagerInternal mPackageManagerInt;
@@ -2235,6 +2237,53 @@ public class ActivityManagerService extends IActivityManager.Stub
}
}
+ /**
+ * Handles settings related to the enforcement of SDK sandbox restrictions.
+ */
+ static class SdkSandboxSettings implements DeviceConfig.OnPropertiesChangedListener {
+
+ private final Context mContext;
+ private final Object mLock = new Object();
+
+ @GuardedBy("mLock")
+ private boolean mEnforceBroadcastReceiverRestrictions;
+
+ /**
+ * Property to enforce broadcast receiver restrictions for SDK sandbox processes. If the
+ * value of this property is {@code true}, the restrictions will be enforced.
+ */
+ public static final String ENFORCE_BROADCAST_RECEIVER_RESTRICTIONS =
+ "enforce_broadcast_receiver_restrictions";
+
+ SdkSandboxSettings(Context context) {
+ mContext = context;
+ }
+
+ void registerObserver() {
+ synchronized (mLock) {
+ mEnforceBroadcastReceiverRestrictions = DeviceConfig.getBoolean(
+ DeviceConfig.NAMESPACE_SDK_SANDBOX,
+ ENFORCE_BROADCAST_RECEIVER_RESTRICTIONS, false);
+ DeviceConfig.addOnPropertiesChangedListener(DeviceConfig.NAMESPACE_SDK_SANDBOX,
+ mContext.getMainExecutor(), this);
+ }
+ }
+
+ @Override
+ public void onPropertiesChanged(DeviceConfig.Properties properties) {
+ synchronized (mLock) {
+ mEnforceBroadcastReceiverRestrictions = properties.getBoolean(
+ ENFORCE_BROADCAST_RECEIVER_RESTRICTIONS, false);
+ }
+ }
+
+ boolean isBroadcastReceiverRestrictionsEnforced() {
+ synchronized (mLock) {
+ return mEnforceBroadcastReceiverRestrictions;
+ }
+ }
+ }
+
AppOpsManager getAppOpsManager() {
if (mAppOpsManager == null) {
mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
@@ -2277,6 +2326,7 @@ public class ActivityManagerService extends IActivityManager.Stub
mProcStartHandlerThread = null;
mProcStartHandler = null;
mHiddenApiBlacklist = null;
+ mSdkSandboxSettings = null;
mFactoryTest = FACTORY_TEST_OFF;
mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
mInternal = new LocalService();
@@ -2396,6 +2446,7 @@ public class ActivityManagerService extends IActivityManager.Stub
mAtmInternal = LocalServices.getService(ActivityTaskManagerInternal.class);
mHiddenApiBlacklist = new HiddenApiSettings(mHandler, mContext);
+ mSdkSandboxSettings = new SdkSandboxSettings(mContext);
Watchdog.getInstance().addMonitor(this);
Watchdog.getInstance().addThread(mHandler);
@@ -2617,7 +2668,7 @@ public class ActivityManagerService extends IActivityManager.Stub
public void batterySendBroadcast(Intent intent) {
synchronized (this) {
broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null, null, null,
- OP_NONE, null, false, false, -1, SYSTEM_UID, Binder.getCallingUid(),
+ null, OP_NONE, null, false, false, -1, SYSTEM_UID, Binder.getCallingUid(),
Binder.getCallingPid(), UserHandle.USER_ALL);
}
}
@@ -4231,7 +4282,7 @@ public class ActivityManagerService extends IActivityManager.Stub
intent.putExtra(Intent.EXTRA_UID, uid);
intent.putExtra(Intent.EXTRA_USER_HANDLE, UserHandle.getUserId(uid));
broadcastIntentLocked(null, null, null, intent,
- null, null, 0, null, null, null, null, OP_NONE,
+ null, null, 0, null, null, null, null, null, OP_NONE,
null, false, false, MY_PID, SYSTEM_UID, Binder.getCallingUid(),
Binder.getCallingPid(), UserHandle.getUserId(uid));
}
@@ -7901,6 +7952,7 @@ public class ActivityManagerService extends IActivityManager.Stub
final boolean alwaysFinishActivities =
Settings.Global.getInt(resolver, ALWAYS_FINISH_ACTIVITIES, 0) != 0;
mHiddenApiBlacklist.registerObserver();
+ mSdkSandboxSettings.registerObserver();
mPlatformCompat.registerContentObserver();
mAppProfiler.retrieveSettings();
@@ -8112,7 +8164,7 @@ public class ActivityManagerService extends IActivityManager.Stub
| Intent.FLAG_RECEIVER_FOREGROUND);
intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId);
broadcastIntentLocked(null, null, null, intent,
- null, null, 0, null, null, null, null, OP_NONE,
+ null, null, 0, null, null, null, null, null, OP_NONE,
null, false, false, MY_PID, SYSTEM_UID, callingUid, callingPid,
currentUserId);
intent = new Intent(Intent.ACTION_USER_STARTING);
@@ -8124,8 +8176,8 @@ public class ActivityManagerService extends IActivityManager.Stub
public void performReceive(Intent intent, int resultCode,
String data, Bundle extras, boolean ordered, boolean sticky,
int sendingUser) {}
- }, 0, null, null, new String[] {INTERACT_ACROSS_USERS}, null, OP_NONE,
- null, true, false, MY_PID, SYSTEM_UID, callingUid, callingPid,
+ }, 0, null, null, new String[] {INTERACT_ACROSS_USERS}, null, null,
+ OP_NONE, null, true, false, MY_PID, SYSTEM_UID, callingUid, callingPid,
UserHandle.USER_ALL);
} catch (Throwable e) {
Slog.wtf(TAG, "Failed sending first user broadcasts", e);
@@ -12930,7 +12982,7 @@ public class ActivityManagerService extends IActivityManager.Stub
// Allow Sandbox process to register only unexported receivers.
if ((flags & Context.RECEIVER_NOT_EXPORTED) != 0) {
enforceNotIsolatedCaller("registerReceiver");
- } else {
+ } else if (mSdkSandboxSettings.isBroadcastReceiverRestrictionsEnforced()) {
enforceNotIsolatedOrSdkSandboxCaller("registerReceiver");
}
ArrayList<Intent> stickyIntents = null;
@@ -13155,8 +13207,8 @@ public class ActivityManagerService extends IActivityManager.Stub
Intent intent = allSticky.get(i);
BroadcastQueue queue = broadcastQueueForIntent(intent);
BroadcastRecord r = new BroadcastRecord(queue, intent, null,
- null, null, -1, -1, false, null, null, null, OP_NONE, null, receivers,
- null, 0, null, null, false, true, true, -1, false, null,
+ null, null, -1, -1, false, null, null, null, null, OP_NONE, null,
+ receivers, null, 0, null, null, false, true, true, -1, false, null,
false /* only PRE_BOOT_COMPLETED should be exempt, no stickies */);
queue.enqueueParallelBroadcastLocked(r);
queue.scheduleBroadcastsLocked();
@@ -13238,8 +13290,8 @@ public class ActivityManagerService extends IActivityManager.Stub
UserManager.DISALLOW_DEBUGGING_FEATURES, user)) {
continue;
}
- List<ResolveInfo> newReceivers = mPackageManagerInt
- .queryIntentReceivers(intent, resolvedType, pmFlags, callingUid, user);
+ List<ResolveInfo> newReceivers = mPackageManagerInt.queryIntentReceivers(
+ intent, resolvedType, pmFlags, callingUid, user, true /* forSend */);
if (user != UserHandle.USER_SYSTEM && newReceivers != null) {
// If this is not the system user, we need to check for
// any receivers that should be filtered out.
@@ -13255,8 +13307,9 @@ public class ActivityManagerService extends IActivityManager.Stub
if (newReceivers != null) {
for (int i = newReceivers.size() - 1; i >= 0; i--) {
final ResolveInfo ri = newReceivers.get(i);
- final Resolution<ResolveInfo> resolution = mComponentAliasResolver
- .resolveReceiver(intent, ri, resolvedType, pmFlags, user, callingUid);
+ final Resolution<ResolveInfo> resolution =
+ mComponentAliasResolver.resolveReceiver(intent, ri, resolvedType,
+ pmFlags, user, callingUid, true /* forSend */);
if (resolution == null) {
// It was an alias, but the target was not found.
newReceivers.remove(i);
@@ -13411,12 +13464,14 @@ public class ActivityManagerService extends IActivityManager.Stub
String callerPackage, String callerFeatureId, Intent intent, String resolvedType,
IIntentReceiver resultTo, int resultCode, String resultData,
Bundle resultExtras, String[] requiredPermissions, String[] excludedPermissions,
- int appOp, Bundle bOptions, boolean ordered, boolean sticky, int callingPid,
+ String[] excludedPackages, int appOp, Bundle bOptions, boolean ordered,
+ boolean sticky, int callingPid,
int callingUid, int realCallingUid, int realCallingPid, int userId) {
return broadcastIntentLocked(callerApp, callerPackage, callerFeatureId, intent,
resolvedType, resultTo, resultCode, resultData, resultExtras, requiredPermissions,
- excludedPermissions, appOp, bOptions, ordered, sticky, callingPid, callingUid,
- realCallingUid, realCallingPid, userId, false /* allowBackgroundActivityStarts */,
+ excludedPermissions, excludedPackages, appOp, bOptions, ordered, sticky, callingPid,
+ callingUid, realCallingUid, realCallingPid, userId,
+ false /* allowBackgroundActivityStarts */,
null /* tokenNeededForBackgroundActivityStarts */, null /* broadcastAllowList */);
}
@@ -13425,7 +13480,7 @@ public class ActivityManagerService extends IActivityManager.Stub
@Nullable String callerFeatureId, Intent intent, String resolvedType,
IIntentReceiver resultTo, int resultCode, String resultData,
Bundle resultExtras, String[] requiredPermissions,
- String[] excludedPermissions, int appOp, Bundle bOptions,
+ String[] excludedPermissions, String[] excludedPackages, int appOp, Bundle bOptions,
boolean ordered, boolean sticky, int callingPid, int callingUid,
int realCallingUid, int realCallingPid, int userId,
boolean allowBackgroundActivityStarts,
@@ -14032,10 +14087,10 @@ public class ActivityManagerService extends IActivityManager.Stub
final BroadcastQueue queue = broadcastQueueForIntent(intent);
BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp, callerPackage,
callerFeatureId, callingPid, callingUid, callerInstantApp, resolvedType,
- requiredPermissions, excludedPermissions, appOp, brOptions, registeredReceivers,
- resultTo, resultCode, resultData, resultExtras, ordered, sticky, false, userId,
- allowBackgroundActivityStarts, backgroundActivityStartsToken,
- timeoutExempt);
+ requiredPermissions, excludedPermissions, excludedPackages, appOp, brOptions,
+ registeredReceivers, resultTo, resultCode, resultData, resultExtras, ordered,
+ sticky, false, userId, allowBackgroundActivityStarts,
+ backgroundActivityStartsToken, timeoutExempt);
if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueueing parallel broadcast " + r);
final boolean replaced = replacePending
&& (queue.replaceParallelBroadcastLocked(r) != null);
@@ -14130,7 +14185,7 @@ public class ActivityManagerService extends IActivityManager.Stub
BroadcastQueue queue = broadcastQueueForIntent(intent);
BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp, callerPackage,
callerFeatureId, callingPid, callingUid, callerInstantApp, resolvedType,
- requiredPermissions, excludedPermissions, appOp, brOptions,
+ requiredPermissions, excludedPermissions, excludedPackages, appOp, brOptions,
receivers, resultTo, resultCode, resultData, resultExtras,
ordered, sticky, false, userId, allowBackgroundActivityStarts,
backgroundActivityStartsToken, timeoutExempt);
@@ -14259,14 +14314,16 @@ public class ActivityManagerService extends IActivityManager.Stub
String[] requiredPermissions, int appOp, Bundle bOptions,
boolean serialized, boolean sticky, int userId) {
return broadcastIntentWithFeature(caller, null, intent, resolvedType, resultTo, resultCode,
- resultData, resultExtras, requiredPermissions, null, appOp, bOptions, serialized,
- sticky, userId);
+ resultData, resultExtras, requiredPermissions, null, null, appOp, bOptions,
+ serialized, sticky, userId);
}
+ @Override
public final int broadcastIntentWithFeature(IApplicationThread caller, String callingFeatureId,
Intent intent, String resolvedType, IIntentReceiver resultTo,
int resultCode, String resultData, Bundle resultExtras,
- String[] requiredPermissions, String[] excludedPermissions, int appOp, Bundle bOptions,
+ String[] requiredPermissions, String[] excludedPermissions,
+ String[] excludedPackages, int appOp, Bundle bOptions,
boolean serialized, boolean sticky, int userId) {
enforceNotIsolatedCaller("broadcastIntent");
synchronized(this) {
@@ -14281,8 +14338,8 @@ public class ActivityManagerService extends IActivityManager.Stub
return broadcastIntentLocked(callerApp,
callerApp != null ? callerApp.info.packageName : null, callingFeatureId,
intent, resolvedType, resultTo, resultCode, resultData, resultExtras,
- requiredPermissions, excludedPermissions, appOp, bOptions, serialized,
- sticky, callingPid, callingUid, callingUid, callingPid, userId);
+ requiredPermissions, excludedPermissions, excludedPackages, appOp, bOptions,
+ serialized, sticky, callingPid, callingUid, callingUid, callingPid, userId);
} finally {
Binder.restoreCallingIdentity(origId);
}
@@ -14305,7 +14362,7 @@ public class ActivityManagerService extends IActivityManager.Stub
try {
return broadcastIntentLocked(null, packageName, featureId, intent, resolvedType,
resultTo, resultCode, resultData, resultExtras, requiredPermissions, null,
- OP_NONE, bOptions, serialized, sticky, -1, uid, realCallingUid,
+ null, OP_NONE, bOptions, serialized, sticky, -1, uid, realCallingUid,
realCallingPid, userId, allowBackgroundActivityStarts,
backgroundActivityStartsToken, broadcastAllowList);
} finally {
@@ -16824,10 +16881,11 @@ public class ActivityManagerService extends IActivityManager.Stub
return ActivityManagerService.this.broadcastIntentLocked(null /*callerApp*/,
null /*callerPackage*/, null /*callingFeatureId*/, intent,
null /*resolvedType*/, resultTo, 0 /*resultCode*/, null /*resultData*/,
- null /*resultExtras*/, requiredPermissions, null, AppOpsManager.OP_NONE,
- bOptions /*options*/, serialized, false /*sticky*/, callingPid,
- callingUid, callingUid, callingPid, userId,
- false /*allowBackgroundStarts*/,
+ null /*resultExtras*/, requiredPermissions,
+ null /*excludedPermissions*/, null /*excludedPackages*/,
+ AppOpsManager.OP_NONE, bOptions /*options*/, serialized,
+ false /*sticky*/, callingPid, callingUid, callingUid, callingPid,
+ userId, false /*allowBackgroundStarts*/,
null /*tokenNeededForBackgroundActivityStarts*/, appIdAllowList);
} finally {
Binder.restoreCallingIdentity(origId);
@@ -16963,7 +17021,7 @@ public class ActivityManagerService extends IActivityManager.Stub
| Intent.FLAG_RECEIVER_FOREGROUND
| Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null, null,
- null, OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
+ null, null, OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
Binder.getCallingUid(), Binder.getCallingPid(), UserHandle.USER_ALL);
if ((changes & ActivityInfo.CONFIG_LOCALE) != 0) {
intent = new Intent(Intent.ACTION_LOCALE_CHANGED);
@@ -16978,8 +17036,8 @@ public class ActivityManagerService extends IActivityManager.Stub
TEMPORARY_ALLOW_LIST_TYPE_FOREGROUND_SERVICE_ALLOWED,
PowerExemptionManager.REASON_LOCALE_CHANGED, "");
broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null, null,
- null, OP_NONE, bOptions.toBundle(), false, false, MY_PID, SYSTEM_UID,
- Binder.getCallingUid(), Binder.getCallingPid(),
+ null, null, OP_NONE, bOptions.toBundle(), false, false, MY_PID,
+ SYSTEM_UID, Binder.getCallingUid(), Binder.getCallingPid(),
UserHandle.USER_ALL);
}
@@ -16994,8 +17052,9 @@ public class ActivityManagerService extends IActivityManager.Stub
String[] permissions =
new String[] { android.Manifest.permission.INSTALL_PACKAGES };
broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null,
- permissions, null, OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
- Binder.getCallingUid(), Binder.getCallingPid(), UserHandle.USER_ALL);
+ permissions, null, null, OP_NONE, null, false, false, MY_PID,
+ SYSTEM_UID, Binder.getCallingUid(), Binder.getCallingPid(),
+ UserHandle.USER_ALL);
}
}
}
@@ -17019,8 +17078,8 @@ public class ActivityManagerService extends IActivityManager.Stub
}
broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null, null,
- null, OP_NONE, null, false, false, -1, SYSTEM_UID, Binder.getCallingUid(),
- Binder.getCallingPid(), UserHandle.USER_ALL);
+ null, null, OP_NONE, null, false, false, -1, SYSTEM_UID,
+ Binder.getCallingUid(), Binder.getCallingPid(), UserHandle.USER_ALL);
}
}
diff --git a/services/core/java/com/android/server/am/ActivityManagerShellCommand.java b/services/core/java/com/android/server/am/ActivityManagerShellCommand.java
index 402491d8fe80..f83d444c2466 100644
--- a/services/core/java/com/android/server/am/ActivityManagerShellCommand.java
+++ b/services/core/java/com/android/server/am/ActivityManagerShellCommand.java
@@ -183,7 +183,7 @@ final class ActivityManagerShellCommand extends ShellCommand {
private boolean mAsync;
private BroadcastOptions mBroadcastOptions;
private boolean mShowSplashScreen;
- private boolean mDismissKeyguardIfInsecure;
+ private boolean mDismissKeyguard;
final boolean mDumping;
@@ -442,8 +442,8 @@ final class ActivityManagerShellCommand extends ShellCommand {
mAsync = true;
} else if (opt.equals("--splashscreen-show-icon")) {
mShowSplashScreen = true;
- } else if (opt.equals("--dismiss-keyguard-if-insecure")) {
- mDismissKeyguardIfInsecure = true;
+ } else if (opt.equals("--dismiss-keyguard")) {
+ mDismissKeyguard = true;
} else {
return false;
}
@@ -588,11 +588,11 @@ final class ActivityManagerShellCommand extends ShellCommand {
}
options.setSplashScreenStyle(SplashScreen.SPLASH_SCREEN_STYLE_ICON);
}
- if (mDismissKeyguardIfInsecure) {
+ if (mDismissKeyguard) {
if (options == null) {
options = ActivityOptions.makeBasic();
}
- options.setDismissKeyguardIfInsecure();
+ options.setDismissKeyguard();
}
if (mWaitOption) {
result = mInternal.startActivityAndWait(null, SHELL_PACKAGE_NAME, null, intent,
@@ -804,8 +804,8 @@ final class ActivityManagerShellCommand extends ShellCommand {
pw.flush();
Bundle bundle = mBroadcastOptions == null ? null : mBroadcastOptions.toBundle();
mInterface.broadcastIntentWithFeature(null, null, intent, null, receiver, 0, null, null,
- requiredPermissions, null, android.app.AppOpsManager.OP_NONE, bundle, true, false,
- mUserId);
+ requiredPermissions, null, null, android.app.AppOpsManager.OP_NONE, bundle, true,
+ false, mUserId);
if (!mAsync) {
receiver.waitForFinish();
}
diff --git a/services/core/java/com/android/server/am/AppBatteryTracker.java b/services/core/java/com/android/server/am/AppBatteryTracker.java
index c09bb2d4dc28..1a566a9e2bc5 100644
--- a/services/core/java/com/android/server/am/AppBatteryTracker.java
+++ b/services/core/java/com/android/server/am/AppBatteryTracker.java
@@ -1258,6 +1258,16 @@ final class AppBatteryTracker extends BaseAppStateTracker<AppBatteryPolicy>
+ "current_drain_event_duration_based_threshold_enabled";
/**
+ * Whether or not we should move the app into the restricted bucket level if its background
+ * battery usage goes beyond the threshold. Note this different from the flag
+ * {@link AppRestrictionController.ConstantsObserver#KEY_BG_AUTO_RESTRICT_ABUSIVE_APPS}
+ * which is to control the overall auto bg restrictions.
+ */
+ static final String KEY_BG_CURRENT_DRAIN_AUTO_RESTRICT_ABUSIVE_APPS_ENABLED =
+ DEVICE_CONFIG_SUBNAMESPACE_PREFIX
+ + "current_drain_auto_restrict_abusive_apps_enabled";
+
+ /**
* The types of battery drain we're checking on each app; if the sum of the battery drain
* exceeds the threshold, it'll be moved to restricted standby bucket; the type here
* must be one of, or combination of {@link #BATTERY_USAGE_TYPE_BACKGROUND},
@@ -1353,6 +1363,11 @@ final class AppBatteryTracker extends BaseAppStateTracker<AppBatteryPolicy>
final boolean mDefaultBgCurrentDrainEventDurationBasedThresholdEnabled;
/**
+ * Default value to {@link #mBgCurrentDrainAutoRestrictAbusiveAppsEnabled}.
+ */
+ final boolean mDefaultBgCurrentDrainAutoRestrictAbusiveAppsEnabled;
+
+ /**
* Default value to {@link #mBgCurrentDrainRestrictedBucketTypes}.
*/
final int mDefaultCurrentDrainTypesToRestrictedBucket;
@@ -1430,6 +1445,11 @@ final class AppBatteryTracker extends BaseAppStateTracker<AppBatteryPolicy>
volatile boolean mBgCurrentDrainEventDurationBasedThresholdEnabled;
/**
+ * @see #KEY_BG_CURRENT_DRAIN_AUTO_RESTRICT_ABUSIVE_APPS_ENABLED.
+ */
+ volatile boolean mBgCurrentDrainAutoRestrictAbusiveAppsEnabled;
+
+ /**
* @see #KEY_BG_CURRENT_DRAIN_TYPES_TO_RESTRICTED_BUCKET.
*/
volatile int mBgCurrentDrainRestrictedBucketTypes;
@@ -1520,6 +1540,8 @@ final class AppBatteryTracker extends BaseAppStateTracker<AppBatteryPolicy>
R.integer.config_bg_current_drain_location_min_duration) * 1_000;
mDefaultBgCurrentDrainEventDurationBasedThresholdEnabled = resources.getBoolean(
R.bool.config_bg_current_drain_event_duration_based_threshold_enabled);
+ mDefaultBgCurrentDrainAutoRestrictAbusiveAppsEnabled = resources.getBoolean(
+ R.bool.config_bg_current_drain_auto_restrict_abusive_apps);
mDefaultCurrentDrainTypesToRestrictedBucket = resources.getInteger(
R.integer.config_bg_current_drain_types_to_restricted_bucket);
mDefaultBgCurrentDrainTypesToBgRestricted = resources.getInteger(
@@ -1569,6 +1591,9 @@ final class AppBatteryTracker extends BaseAppStateTracker<AppBatteryPolicy>
case KEY_BG_CURRENT_DRAIN_POWER_COMPONENTS:
updateCurrentDrainThreshold();
break;
+ case KEY_BG_CURRENT_DRAIN_AUTO_RESTRICT_ABUSIVE_APPS_ENABLED:
+ updateBgCurrentDrainAutoRestrictAbusiveAppsEnabled();
+ break;
case KEY_BG_CURRENT_DRAIN_WINDOW:
updateCurrentDrainWindow();
break;
@@ -1701,6 +1726,13 @@ final class AppBatteryTracker extends BaseAppStateTracker<AppBatteryPolicy>
DEFAULT_BG_CURRENT_DRAIN_DECOUPLE_THRESHOLD);
}
+ private void updateBgCurrentDrainAutoRestrictAbusiveAppsEnabled() {
+ mBgCurrentDrainAutoRestrictAbusiveAppsEnabled = DeviceConfig.getBoolean(
+ DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
+ KEY_BG_CURRENT_DRAIN_AUTO_RESTRICT_ABUSIVE_APPS_ENABLED,
+ mDefaultBgCurrentDrainAutoRestrictAbusiveAppsEnabled);
+ }
+
@Override
public void onSystemReady() {
mBatteryFullChargeMah =
@@ -1714,6 +1746,7 @@ final class AppBatteryTracker extends BaseAppStateTracker<AppBatteryPolicy>
updateCurrentDrainEventDurationBasedThresholdEnabled();
updateCurrentDrainExemptedTypes();
updateCurrentDrainDecoupleThresholds();
+ updateBgCurrentDrainAutoRestrictAbusiveAppsEnabled();
}
@Override
@@ -1728,9 +1761,12 @@ final class AppBatteryTracker extends BaseAppStateTracker<AppBatteryPolicy>
if (pair != null) {
final long lastInteractionTime = mLastInteractionTime.get(uid, 0L);
final long[] ts = pair.first;
- final int restrictedLevel = ts[TIME_STAMP_INDEX_RESTRICTED_BUCKET]
- > (lastInteractionTime + mBgCurrentDrainInteractionGracePeriodMs)
- && mTracker.mAppRestrictionController.isAutoRestrictAbusiveAppEnabled()
+ final boolean noInteractionRecently = ts[TIME_STAMP_INDEX_RESTRICTED_BUCKET]
+ > (lastInteractionTime + mBgCurrentDrainInteractionGracePeriodMs);
+ final boolean canRestrict =
+ mTracker.mAppRestrictionController.isAutoRestrictAbusiveAppEnabled()
+ && mBgCurrentDrainAutoRestrictAbusiveAppsEnabled;
+ final int restrictedLevel = noInteractionRecently && canRestrict
? RESTRICTION_LEVEL_RESTRICTED_BUCKET
: RESTRICTION_LEVEL_ADAPTIVE_BUCKET;
if (maxLevel > RESTRICTION_LEVEL_BACKGROUND_RESTRICTED) {
@@ -2066,6 +2102,10 @@ final class AppBatteryTracker extends BaseAppStateTracker<AppBatteryPolicy>
pw.print('=');
pw.println(mBgCurrentDrainEventDurationBasedThresholdEnabled);
pw.print(prefix);
+ pw.print(KEY_BG_CURRENT_DRAIN_AUTO_RESTRICT_ABUSIVE_APPS_ENABLED);
+ pw.print('=');
+ pw.println(mBgCurrentDrainAutoRestrictAbusiveAppsEnabled);
+ pw.print(prefix);
pw.print(KEY_BG_CURRENT_DRAIN_TYPES_TO_RESTRICTED_BUCKET);
pw.print('=');
pw.println(batteryUsageTypesToString(mBgCurrentDrainRestrictedBucketTypes));
diff --git a/services/core/java/com/android/server/am/BatteryExternalStatsWorker.java b/services/core/java/com/android/server/am/BatteryExternalStatsWorker.java
index 84969aa9e916..702526a4beab 100644
--- a/services/core/java/com/android/server/am/BatteryExternalStatsWorker.java
+++ b/services/core/java/com/android/server/am/BatteryExternalStatsWorker.java
@@ -320,12 +320,11 @@ class BatteryExternalStatsWorker implements BatteryStatsImpl.ExternalStatsSync {
}
@Override
- public Future<?> scheduleSyncDueToProcessStateChange(long delayMillis) {
+ public void scheduleSyncDueToProcessStateChange(int flags, long delayMillis) {
synchronized (BatteryExternalStatsWorker.this) {
mProcessStateSync = scheduleDelayedSyncLocked(mProcessStateSync,
- () -> scheduleSync("procstate-change", UPDATE_ON_PROC_STATE_CHANGE),
+ () -> scheduleSync("procstate-change", flags),
delayMillis);
- return mProcessStateSync;
}
}
diff --git a/services/core/java/com/android/server/am/BroadcastQueue.java b/services/core/java/com/android/server/am/BroadcastQueue.java
index dd7fb84b46bf..d2e40c56c772 100644
--- a/services/core/java/com/android/server/am/BroadcastQueue.java
+++ b/services/core/java/com/android/server/am/BroadcastQueue.java
@@ -860,6 +860,21 @@ public final class BroadcastQueue {
}
}
+ // Check that the receiver does *not* belong to any of the excluded packages
+ if (!skip && r.excludedPackages != null && r.excludedPackages.length > 0) {
+ if (ArrayUtils.contains(r.excludedPackages, filter.packageName)) {
+ Slog.w(TAG, "Skipping delivery of excluded package "
+ + r.intent.toString()
+ + " to " + filter.receiverList.app
+ + " (pid=" + filter.receiverList.pid
+ + ", uid=" + filter.receiverList.uid + ")"
+ + " excludes package " + filter.packageName
+ + " due to sender " + r.callerPackage
+ + " (uid " + r.callingUid + ")");
+ skip = true;
+ }
+ }
+
// If the broadcast also requires an app op check that as well.
if (!skip && r.appOp != AppOpsManager.OP_NONE
&& mService.getAppOpsManager().noteOpNoThrow(r.appOp,
@@ -1721,6 +1736,19 @@ public final class BroadcastQueue {
}
}
+ // Check that the receiver does *not* belong to any of the excluded packages
+ if (!skip && r.excludedPackages != null && r.excludedPackages.length > 0) {
+ if (ArrayUtils.contains(r.excludedPackages, component.getPackageName())) {
+ Slog.w(TAG, "Skipping delivery of excluded package "
+ + r.intent + " to "
+ + component.flattenToShortString()
+ + " excludes package " + component.getPackageName()
+ + " due to sender " + r.callerPackage
+ + " (uid " + r.callingUid + ")");
+ skip = true;
+ }
+ }
+
if (!skip && info.activityInfo.applicationInfo.uid != Process.SYSTEM_UID &&
r.requiredPermissions != null && r.requiredPermissions.length > 0) {
for (int i = 0; i < r.requiredPermissions.length; i++) {
diff --git a/services/core/java/com/android/server/am/BroadcastRecord.java b/services/core/java/com/android/server/am/BroadcastRecord.java
index 5343af25fd39..19ffc1733f3d 100644
--- a/services/core/java/com/android/server/am/BroadcastRecord.java
+++ b/services/core/java/com/android/server/am/BroadcastRecord.java
@@ -75,6 +75,7 @@ final class BroadcastRecord extends Binder {
final String resolvedType; // the resolved data type
final String[] requiredPermissions; // permissions the caller has required
final String[] excludedPermissions; // permissions to exclude
+ final String[] excludedPackages; // packages to exclude
final int appOp; // an app op that is associated with this broadcast
final BroadcastOptions options; // BroadcastOptions supplied by caller
final List receivers; // contains BroadcastFilter and ResolveInfo
@@ -162,6 +163,10 @@ final class BroadcastRecord extends Binder {
pw.print(prefix); pw.print("excludedPermissions=");
pw.print(Arrays.toString(excludedPermissions));
}
+ if (excludedPackages != null && excludedPackages.length > 0) {
+ pw.print(prefix); pw.print("excludedPackages=");
+ pw.print(Arrays.toString(excludedPackages));
+ }
if (options != null) {
pw.print(prefix); pw.print("options="); pw.println(options.toBundle());
}
@@ -260,7 +265,8 @@ final class BroadcastRecord extends Binder {
Intent _intent, ProcessRecord _callerApp, String _callerPackage,
@Nullable String _callerFeatureId, int _callingPid, int _callingUid,
boolean _callerInstantApp, String _resolvedType,
- String[] _requiredPermissions, String[] _excludedPermissions, int _appOp,
+ String[] _requiredPermissions, String[] _excludedPermissions,
+ String[] _excludedPackages, int _appOp,
BroadcastOptions _options, List _receivers, IIntentReceiver _resultTo, int _resultCode,
String _resultData, Bundle _resultExtras, boolean _serialized, boolean _sticky,
boolean _initialSticky, int _userId, boolean allowBackgroundActivityStarts,
@@ -280,6 +286,7 @@ final class BroadcastRecord extends Binder {
resolvedType = _resolvedType;
requiredPermissions = _requiredPermissions;
excludedPermissions = _excludedPermissions;
+ excludedPackages = _excludedPackages;
appOp = _appOp;
options = _options;
receivers = _receivers;
@@ -321,6 +328,7 @@ final class BroadcastRecord extends Binder {
resolvedType = from.resolvedType;
requiredPermissions = from.requiredPermissions;
excludedPermissions = from.excludedPermissions;
+ excludedPackages = from.excludedPackages;
appOp = from.appOp;
options = from.options;
receivers = from.receivers;
@@ -381,9 +389,10 @@ final class BroadcastRecord extends Binder {
// build a new BroadcastRecord around that single-target list
BroadcastRecord split = new BroadcastRecord(queue, intent, callerApp, callerPackage,
callerFeatureId, callingPid, callingUid, callerInstantApp, resolvedType,
- requiredPermissions, excludedPermissions, appOp, options, splitReceivers, resultTo,
- resultCode, resultData, resultExtras, ordered, sticky, initialSticky, userId,
- allowBackgroundActivityStarts, mBackgroundActivityStartsToken, timeoutExempt);
+ requiredPermissions, excludedPermissions, excludedPackages, appOp, options,
+ splitReceivers, resultTo, resultCode, resultData, resultExtras, ordered, sticky,
+ initialSticky, userId, allowBackgroundActivityStarts,
+ mBackgroundActivityStartsToken, timeoutExempt);
split.enqueueTime = this.enqueueTime;
split.enqueueRealTime = this.enqueueRealTime;
split.enqueueClockTime = this.enqueueClockTime;
@@ -459,7 +468,7 @@ final class BroadcastRecord extends Binder {
for (int i = 0; i < uidSize; i++) {
final BroadcastRecord br = new BroadcastRecord(queue, intent, callerApp, callerPackage,
callerFeatureId, callingPid, callingUid, callerInstantApp, resolvedType,
- requiredPermissions, excludedPermissions, appOp, options,
+ requiredPermissions, excludedPermissions, excludedPackages, appOp, options,
uid2receiverList.valueAt(i), null /* _resultTo */,
resultCode, resultData, resultExtras, ordered, sticky, initialSticky, userId,
allowBackgroundActivityStarts, mBackgroundActivityStartsToken, timeoutExempt);
diff --git a/services/core/java/com/android/server/am/ComponentAliasResolver.java b/services/core/java/com/android/server/am/ComponentAliasResolver.java
index 2db3b15e719d..01735a754c83 100644
--- a/services/core/java/com/android/server/am/ComponentAliasResolver.java
+++ b/services/core/java/com/android/server/am/ComponentAliasResolver.java
@@ -483,7 +483,7 @@ public class ComponentAliasResolver {
@Nullable
public Resolution<ResolveInfo> resolveReceiver(@NonNull Intent intent,
@NonNull ResolveInfo receiver, @Nullable String resolvedType,
- int packageFlags, int userId, int callingUid) {
+ int packageFlags, int userId, int callingUid, boolean forSend) {
// Resolve this alias.
final Resolution<ComponentName> resolution = resolveComponentAlias(() ->
receiver.activityInfo.getComponentName());
@@ -506,8 +506,8 @@ public class ComponentAliasResolver {
i.setPackage(null);
i.setComponent(resolution.getTarget());
- List<ResolveInfo> resolved = pmi.queryIntentReceivers(i,
- resolvedType, packageFlags, callingUid, userId);
+ List<ResolveInfo> resolved = pmi.queryIntentReceivers(
+ i, resolvedType, packageFlags, callingUid, userId, forSend);
if (resolved == null || resolved.size() == 0) {
// Target component not found.
Slog.w(TAG, "Alias target " + target.flattenToShortString() + " not found");
diff --git a/services/core/java/com/android/server/am/PreBootBroadcaster.java b/services/core/java/com/android/server/am/PreBootBroadcaster.java
index 756209824614..35f91ba1169b 100644
--- a/services/core/java/com/android/server/am/PreBootBroadcaster.java
+++ b/services/core/java/com/android/server/am/PreBootBroadcaster.java
@@ -124,7 +124,7 @@ public abstract class PreBootBroadcaster extends IIntentReceiver.Stub {
REASON_PRE_BOOT_COMPLETED, "");
synchronized (mService) {
mService.broadcastIntentLocked(null, null, null, mIntent, null, this, 0, null, null,
- null, null, AppOpsManager.OP_NONE, bOptions.toBundle(), true,
+ null, null, null, AppOpsManager.OP_NONE, bOptions.toBundle(), true,
false, ActivityManagerService.MY_PID,
Process.SYSTEM_UID, Binder.getCallingUid(), Binder.getCallingPid(), mUserId);
}
diff --git a/services/core/java/com/android/server/am/UserController.java b/services/core/java/com/android/server/am/UserController.java
index c04377389e8e..7ffea26638f5 100644
--- a/services/core/java/com/android/server/am/UserController.java
+++ b/services/core/java/com/android/server/am/UserController.java
@@ -3203,8 +3203,8 @@ class UserController implements Handler.Callback {
synchronized (mService) {
return mService.broadcastIntentLocked(null, null, null, intent, resolvedType,
resultTo, resultCode, resultData, resultExtras, requiredPermissions, null,
- appOp, bOptions, ordered, sticky, callingPid, callingUid, realCallingUid,
- realCallingPid, userId);
+ null, appOp, bOptions, ordered, sticky, callingPid, callingUid,
+ realCallingUid, realCallingPid, userId);
}
}
diff --git a/services/core/java/com/android/server/apphibernation/AppHibernationService.java b/services/core/java/com/android/server/apphibernation/AppHibernationService.java
index d239c02d4529..27ce493f717f 100644
--- a/services/core/java/com/android/server/apphibernation/AppHibernationService.java
+++ b/services/core/java/com/android/server/apphibernation/AppHibernationService.java
@@ -501,6 +501,7 @@ public final class AppHibernationService extends SystemService {
null /* resultExtras */,
requiredPermissions,
null /* excludedPermissions */,
+ null /* excludedPackages */,
OP_NONE,
null /* bOptions */,
false /* serialized */,
@@ -519,6 +520,7 @@ public final class AppHibernationService extends SystemService {
null /* resultExtras */,
requiredPermissions,
null /* excludedPermissions */,
+ null /* excludedPackages */,
OP_NONE,
null /* bOptions */,
false /* serialized */,
diff --git a/services/core/java/com/android/server/appop/AppOpsService.java b/services/core/java/com/android/server/appop/AppOpsService.java
index 8cef0b0130f6..b56654fd7b9a 100644
--- a/services/core/java/com/android/server/appop/AppOpsService.java
+++ b/services/core/java/com/android/server/appop/AppOpsService.java
@@ -43,6 +43,7 @@ import static android.app.AppOpsManager.OP_FLAG_SELF;
import static android.app.AppOpsManager.OP_FLAG_TRUSTED_PROXIED;
import static android.app.AppOpsManager.OP_NONE;
import static android.app.AppOpsManager.OP_PLAY_AUDIO;
+import static android.app.AppOpsManager.OP_RECEIVE_AMBIENT_TRIGGER_AUDIO;
import static android.app.AppOpsManager.OP_RECORD_AUDIO;
import static android.app.AppOpsManager.OP_RECORD_AUDIO_HOTWORD;
import static android.app.AppOpsManager.OnOpStartedListener.START_TYPE_FAILED;
@@ -3257,7 +3258,7 @@ public class AppOpsService extends IAppOpsService.Stub {
return AppOpsManager.MODE_IGNORED;
}
synchronized (this) {
- if (isOpRestrictedLocked(uid, code, packageName, attributionTag, pvr.bypass)) {
+ if (isOpRestrictedLocked(uid, code, packageName, attributionTag, pvr.bypass, true)) {
return AppOpsManager.MODE_IGNORED;
}
code = AppOpsManager.opToSwitch(code);
@@ -3482,7 +3483,7 @@ public class AppOpsService extends IAppOpsService.Stub {
final int switchCode = AppOpsManager.opToSwitch(code);
final UidState uidState = ops.uidState;
- if (isOpRestrictedLocked(uid, code, packageName, attributionTag, pvr.bypass)) {
+ if (isOpRestrictedLocked(uid, code, packageName, attributionTag, pvr.bypass, false)) {
attributedOp.rejected(uidState.state, flags);
scheduleOpNotedIfNeededLocked(code, uid, packageName, attributionTag, flags,
AppOpsManager.MODE_IGNORED);
@@ -3849,7 +3850,7 @@ public class AppOpsService extends IAppOpsService.Stub {
// the data gated by OP_RECORD_AUDIO.
//
// TODO: Revert this change before Android 12.
- if (code == OP_RECORD_AUDIO_HOTWORD) {
+ if (code == OP_RECORD_AUDIO_HOTWORD || code == OP_RECEIVE_AMBIENT_TRIGGER_AUDIO) {
int result = checkOperation(OP_RECORD_AUDIO, uid, packageName);
if (result != AppOpsManager.MODE_ALLOWED) {
return new SyncNotedAppOp(result, code, attributionTag, packageName);
@@ -3996,7 +3997,8 @@ public class AppOpsService extends IAppOpsService.Stub {
final Op op = getOpLocked(ops, code, uid, true);
final AttributedOp attributedOp = op.getOrCreateAttribution(op, attributionTag);
final UidState uidState = ops.uidState;
- isRestricted = isOpRestrictedLocked(uid, code, packageName, attributionTag, pvr.bypass);
+ isRestricted = isOpRestrictedLocked(uid, code, packageName, attributionTag, pvr.bypass,
+ false);
final int switchCode = AppOpsManager.opToSwitch(code);
// If there is a non-default per UID policy (we set UID op mode only if
// non-default) it takes over, otherwise use the per package policy.
@@ -4833,7 +4835,7 @@ public class AppOpsService extends IAppOpsService.Stub {
}
private boolean isOpRestrictedLocked(int uid, int code, String packageName,
- String attributionTag, @Nullable RestrictionBypass appBypass) {
+ String attributionTag, @Nullable RestrictionBypass appBypass, boolean isCheckOp) {
int restrictionSetCount = mOpGlobalRestrictions.size();
for (int i = 0; i < restrictionSetCount; i++) {
@@ -4850,7 +4852,8 @@ public class AppOpsService extends IAppOpsService.Stub {
// For each client, check that the given op is not restricted, or that the given
// package is exempt from the restriction.
ClientUserRestrictionState restrictionState = mOpUserRestrictions.valueAt(i);
- if (restrictionState.hasRestriction(code, packageName, attributionTag, userHandle)) {
+ if (restrictionState.hasRestriction(code, packageName, attributionTag, userHandle,
+ isCheckOp)) {
RestrictionBypass opBypass = opAllowSystemBypassRestriction(code);
if (opBypass != null) {
// If we are the system, bypass user restrictions for certain codes
@@ -7223,7 +7226,7 @@ public class AppOpsService extends IAppOpsService.Stub {
}
public boolean hasRestriction(int restriction, String packageName, String attributionTag,
- int userId) {
+ int userId, boolean isCheckOp) {
if (perUserRestrictions == null) {
return false;
}
@@ -7242,6 +7245,9 @@ public class AppOpsService extends IAppOpsService.Stub {
return true;
}
+ if (isCheckOp) {
+ return !perUserExclusions.includes(packageName);
+ }
return !perUserExclusions.contains(packageName, attributionTag);
}
@@ -7408,7 +7414,8 @@ public class AppOpsService extends IAppOpsService.Stub {
int numRestrictions = mOpUserRestrictions.size();
for (int i = 0; i < numRestrictions; i++) {
if (mOpUserRestrictions.valueAt(i)
- .hasRestriction(code, pkg, attributionTag, user.getIdentifier())) {
+ .hasRestriction(code, pkg, attributionTag, user.getIdentifier(),
+ false)) {
number++;
}
}
diff --git a/services/core/java/com/android/server/appop/DiscreteRegistry.java b/services/core/java/com/android/server/appop/DiscreteRegistry.java
index 8de515d4d3e5..158092f33ee3 100644
--- a/services/core/java/com/android/server/appop/DiscreteRegistry.java
+++ b/services/core/java/com/android/server/appop/DiscreteRegistry.java
@@ -34,6 +34,7 @@ import static android.app.AppOpsManager.OP_FLAG_TRUSTED_PROXY;
import static android.app.AppOpsManager.OP_NONE;
import static android.app.AppOpsManager.OP_PHONE_CALL_CAMERA;
import static android.app.AppOpsManager.OP_PHONE_CALL_MICROPHONE;
+import static android.app.AppOpsManager.OP_RECEIVE_AMBIENT_TRIGGER_AUDIO;
import static android.app.AppOpsManager.OP_RECORD_AUDIO;
import static android.app.AppOpsManager.flagsToString;
import static android.app.AppOpsManager.getUidStateName;
@@ -133,7 +134,7 @@ final class DiscreteRegistry {
private static final String PROPERTY_DISCRETE_OPS_LIST = "discrete_history_ops_cslist";
private static final String DEFAULT_DISCRETE_OPS = OP_FINE_LOCATION + "," + OP_COARSE_LOCATION
+ "," + OP_CAMERA + "," + OP_RECORD_AUDIO + "," + OP_PHONE_CALL_MICROPHONE + ","
- + OP_PHONE_CALL_CAMERA;
+ + OP_PHONE_CALL_CAMERA + "," + OP_RECEIVE_AMBIENT_TRIGGER_AUDIO;
private static final long DEFAULT_DISCRETE_HISTORY_CUTOFF = Duration.ofDays(7).toMillis();
private static final long MAXIMUM_DISCRETE_HISTORY_CUTOFF = Duration.ofDays(30).toMillis();
private static final long DEFAULT_DISCRETE_HISTORY_QUANTIZATION =
diff --git a/services/core/java/com/android/server/audio/AudioService.java b/services/core/java/com/android/server/audio/AudioService.java
index aed63ce5b2c6..0123c646c764 100644
--- a/services/core/java/com/android/server/audio/AudioService.java
+++ b/services/core/java/com/android/server/audio/AudioService.java
@@ -4146,19 +4146,8 @@ public class AudioService extends IAudioService.Stub
{
streamType = mStreamVolumeAlias[streamType];
- if (streamType == AudioSystem.STREAM_MUSIC) {
- flags = updateFlagsForTvPlatform(flags);
- synchronized (mHdmiClientLock) {
- // Don't display volume UI on a TV Playback device when using absolute volume
- if (mHdmiCecVolumeControlEnabled && mHdmiPlaybackClient != null
- && (isAbsoluteVolumeDevice(device)
- || isA2dpAbsoluteVolumeDevice(device))) {
- flags &= ~AudioManager.FLAG_SHOW_UI;
- }
- }
- if (isFullVolumeDevice(device)) {
- flags &= ~AudioManager.FLAG_SHOW_UI;
- }
+ if (streamType == AudioSystem.STREAM_MUSIC && isFullVolumeDevice(device)) {
+ flags &= ~AudioManager.FLAG_SHOW_UI;
}
mVolumeController.postVolumeChanged(streamType, flags);
}
@@ -6648,6 +6637,11 @@ public class AudioService extends IAudioService.Stub
// verify arguments
Objects.requireNonNull(device);
AudioManager.enforceValidVolumeBehavior(deviceVolumeBehavior);
+ sVolumeLogger.log(new AudioEventLogger.StringEvent("setDeviceVolumeBehavior: dev:"
+ + AudioSystem.getOutputDeviceName(device.getInternalType()) + " addr:"
+ + device.getAddress() + " behavior:"
+ + AudioDeviceVolumeManager.volumeBehaviorName(deviceVolumeBehavior)
+ + " pack:" + pkgName).printLog(TAG));
if (pkgName == null) {
pkgName = "";
}
@@ -8363,7 +8357,7 @@ public class AudioService extends IAudioService.Stub
private void avrcpSupportsAbsoluteVolume(String address, boolean support) {
// address is not used for now, but may be used when multiple a2dp devices are supported
sVolumeLogger.log(new AudioEventLogger.StringEvent("avrcpSupportsAbsoluteVolume addr="
- + address + " support=" + support));
+ + address + " support=" + support).printLog(TAG));
mDeviceBroker.setAvrcpAbsoluteVolumeSupported(support);
setAvrcpAbsoluteVolumeSupported(support);
}
diff --git a/services/core/java/com/android/server/audio/SpatializerHelper.java b/services/core/java/com/android/server/audio/SpatializerHelper.java
index 4ac611bb7e2a..0b9cb1977643 100644
--- a/services/core/java/com/android/server/audio/SpatializerHelper.java
+++ b/services/core/java/com/android/server/audio/SpatializerHelper.java
@@ -70,12 +70,6 @@ public class SpatializerHelper {
private @Nullable SensorManager mSensorManager;
//------------------------------------------------------------
- /** head tracker sensor name */
- // TODO: replace with generic head tracker sensor name.
- // the current implementation refers to the "google" namespace but will be replaced
- // by an android name at the next API level revision, it is not Google-specific.
- private static final String HEADTRACKER_SENSOR =
- "com.google.hardware.sensor.hid_dynamic.headtracker";
private static final SparseIntArray SPAT_MODE_FOR_DEVICE_TYPE = new SparseIntArray(15) {
{
@@ -1522,24 +1516,24 @@ public class SpatializerHelper {
private int getHeadSensorHandleUpdateTracker() {
int headHandle = -1;
UUID routingDeviceUuid = mAudioService.getDeviceSensorUuid(ROUTING_DEVICES[0]);
- List<Sensor> sensors = new ArrayList<Sensor>(0);
- sensors.addAll(mSensorManager.getDynamicSensorList(Sensor.TYPE_HEAD_TRACKER));
- sensors.addAll(mSensorManager.getDynamicSensorList(Sensor.TYPE_DEVICE_PRIVATE_BASE));
+ // We limit only to Sensor.TYPE_HEAD_TRACKER here to avoid confusion
+ // with gaming sensors. (Note that Sensor.TYPE_ROTATION_VECTOR
+ // and Sensor.TYPE_GAME_ROTATION_VECTOR are supported internally by
+ // SensorPoseProvider).
+ // Note: this is a dynamic sensor list right now.
+ List<Sensor> sensors = mSensorManager.getDynamicSensorList(Sensor.TYPE_HEAD_TRACKER);
for (Sensor sensor : sensors) {
- if (sensor.getType() == Sensor.TYPE_HEAD_TRACKER
- || sensor.getStringType().equals(HEADTRACKER_SENSOR)) {
- UUID uuid = sensor.getUuid();
- if (uuid.equals(routingDeviceUuid)) {
- headHandle = sensor.getHandle();
- if (!setHasHeadTracker(ROUTING_DEVICES[0])) {
- headHandle = -1;
- }
- break;
- }
- if (uuid.equals(UuidUtils.STANDALONE_UUID)) {
- headHandle = sensor.getHandle();
- break;
+ final UUID uuid = sensor.getUuid();
+ if (uuid.equals(routingDeviceUuid)) {
+ headHandle = sensor.getHandle();
+ if (!setHasHeadTracker(ROUTING_DEVICES[0])) {
+ headHandle = -1;
}
+ break;
+ }
+ if (uuid.equals(UuidUtils.STANDALONE_UUID)) {
+ headHandle = sensor.getHandle();
+ // we do not break, perhaps we find a head tracker on device.
}
}
return headHandle;
diff --git a/services/core/java/com/android/server/biometrics/sensors/face/aidl/FaceResetLockoutClient.java b/services/core/java/com/android/server/biometrics/sensors/face/aidl/FaceResetLockoutClient.java
index de0a36a32b66..bf7a62aadc28 100644
--- a/services/core/java/com/android/server/biometrics/sensors/face/aidl/FaceResetLockoutClient.java
+++ b/services/core/java/com/android/server/biometrics/sensors/face/aidl/FaceResetLockoutClient.java
@@ -88,6 +88,10 @@ public class FaceResetLockoutClient extends HalClientMonitor<AidlSession> implem
mCallback.onClientFinished(this, true /* success */);
}
+ public boolean interruptsPrecedingClients() {
+ return true;
+ }
+
/**
* Reset the local lockout state and notify any listeners.
*
diff --git a/services/core/java/com/android/server/biometrics/sensors/face/hidl/FaceResetLockoutClient.java b/services/core/java/com/android/server/biometrics/sensors/face/hidl/FaceResetLockoutClient.java
index 6e74d3622c1a..f29b9e823109 100644
--- a/services/core/java/com/android/server/biometrics/sensors/face/hidl/FaceResetLockoutClient.java
+++ b/services/core/java/com/android/server/biometrics/sensors/face/hidl/FaceResetLockoutClient.java
@@ -65,6 +65,10 @@ public class FaceResetLockoutClient extends HalClientMonitor<IBiometricsFace> {
startHalOperation();
}
+ public boolean interruptsPrecedingClients() {
+ return true;
+ }
+
@Override
protected void startHalOperation() {
try {
diff --git a/services/core/java/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintResetLockoutClient.java b/services/core/java/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintResetLockoutClient.java
index f90cba79dac2..c8148df9ea71 100644
--- a/services/core/java/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintResetLockoutClient.java
+++ b/services/core/java/com/android/server/biometrics/sensors/fingerprint/aidl/FingerprintResetLockoutClient.java
@@ -82,6 +82,10 @@ class FingerprintResetLockoutClient extends HalClientMonitor<AidlSession> implem
}
}
+ public boolean interruptsPrecedingClients() {
+ return true;
+ }
+
void onLockoutCleared() {
resetLocalLockoutStateToNone(getSensorId(), getTargetUserId(), mLockoutCache,
mLockoutResetDispatcher);
diff --git a/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/FingerprintResetLockoutClient.java b/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/FingerprintResetLockoutClient.java
index 559ca0633c42..843fcc8ee2a6 100644
--- a/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/FingerprintResetLockoutClient.java
+++ b/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/FingerprintResetLockoutClient.java
@@ -50,6 +50,10 @@ public class FingerprintResetLockoutClient extends BaseClientMonitor {
callback.onClientFinished(this, true /* success */);
}
+ public boolean interruptsPrecedingClients() {
+ return true;
+ }
+
@Override
public int getProtoEnum() {
return BiometricsProto.CM_RESET_LOCKOUT;
diff --git a/services/core/java/com/android/server/clipboard/EmulatorClipboardMonitor.java b/services/core/java/com/android/server/clipboard/EmulatorClipboardMonitor.java
index 28c7cad3b184..ab3b2506f5ac 100644
--- a/services/core/java/com/android/server/clipboard/EmulatorClipboardMonitor.java
+++ b/services/core/java/com/android/server/clipboard/EmulatorClipboardMonitor.java
@@ -18,6 +18,7 @@ package com.android.server.clipboard;
import android.annotation.Nullable;
import android.content.ClipData;
+import android.os.PersistableBundle;
import android.os.SystemProperties;
import android.system.ErrnoException;
import android.system.Os;
@@ -25,6 +26,7 @@ import android.system.OsConstants;
import android.system.VmSocketAddress;
import android.util.Slog;
+import java.io.EOFException;
import java.io.FileDescriptor;
import java.io.InterruptedIOException;
import java.net.SocketException;
@@ -58,11 +60,11 @@ class EmulatorClipboardMonitor implements Consumer<ClipData> {
return mPipe;
}
- private synchronized boolean openPipe() {
- if (mPipe != null) {
- return true;
- }
+ private synchronized void setPipeFD(final FileDescriptor fd) {
+ mPipe = fd;
+ }
+ private static FileDescriptor openPipeImpl() {
try {
final FileDescriptor fd = Os.socket(OsConstants.AF_VSOCK, OsConstants.SOCK_STREAM, 0);
@@ -70,39 +72,42 @@ class EmulatorClipboardMonitor implements Consumer<ClipData> {
Os.connect(fd, new VmSocketAddress(HOST_PORT, OsConstants.VMADDR_CID_HOST));
final byte[] handshake = createOpenHandshake();
- Os.write(fd, handshake, 0, handshake.length);
- mPipe = fd;
- return true;
+ writeFully(fd, handshake, 0, handshake.length);
+ return fd;
} catch (ErrnoException | SocketException | InterruptedIOException e) {
Os.close(fd);
}
} catch (ErrnoException e) {
}
- return false;
+ return null;
}
- private synchronized void closePipe() {
- try {
- final FileDescriptor fd = mPipe;
- mPipe = null;
- if (fd != null) {
- Os.close(fd);
- }
- } catch (ErrnoException ignore) {
+ private static FileDescriptor openPipe() throws InterruptedException {
+ FileDescriptor fd = openPipeImpl();
+
+ // There's no guarantee that QEMU pipes will be ready at the moment
+ // this method is invoked. We simply try to get the pipe open and
+ // retry on failure indefinitely.
+ while (fd == null) {
+ Thread.sleep(100);
+ fd = openPipeImpl();
}
+
+ return fd;
}
- private byte[] receiveMessage() throws ErrnoException, InterruptedIOException {
+ private static byte[] receiveMessage(final FileDescriptor fd) throws ErrnoException,
+ InterruptedIOException, EOFException {
final byte[] lengthBits = new byte[4];
- Os.read(mPipe, lengthBits, 0, lengthBits.length);
+ readFully(fd, lengthBits, 0, lengthBits.length);
final ByteBuffer bb = ByteBuffer.wrap(lengthBits);
bb.order(ByteOrder.LITTLE_ENDIAN);
final int msgLen = bb.getInt();
final byte[] msg = new byte[msgLen];
- Os.read(mPipe, msg, 0, msg.length);
+ readFully(fd, msg, 0, msg.length);
return msg;
}
@@ -115,35 +120,46 @@ class EmulatorClipboardMonitor implements Consumer<ClipData> {
bb.order(ByteOrder.LITTLE_ENDIAN);
bb.putInt(msg.length);
- Os.write(fd, lengthBits, 0, lengthBits.length);
- Os.write(fd, msg, 0, msg.length);
+ writeFully(fd, lengthBits, 0, lengthBits.length);
+ writeFully(fd, msg, 0, msg.length);
}
EmulatorClipboardMonitor(final Consumer<ClipData> setAndroidClipboard) {
this.mHostMonitorThread = new Thread(() -> {
+ FileDescriptor fd = null;
+
while (!Thread.interrupted()) {
try {
- // There's no guarantee that QEMU pipes will be ready at the moment
- // this method is invoked. We simply try to get the pipe open and
- // retry on failure indefinitely.
- while (!openPipe()) {
- Thread.sleep(100);
+ if (fd == null) {
+ fd = openPipe();
+ setPipeFD(fd);
}
- final byte[] receivedData = receiveMessage();
+ final byte[] receivedData = receiveMessage(fd);
final String str = new String(receivedData);
final ClipData clip = new ClipData("host clipboard",
new String[]{"text/plain"},
new ClipData.Item(str));
+ final PersistableBundle bundle = new PersistableBundle();
+ bundle.putBoolean("com.android.systemui.SUPPRESS_CLIPBOARD_OVERLAY", true);
+ clip.getDescription().setExtras(bundle);
if (LOG_CLIBOARD_ACCESS) {
Slog.i(TAG, "Setting the guest clipboard to '" + str + "'");
}
setAndroidClipboard.accept(clip);
- } catch (ErrnoException | InterruptedIOException e) {
- closePipe();
- } catch (InterruptedException | IllegalArgumentException e) {
+ } catch (ErrnoException | EOFException | InterruptedIOException
+ | InterruptedException e) {
+ setPipeFD(null);
+
+ try {
+ Os.close(fd);
+ } catch (ErrnoException e2) {
+ // ignore
+ }
+
+ fd = null;
}
}
});
@@ -153,33 +169,70 @@ class EmulatorClipboardMonitor implements Consumer<ClipData> {
@Override
public void accept(final @Nullable ClipData clip) {
+ final FileDescriptor fd = getPipeFD();
+ if (fd != null) {
+ setHostClipboard(fd, getClipString(clip));
+ }
+ }
+
+ private String getClipString(final @Nullable ClipData clip) {
if (clip == null) {
- setHostClipboardImpl("");
- } else if (clip.getItemCount() > 0) {
- final CharSequence text = clip.getItemAt(0).getText();
- if (text != null) {
- setHostClipboardImpl(text.toString());
- }
+ return "";
+ }
+
+ if (clip.getItemCount() == 0) {
+ return "";
}
+
+ final CharSequence text = clip.getItemAt(0).getText();
+ if (text == null) {
+ return "";
+ }
+
+ return text.toString();
}
- private void setHostClipboardImpl(final String value) {
- final FileDescriptor pipeFD = getPipeFD();
+ private static void setHostClipboard(final FileDescriptor fd, final String value) {
+ Thread t = new Thread(() -> {
+ if (LOG_CLIBOARD_ACCESS) {
+ Slog.i(TAG, "Setting the host clipboard to '" + value + "'");
+ }
- if (pipeFD != null) {
- Thread t = new Thread(() -> {
- if (LOG_CLIBOARD_ACCESS) {
- Slog.i(TAG, "Setting the host clipboard to '" + value + "'");
- }
+ try {
+ sendMessage(fd, value.getBytes());
+ } catch (ErrnoException | InterruptedIOException e) {
+ Slog.e(TAG, "Failed to set host clipboard " + e.getMessage());
+ } catch (IllegalArgumentException e) {
+ }
+ });
+ t.start();
+ }
- try {
- sendMessage(pipeFD, value.getBytes());
- } catch (ErrnoException | InterruptedIOException e) {
- Slog.e(TAG, "Failed to set host clipboard " + e.getMessage());
- } catch (IllegalArgumentException e) {
- }
- });
- t.start();
+ private static void readFully(final FileDescriptor fd,
+ final byte[] buf, int offset, int size)
+ throws ErrnoException, InterruptedIOException, EOFException {
+ while (size > 0) {
+ final int r = Os.read(fd, buf, offset, size);
+ if (r > 0) {
+ offset += r;
+ size -= r;
+ } else {
+ throw new EOFException();
+ }
+ }
+ }
+
+ private static void writeFully(final FileDescriptor fd,
+ final byte[] buf, int offset, int size)
+ throws ErrnoException, InterruptedIOException {
+ while (size > 0) {
+ final int r = Os.write(fd, buf, offset, size);
+ if (r > 0) {
+ offset += r;
+ size -= r;
+ } else {
+ throw new ErrnoException("write", OsConstants.EIO);
+ }
}
}
}
diff --git a/services/core/java/com/android/server/connectivity/Vpn.java b/services/core/java/com/android/server/connectivity/Vpn.java
index 68a53f13da8a..089a92402de5 100644
--- a/services/core/java/com/android/server/connectivity/Vpn.java
+++ b/services/core/java/com/android/server/connectivity/Vpn.java
@@ -27,6 +27,8 @@ import static android.net.VpnManager.NOTIFICATION_CHANNEL_VPN;
import static android.os.PowerWhitelistManager.REASON_VPN;
import static android.os.UserHandle.PER_USER_RANGE;
+import static com.android.server.vcn.util.PersistableBundleUtils.STRING_DESERIALIZER;
+
import static java.util.Objects.requireNonNull;
import android.Manifest;
@@ -97,6 +99,7 @@ import android.os.INetworkManagementService;
import android.os.Looper;
import android.os.Parcel;
import android.os.ParcelFileDescriptor;
+import android.os.PersistableBundle;
import android.os.Process;
import android.os.RemoteException;
import android.os.SystemClock;
@@ -127,6 +130,7 @@ import com.android.net.module.util.NetworkStackConstants;
import com.android.server.DeviceIdleInternal;
import com.android.server.LocalServices;
import com.android.server.net.BaseNetworkObserver;
+import com.android.server.vcn.util.PersistableBundleUtils;
import libcore.io.IoUtils;
@@ -174,6 +178,8 @@ public class Vpn {
private static final String VPN_PROVIDER_NAME_BASE = "VpnNetworkProvider:";
private static final boolean LOGD = true;
private static final String ANDROID_KEYSTORE_PROVIDER = "AndroidKeyStore";
+ /** Key containing prefix of vpn app excluded list */
+ @VisibleForTesting static final String VPN_APP_EXCLUDED = "VPN_APP_EXCLUDED_";
// Length of time (in milliseconds) that an app hosting an always-on VPN is placed on
// the device idle allowlist during service launch and VPN bootstrap.
@@ -209,7 +215,6 @@ public class Vpn {
private final NetworkInfo mNetworkInfo;
private int mLegacyState;
@VisibleForTesting protected String mPackage;
- private String mSessionKey;
private int mOwnerUID;
private boolean mIsPackageTargetingAtLeastQ;
@VisibleForTesting
@@ -1534,11 +1539,17 @@ public class Vpn {
}
// Note: Return type guarantees results are deduped and sorted, which callers require.
+ // This method also adds the SDK sandbox UIDs corresponding to the applications by default,
+ // since apps are generally not aware of them, yet they should follow the VPN configuration
+ // of the app they belong to.
private SortedSet<Integer> getAppsUids(List<String> packageNames, int userId) {
SortedSet<Integer> uids = new TreeSet<>();
for (String app : packageNames) {
int uid = getAppUid(app, userId);
if (uid != -1) uids.add(uid);
+ if (Process.isApplicationUid(uid)) {
+ uids.add(Process.toSdkSandboxUid(uid));
+ }
}
return uids;
}
@@ -1991,9 +2002,7 @@ public class Vpn {
public synchronized int getActiveVpnType() {
if (!mNetworkInfo.isConnectedOrConnecting()) return VpnManager.TYPE_VPN_NONE;
if (mVpnRunner == null) return VpnManager.TYPE_VPN_SERVICE;
- return mVpnRunner instanceof IkeV2VpnRunner
- ? VpnManager.TYPE_VPN_PLATFORM
- : VpnManager.TYPE_VPN_LEGACY;
+ return isIkev2VpnRunner() ? VpnManager.TYPE_VPN_PLATFORM : VpnManager.TYPE_VPN_LEGACY;
}
private void updateAlwaysOnNotification(DetailedState networkState) {
@@ -2531,12 +2540,15 @@ public class Vpn {
@Nullable private IpSecTunnelInterface mTunnelIface;
@Nullable private IkeSession mSession;
@Nullable private Network mActiveNetwork;
+ private final String mSessionKey;
IkeV2VpnRunner(@NonNull Ikev2VpnProfile profile) {
super(TAG);
mProfile = profile;
mIpSecManager = (IpSecManager) mContext.getSystemService(Context.IPSEC_SERVICE);
- mNetworkCallback = new VpnIkev2Utils.Ikev2VpnNetworkCallback(TAG, this);
+ // Pass mExecutor into Ikev2VpnNetworkCallback and make sure that IkeV2VpnRunnerCallback
+ // will be called by the mExecutor thread.
+ mNetworkCallback = new VpnIkev2Utils.Ikev2VpnNetworkCallback(TAG, this, mExecutor);
mSessionKey = UUID.randomUUID().toString();
}
@@ -2630,6 +2642,8 @@ public class Vpn {
mConfig.underlyingNetworks = new Network[] {network};
+ mConfig.disallowedApplications = getAppExclusionList(mPackage);
+
networkAgent = mNetworkAgent;
// The below must be done atomically with the mConfig update, otherwise
@@ -2691,73 +2705,68 @@ public class Vpn {
* <p>The Ikev2VpnRunner will unconditionally switch to the new network, killing the old IKE
* state in the process, and starting a new IkeSession instance.
*
- * <p>This method is called multiple times over the lifetime of the Ikev2VpnRunner, and is
- * called on the ConnectivityService thread. Thus, the actual work MUST be proxied to the
- * mExecutor thread in order to ensure consistency of the Ikev2VpnRunner fields.
+ * <p>This method MUST always be called on the mExecutor thread in order to ensure
+ * consistency of the Ikev2VpnRunner fields.
*/
public void onDefaultNetworkChanged(@NonNull Network network) {
Log.d(TAG, "Starting IKEv2/IPsec session on new network: " + network);
- // Proxy to the Ikev2VpnRunner (single-thread) executor to ensure consistency in lieu
- // of locking.
- mExecutor.execute(() -> {
- try {
- if (!mIsRunning) {
- Log.d(TAG, "onDefaultNetworkChanged after exit");
- return; // VPN has been shut down.
- }
+ try {
+ if (!mIsRunning) {
+ Log.d(TAG, "onDefaultNetworkChanged after exit");
+ return; // VPN has been shut down.
+ }
- // Clear mInterface to prevent Ikev2VpnRunner being cleared when
- // interfaceRemoved() is called.
- mInterface = null;
- // Without MOBIKE, we have no way to seamlessly migrate. Close on old
- // (non-default) network, and start the new one.
- resetIkeState();
- mActiveNetwork = network;
-
- // Get Ike options from IkeTunnelConnectionParams if it's available in the
- // profile.
- final IkeTunnelConnectionParams ikeTunConnParams =
- mProfile.getIkeTunnelConnectionParams();
- final IkeSessionParams ikeSessionParams;
- final ChildSessionParams childSessionParams;
- if (ikeTunConnParams != null) {
- final IkeSessionParams.Builder builder = new IkeSessionParams.Builder(
- ikeTunConnParams.getIkeSessionParams()).setNetwork(network);
- ikeSessionParams = builder.build();
- childSessionParams = ikeTunConnParams.getTunnelModeChildSessionParams();
- } else {
- ikeSessionParams = VpnIkev2Utils.buildIkeSessionParams(
- mContext, mProfile, network);
- childSessionParams = VpnIkev2Utils.buildChildSessionParams(
- mProfile.getAllowedAlgorithms());
- }
+ // Clear mInterface to prevent Ikev2VpnRunner being cleared when
+ // interfaceRemoved() is called.
+ mInterface = null;
+ // Without MOBIKE, we have no way to seamlessly migrate. Close on old
+ // (non-default) network, and start the new one.
+ resetIkeState();
+ mActiveNetwork = network;
- // TODO: Remove the need for adding two unused addresses with
- // IPsec tunnels.
- final InetAddress address = InetAddress.getLocalHost();
- mTunnelIface =
- mIpSecManager.createIpSecTunnelInterface(
- address /* unused */,
- address /* unused */,
- network);
- NetdUtils.setInterfaceUp(mNetd, mTunnelIface.getInterfaceName());
-
- mSession = mIkev2SessionCreator.createIkeSession(
- mContext,
- ikeSessionParams,
- childSessionParams,
- mExecutor,
- new VpnIkev2Utils.IkeSessionCallbackImpl(
- TAG, IkeV2VpnRunner.this, network),
- new VpnIkev2Utils.ChildSessionCallbackImpl(
- TAG, IkeV2VpnRunner.this, network));
- Log.d(TAG, "Ike Session started for network " + network);
- } catch (Exception e) {
- Log.i(TAG, "Setup failed for network " + network + ". Aborting", e);
- onSessionLost(network, e);
+ // Get Ike options from IkeTunnelConnectionParams if it's available in the
+ // profile.
+ final IkeTunnelConnectionParams ikeTunConnParams =
+ mProfile.getIkeTunnelConnectionParams();
+ final IkeSessionParams ikeSessionParams;
+ final ChildSessionParams childSessionParams;
+ if (ikeTunConnParams != null) {
+ final IkeSessionParams.Builder builder = new IkeSessionParams.Builder(
+ ikeTunConnParams.getIkeSessionParams()).setNetwork(network);
+ ikeSessionParams = builder.build();
+ childSessionParams = ikeTunConnParams.getTunnelModeChildSessionParams();
+ } else {
+ ikeSessionParams = VpnIkev2Utils.buildIkeSessionParams(
+ mContext, mProfile, network);
+ childSessionParams = VpnIkev2Utils.buildChildSessionParams(
+ mProfile.getAllowedAlgorithms());
}
- });
+
+ // TODO: Remove the need for adding two unused addresses with
+ // IPsec tunnels.
+ final InetAddress address = InetAddress.getLocalHost();
+ mTunnelIface =
+ mIpSecManager.createIpSecTunnelInterface(
+ address /* unused */,
+ address /* unused */,
+ network);
+ NetdUtils.setInterfaceUp(mNetd, mTunnelIface.getInterfaceName());
+
+ mSession = mIkev2SessionCreator.createIkeSession(
+ mContext,
+ ikeSessionParams,
+ childSessionParams,
+ mExecutor,
+ new VpnIkev2Utils.IkeSessionCallbackImpl(
+ TAG, IkeV2VpnRunner.this, network),
+ new VpnIkev2Utils.ChildSessionCallbackImpl(
+ TAG, IkeV2VpnRunner.this, network));
+ Log.d(TAG, "Ike Session started for network " + network);
+ } catch (Exception e) {
+ Log.i(TAG, "Setup failed for network " + network + ". Aborting", e);
+ onSessionLost(network, e);
+ }
}
/** Marks the state as FAILED, and disconnects. */
@@ -2876,7 +2885,6 @@ public class Vpn {
*/
private void disconnectVpnRunner() {
mActiveNetwork = null;
- mSessionKey = null;
mIsRunning = false;
resetIkeState();
@@ -3306,7 +3314,7 @@ public class Vpn {
}
private boolean isCurrentIkev2VpnLocked(@NonNull String packageName) {
- return isCurrentPreparedPackage(packageName) && mVpnRunner instanceof IkeV2VpnRunner;
+ return isCurrentPreparedPackage(packageName) && isIkev2VpnRunner();
}
/**
@@ -3360,6 +3368,16 @@ public class Vpn {
return VpnProfile.decode("" /* Key unused */, encoded);
}
+ private boolean isIkev2VpnRunner() {
+ return (mVpnRunner instanceof IkeV2VpnRunner);
+ }
+
+ @GuardedBy("this")
+ @Nullable
+ private String getSessionKeyLocked() {
+ return isIkev2VpnRunner() ? ((IkeV2VpnRunner) mVpnRunner).mSessionKey : null;
+ }
+
/**
* Starts an already provisioned VPN Profile, keyed by package name.
*
@@ -3387,7 +3405,11 @@ public class Vpn {
}
startVpnProfilePrivileged(profile, packageName);
- return mSessionKey;
+ if (!isIkev2VpnRunner()) {
+ throw new IllegalStateException("mVpnRunner shouldn't be null and should also be "
+ + "an instance of Ikev2VpnRunner");
+ }
+ return getSessionKeyLocked();
} finally {
Binder.restoreCallingIdentity(token);
}
@@ -3472,6 +3494,88 @@ public class Vpn {
}
}
+ private boolean storeAppExclusionList(@NonNull String packageName,
+ @NonNull List<String> excludedApps) {
+ byte[] data;
+ try {
+ final PersistableBundle bundle = PersistableBundleUtils.fromList(
+ excludedApps, PersistableBundleUtils.STRING_SERIALIZER);
+ data = PersistableBundleUtils.toDiskStableBytes(bundle);
+ } catch (IOException e) {
+ Log.e(TAG, "problem writing into stream", e);
+ return false;
+ }
+
+ final long oldId = Binder.clearCallingIdentity();
+ try {
+ getVpnProfileStore().put(getVpnAppExcludedForPackage(packageName), data);
+ } finally {
+ Binder.restoreCallingIdentity(oldId);
+ }
+ return true;
+ }
+
+ @VisibleForTesting
+ String getVpnAppExcludedForPackage(String packageName) {
+ return VPN_APP_EXCLUDED + mUserId + "_" + packageName;
+ }
+
+ /**
+ * Set the application exclusion list for the specified VPN profile.
+ *
+ * @param packageName the package name of the app provisioning this profile
+ * @param excludedApps the list of excluded packages
+ *
+ * @return whether setting the list is successful or not
+ */
+ public synchronized boolean setAppExclusionList(@NonNull String packageName,
+ @NonNull List<String> excludedApps) {
+ enforceNotRestrictedUser();
+ if (!storeAppExclusionList(packageName, excludedApps)) return false;
+ // Re-build and update NetworkCapabilities via NetworkAgent.
+ if (mNetworkAgent != null) {
+ // Only update the platform VPN
+ if (isIkev2VpnRunner()) {
+ mConfig.disallowedApplications = List.copyOf(excludedApps);
+ mNetworkCapabilities = new NetworkCapabilities.Builder(mNetworkCapabilities)
+ .setUids(createUserAndRestrictedProfilesRanges(
+ mUserId, null /* allowedApplications */, excludedApps))
+ .build();
+ mNetworkAgent.sendNetworkCapabilities(mNetworkCapabilities);
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * Gets the application exclusion list for the specified VPN profile.
+ *
+ * @param packageName the package name of the app provisioning this profile
+ * @return the list of excluded packages for the specified VPN profile or empty list if there is
+ * no provisioned VPN profile.
+ */
+ @NonNull
+ public synchronized List<String> getAppExclusionList(@NonNull String packageName) {
+ enforceNotRestrictedUser();
+
+ final long oldId = Binder.clearCallingIdentity();
+ try {
+ final byte[] bytes = getVpnProfileStore().get(getVpnAppExcludedForPackage(packageName));
+
+ if (bytes == null || bytes.length == 0) return new ArrayList<>();
+
+ final PersistableBundle bundle = PersistableBundleUtils.fromDiskStableBytes(bytes);
+ return PersistableBundleUtils.toList(bundle, STRING_DESERIALIZER);
+ } catch (IOException e) {
+ Log.e(TAG, "problem reading from stream", e);
+ } finally {
+ Binder.restoreCallingIdentity(oldId);
+ }
+
+ return new ArrayList<>();
+ }
+
private @VpnProfileState.State int getStateFromLegacyState(int legacyState) {
switch (legacyState) {
case LegacyVpnInfo.STATE_CONNECTING:
@@ -3490,11 +3594,8 @@ public class Vpn {
}
private VpnProfileState makeVpnProfileState() {
- // TODO: mSessionKey will be moved to Ikev2VpnRunner once aosp/2007077 is merged, so after
- // merging aosp/2007077, here should check Ikev2VpnRunner is null or not. Session key will
- // be null if Ikev2VpnRunner is null.
- return new VpnProfileState(getStateFromLegacyState(mLegacyState), mSessionKey, mAlwaysOn,
- mLockdown);
+ return new VpnProfileState(getStateFromLegacyState(mLegacyState),
+ isIkev2VpnRunner() ? getSessionKeyLocked() : null, mAlwaysOn, mLockdown);
}
/**
diff --git a/services/core/java/com/android/server/connectivity/VpnIkev2Utils.java b/services/core/java/com/android/server/connectivity/VpnIkev2Utils.java
index a0a596d998bf..6982d6095689 100644
--- a/services/core/java/com/android/server/connectivity/VpnIkev2Utils.java
+++ b/services/core/java/com/android/server/connectivity/VpnIkev2Utils.java
@@ -86,6 +86,7 @@ import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
+import java.util.concurrent.ExecutorService;
/**
* Utility class to build and convert IKEv2/IPsec parameters.
@@ -376,22 +377,25 @@ public class VpnIkev2Utils {
static class Ikev2VpnNetworkCallback extends NetworkCallback {
private final String mTag;
private final Vpn.IkeV2VpnRunnerCallback mCallback;
+ private final ExecutorService mExecutor;
- Ikev2VpnNetworkCallback(String tag, Vpn.IkeV2VpnRunnerCallback callback) {
+ Ikev2VpnNetworkCallback(String tag, Vpn.IkeV2VpnRunnerCallback callback,
+ ExecutorService executor) {
mTag = tag;
mCallback = callback;
+ mExecutor = executor;
}
@Override
public void onAvailable(@NonNull Network network) {
Log.d(mTag, "Starting IKEv2/IPsec session on new network: " + network);
- mCallback.onDefaultNetworkChanged(network);
+ mExecutor.execute(() -> mCallback.onDefaultNetworkChanged(network));
}
@Override
public void onLost(@NonNull Network network) {
Log.d(mTag, "Tearing down; lost network: " + network);
- mCallback.onSessionLost(network, null);
+ mExecutor.execute(() -> mCallback.onSessionLost(network, null));
}
}
diff --git a/services/core/java/com/android/server/display/color/ColorDisplayService.java b/services/core/java/com/android/server/display/color/ColorDisplayService.java
index 80355262be0e..8de150ac4124 100644
--- a/services/core/java/com/android/server/display/color/ColorDisplayService.java
+++ b/services/core/java/com/android/server/display/color/ColorDisplayService.java
@@ -948,19 +948,15 @@ public final class ColorDisplayService extends SystemService {
if (!isColorModeAvailable(colorMode)) {
final int[] mappedColorModes = getContext().getResources().getIntArray(
R.array.config_mappedColorModes);
- if (colorMode == COLOR_MODE_BOOSTED && mappedColorModes.length > COLOR_MODE_NATURAL
- && isColorModeAvailable(mappedColorModes[COLOR_MODE_NATURAL])) {
- colorMode = COLOR_MODE_NATURAL;
- } else if (colorMode == COLOR_MODE_SATURATED
- && mappedColorModes.length > COLOR_MODE_AUTOMATIC
- && isColorModeAvailable(mappedColorModes[COLOR_MODE_AUTOMATIC])) {
- colorMode = COLOR_MODE_AUTOMATIC;
- } else if (colorMode == COLOR_MODE_AUTOMATIC
- && mappedColorModes.length > COLOR_MODE_SATURATED
- && isColorModeAvailable(mappedColorModes[COLOR_MODE_SATURATED])) {
- colorMode = COLOR_MODE_SATURATED;
+ if (colorMode != -1 && mappedColorModes.length > colorMode
+ && isColorModeAvailable(mappedColorModes[colorMode])) {
+ colorMode = mappedColorModes[colorMode];
} else {
- colorMode = -1;
+ final int[] availableColorModes = getContext().getResources().getIntArray(
+ R.array.config_availableColorModes);
+ if (availableColorModes.length > 0) {
+ colorMode = availableColorModes[0];
+ }
}
}
diff --git a/services/core/java/com/android/server/dreams/DreamManagerService.java b/services/core/java/com/android/server/dreams/DreamManagerService.java
index 4e1d899b26a6..63c5456c972b 100644
--- a/services/core/java/com/android/server/dreams/DreamManagerService.java
+++ b/services/core/java/com/android/server/dreams/DreamManagerService.java
@@ -124,8 +124,10 @@ public final class DreamManagerService extends SystemService {
final boolean activityAllowed = activityType == ACTIVITY_TYPE_HOME
|| activityType == ACTIVITY_TYPE_DREAM
|| activityType == ACTIVITY_TYPE_ASSISTANT;
- if (mCurrentDreamToken != null && !mCurrentDreamIsWaking && !activityAllowed) {
- stopDreamInternal(false, "activity starting: " + activityInfo.name);
+ if (mCurrentDreamToken != null && !mCurrentDreamIsWaking
+ && !mCurrentDreamIsDozing && !activityAllowed) {
+ requestAwakenInternal(
+ "stopping dream due to activity start: " + activityInfo.name);
}
}
};
@@ -229,13 +231,13 @@ public final class DreamManagerService extends SystemService {
mPowerManager.nap(time);
}
- private void requestAwakenInternal() {
+ private void requestAwakenInternal(String reason) {
// Treat an explicit request to awaken as user activity so that the
// device doesn't immediately go to sleep if the timeout expired,
// for example when being undocked.
long time = SystemClock.uptimeMillis();
mPowerManager.userActivity(time, false /*noChangeLights*/);
- stopDreamInternal(false /*immediate*/, "request awaken");
+ stopDreamInternal(false /*immediate*/, reason);
}
private void finishSelfInternal(IBinder token, boolean immediate) {
@@ -715,7 +717,7 @@ public final class DreamManagerService extends SystemService {
final long ident = Binder.clearCallingIdentity();
try {
- requestAwakenInternal();
+ requestAwakenInternal("request awaken");
} finally {
Binder.restoreCallingIdentity(ident);
}
diff --git a/services/core/java/com/android/server/hdmi/HdmiCecLocalDeviceTv.java b/services/core/java/com/android/server/hdmi/HdmiCecLocalDeviceTv.java
index 1ea1457439ec..9bce471fd0cb 100644
--- a/services/core/java/com/android/server/hdmi/HdmiCecLocalDeviceTv.java
+++ b/services/core/java/com/android/server/hdmi/HdmiCecLocalDeviceTv.java
@@ -810,35 +810,24 @@ final class HdmiCecLocalDeviceTv extends HdmiCecLocalDevice {
}
}
- /**
- * Change ARC status into the given {@code enabled} status.
- *
- * @return {@code true} if ARC was in "Enabled" status
- */
@ServiceThreadOnly
- boolean setArcStatus(boolean enabled) {
+ void enableArc(List<byte[]> supportedSads) {
assertRunOnServiceThread();
+ HdmiLogger.debug("Set Arc Status[old:%b new:true]", mArcEstablished);
- HdmiLogger.debug("Set Arc Status[old:%b new:%b]", mArcEstablished, enabled);
- boolean oldStatus = mArcEstablished;
- if (enabled) {
- RequestSadAction action = new RequestSadAction(
- this, Constants.ADDR_AUDIO_SYSTEM,
- new RequestSadAction.RequestSadCallback() {
- @Override
- public void onRequestSadDone(List<byte[]> supportedSads) {
- enableAudioReturnChannel(enabled);
- notifyArcStatusToAudioService(enabled, supportedSads);
- mArcEstablished = enabled;
- }
- });
- addAndStartAction(action);
- } else {
- enableAudioReturnChannel(enabled);
- notifyArcStatusToAudioService(enabled, new ArrayList<>());
- mArcEstablished = enabled;
- }
- return oldStatus;
+ enableAudioReturnChannel(true);
+ notifyArcStatusToAudioService(true, supportedSads);
+ mArcEstablished = true;
+ }
+
+ @ServiceThreadOnly
+ void disableArc() {
+ assertRunOnServiceThread();
+ HdmiLogger.debug("Set Arc Status[old:%b new:false]", mArcEstablished);
+
+ enableAudioReturnChannel(false);
+ notifyArcStatusToAudioService(false, new ArrayList<>());
+ mArcEstablished = false;
}
/**
@@ -1066,7 +1055,7 @@ final class HdmiCecLocalDeviceTv extends HdmiCecLocalDevice {
protected int handleTerminateArc(HdmiCecMessage message) {
assertRunOnServiceThread();
if (mService .isPowerStandbyOrTransient()) {
- setArcStatus(false);
+ disableArc();
return Constants.HANDLED;
}
// Do not check ARC configuration since the AVR might have been already removed.
@@ -1353,7 +1342,7 @@ final class HdmiCecLocalDeviceTv extends HdmiCecLocalDevice {
if (avr == null) {
return;
}
- setArcStatus(false);
+ disableArc();
// Seq #44.
removeAllRunningArcAction();
diff --git a/services/core/java/com/android/server/hdmi/HdmiControlService.java b/services/core/java/com/android/server/hdmi/HdmiControlService.java
index 9824b4e6c43a..f8a74f4f3f55 100644
--- a/services/core/java/com/android/server/hdmi/HdmiControlService.java
+++ b/services/core/java/com/android/server/hdmi/HdmiControlService.java
@@ -4176,7 +4176,11 @@ public class HdmiControlService extends SystemService {
List<AudioDeviceAttributes> streamMusicDevices =
getAudioManager().getDevicesForAttributes(STREAM_MUSIC_ATTRIBUTES);
if (streamMusicDevices.contains(getAvcAudioOutputDevice())) {
- setStreamMusicVolume(volume, AudioManager.FLAG_ABSOLUTE_VOLUME);
+ int flags = AudioManager.FLAG_ABSOLUTE_VOLUME;
+ if (isTvDevice()) {
+ flags |= AudioManager.FLAG_SHOW_UI;
+ }
+ setStreamMusicVolume(volume, flags);
}
}
@@ -4190,8 +4194,11 @@ public class HdmiControlService extends SystemService {
getAudioManager().getDevicesForAttributes(STREAM_MUSIC_ATTRIBUTES);
if (streamMusicDevices.contains(getAvcAudioOutputDevice())) {
int direction = mute ? AudioManager.ADJUST_MUTE : AudioManager.ADJUST_UNMUTE;
- getAudioManager().adjustStreamVolume(AudioManager.STREAM_MUSIC, direction,
- AudioManager.FLAG_ABSOLUTE_VOLUME);
+ int flags = AudioManager.FLAG_ABSOLUTE_VOLUME;
+ if (isTvDevice()) {
+ flags |= AudioManager.FLAG_SHOW_UI;
+ }
+ getAudioManager().adjustStreamVolume(AudioManager.STREAM_MUSIC, direction, flags);
}
}
diff --git a/services/core/java/com/android/server/hdmi/RequestArcAction.java b/services/core/java/com/android/server/hdmi/RequestArcAction.java
index c70101c43d79..3d9a2905f4fb 100644
--- a/services/core/java/com/android/server/hdmi/RequestArcAction.java
+++ b/services/core/java/com/android/server/hdmi/RequestArcAction.java
@@ -63,7 +63,7 @@ abstract class RequestArcAction extends HdmiCecFeatureAction {
finish();
return true;
} else if (originalOpcode == Constants.MESSAGE_REQUEST_ARC_INITIATION) {
- tv().setArcStatus(false);
+ tv().disableArc();
finish();
return true;
}
diff --git a/services/core/java/com/android/server/hdmi/RequestArcInitiationAction.java b/services/core/java/com/android/server/hdmi/RequestArcInitiationAction.java
index 4eb220fd65ee..3b7f1dd0d971 100644
--- a/services/core/java/com/android/server/hdmi/RequestArcInitiationAction.java
+++ b/services/core/java/com/android/server/hdmi/RequestArcInitiationAction.java
@@ -48,7 +48,7 @@ final class RequestArcInitiationAction extends RequestArcAction {
public void onSendCompleted(int error) {
if (error != SendMessageResult.SUCCESS) {
// Turn off ARC status if <Request ARC Initiation> fails.
- tv().setArcStatus(false);
+ tv().disableArc();
finish();
}
}
diff --git a/services/core/java/com/android/server/hdmi/RequestSadAction.java b/services/core/java/com/android/server/hdmi/RequestSadAction.java
index 702c0004cb91..23aaf3260bac 100644
--- a/services/core/java/com/android/server/hdmi/RequestSadAction.java
+++ b/services/core/java/com/android/server/hdmi/RequestSadAction.java
@@ -181,13 +181,20 @@ final class RequestSadAction extends HdmiCecFeatureAction {
return true;
}
if (cmd.getOpcode() == Constants.MESSAGE_FEATURE_ABORT
- && (cmd.getParams()[0] & 0xFF) == Constants.MESSAGE_REQUEST_SHORT_AUDIO_DESCRIPTOR
- && (cmd.getParams()[1] & 0xFF) == Constants.ABORT_INVALID_OPERAND) {
- // Queried SADs are not supported
- mQueriedSadCount += MAX_SAD_PER_REQUEST;
- mTimeoutRetry = 0;
- querySad();
- return true;
+ && (cmd.getParams()[0] & 0xFF)
+ == Constants.MESSAGE_REQUEST_SHORT_AUDIO_DESCRIPTOR) {
+ if ((cmd.getParams()[1] & 0xFF) == Constants.ABORT_UNRECOGNIZED_OPCODE) {
+ // SAD feature is not supported
+ wrapUpAndFinish();
+ return true;
+ }
+ if ((cmd.getParams()[1] & 0xFF) == Constants.ABORT_INVALID_OPERAND) {
+ // Queried SADs are not supported
+ mQueriedSadCount += MAX_SAD_PER_REQUEST;
+ mTimeoutRetry = 0;
+ querySad();
+ return true;
+ }
}
return false;
}
@@ -211,9 +218,9 @@ final class RequestSadAction extends HdmiCecFeatureAction {
querySad();
return;
}
- mQueriedSadCount += MAX_SAD_PER_REQUEST;
- mTimeoutRetry = 0;
- querySad();
+ // Don't query any other SADs if one of the SAD queries ran into the maximum amount of
+ // retries.
+ wrapUpAndFinish();
}
}
diff --git a/services/core/java/com/android/server/hdmi/SetArcTransmissionStateAction.java b/services/core/java/com/android/server/hdmi/SetArcTransmissionStateAction.java
index db93ad0617ff..32e274ece9ab 100644
--- a/services/core/java/com/android/server/hdmi/SetArcTransmissionStateAction.java
+++ b/services/core/java/com/android/server/hdmi/SetArcTransmissionStateAction.java
@@ -20,6 +20,8 @@ import android.hardware.hdmi.HdmiDeviceInfo;
import android.hardware.tv.cec.V1_0.SendMessageResult;
import android.util.Slog;
+import java.util.List;
+
/**
* Feature action that handles enabling/disabling of ARC transmission channel.
* Once TV gets &lt;Initiate ARC&gt;, TV sends &lt;Report ARC Initiated&gt; to AV Receiver.
@@ -55,21 +57,31 @@ final class SetArcTransmissionStateAction extends HdmiCecFeatureAction {
boolean start() {
// Seq #37.
if (mEnabled) {
- // Enable ARC status immediately before sending <Report Arc Initiated>.
- // If AVR responds with <Feature Abort>, disable ARC status again.
- // This is different from spec that says that turns ARC status to
- // "Enabled" if <Report ARC Initiated> is acknowledged and no
- // <Feature Abort> is received.
- // But implemented this way to save the time having to wait for
- // <Feature Abort>.
- setArcStatus(true);
- // If succeeds to send <Report ARC Initiated>, wait general timeout
- // to check whether there is no <Feature Abort> for <Report ARC Initiated>.
- mState = STATE_WAITING_TIMEOUT;
- addTimer(mState, HdmiConfig.TIMEOUT_MS);
- sendReportArcInitiated();
+ // Request SADs before enabling ARC
+ RequestSadAction action = new RequestSadAction(
+ localDevice(), Constants.ADDR_AUDIO_SYSTEM,
+ new RequestSadAction.RequestSadCallback() {
+ @Override
+ public void onRequestSadDone(List<byte[]> supportedSads) {
+ // Enable ARC status immediately before sending <Report Arc Initiated>.
+ // If AVR responds with <Feature Abort>, disable ARC status again.
+ // This is different from spec that says that turns ARC status to
+ // "Enabled" if <Report ARC Initiated> is acknowledged and no
+ // <Feature Abort> is received.
+ // But implemented this way to save the time having to wait for
+ // <Feature Abort>.
+ Slog.i(TAG, "Enabling ARC");
+ tv().enableArc(supportedSads);
+ // If succeeds to send <Report ARC Initiated>, wait general timeout to
+ // check whether there is no <Feature Abort> for <Report ARC Initiated>.
+ mState = STATE_WAITING_TIMEOUT;
+ addTimer(mState, HdmiConfig.TIMEOUT_MS);
+ sendReportArcInitiated();
+ }
+ });
+ addAndStartAction(action);
} else {
- setArcStatus(false);
+ disableArc();
finish();
}
return true;
@@ -92,7 +104,7 @@ final class SetArcTransmissionStateAction extends HdmiCecFeatureAction {
case SendMessageResult.NACK:
// If <Report ARC Initiated> is negatively ack'ed, disable ARC and
// send <Report ARC Terminated> directly.
- setArcStatus(false);
+ disableArc();
HdmiLogger.debug("Failed to send <Report Arc Initiated>.");
finish();
break;
@@ -101,16 +113,12 @@ final class SetArcTransmissionStateAction extends HdmiCecFeatureAction {
});
}
- private void setArcStatus(boolean enabled) {
- tv().setArcStatus(enabled);
- Slog.i(TAG, "Change arc status to " + enabled);
+ private void disableArc() {
+ Slog.i(TAG, "Disabling ARC");
- // If enabled before and set to "disabled" and send <Report Arc Terminated> to
- // av reciever.
- if (!enabled) {
- sendCommand(HdmiCecMessageBuilder.buildReportArcTerminated(getSourceAddress(),
- mAvrAddress));
- }
+ tv().disableArc();
+ sendCommand(HdmiCecMessageBuilder.buildReportArcTerminated(getSourceAddress(),
+ mAvrAddress));
}
@Override
@@ -124,7 +132,7 @@ final class SetArcTransmissionStateAction extends HdmiCecFeatureAction {
int originalOpcode = cmd.getParams()[0] & 0xFF;
if (originalOpcode == Constants.MESSAGE_REPORT_ARC_INITIATED) {
HdmiLogger.debug("Feature aborted for <Report Arc Initiated>");
- setArcStatus(false);
+ disableArc();
finish();
return true;
}
diff --git a/services/core/java/com/android/server/location/gnss/GnssLocationProvider.java b/services/core/java/com/android/server/location/gnss/GnssLocationProvider.java
index ea99e7972887..f5c2bbc8d5a2 100644
--- a/services/core/java/com/android/server/location/gnss/GnssLocationProvider.java
+++ b/services/core/java/com/android/server/location/gnss/GnssLocationProvider.java
@@ -1587,6 +1587,7 @@ public class GnssLocationProvider extends AbstractLocationProvider implements
if (isGpsEnabled()) {
setGpsEnabled(false);
updateEnabled();
+ restartLocationRequest();
}
}
diff --git a/services/core/java/com/android/server/location/gnss/GnssNetworkConnectivityHandler.java b/services/core/java/com/android/server/location/gnss/GnssNetworkConnectivityHandler.java
index 718f98a0f04b..70b86898c24b 100644
--- a/services/core/java/com/android/server/location/gnss/GnssNetworkConnectivityHandler.java
+++ b/services/core/java/com/android/server/location/gnss/GnssNetworkConnectivityHandler.java
@@ -200,7 +200,7 @@ class GnssNetworkConnectivityHandler {
mHandler = new Handler(looper);
mNiHandler = niHandler;
mConnMgr = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
- mSuplConnectivityCallback = createSuplConnectivityCallback();
+ mSuplConnectivityCallback = null;
}
/**
@@ -584,11 +584,21 @@ class GnssNetworkConnectivityHandler {
networkRequestBuilder.setNetworkSpecifier(Integer.toString(mActiveSubId));
}
NetworkRequest networkRequest = networkRequestBuilder.build();
- mConnMgr.requestNetwork(
- networkRequest,
- mSuplConnectivityCallback,
- mHandler,
- SUPL_NETWORK_REQUEST_TIMEOUT_MILLIS);
+ // Make sure we only have a single request.
+ if (mSuplConnectivityCallback != null) {
+ mConnMgr.unregisterNetworkCallback(mSuplConnectivityCallback);
+ }
+ mSuplConnectivityCallback = createSuplConnectivityCallback();
+ try {
+ mConnMgr.requestNetwork(
+ networkRequest,
+ mSuplConnectivityCallback,
+ mHandler,
+ SUPL_NETWORK_REQUEST_TIMEOUT_MILLIS);
+ } catch (RuntimeException e) {
+ Log.e(TAG, "Failed to request network.", e);
+ handleReleaseSuplConnection(GPS_AGPS_DATA_CONN_FAILED);
+ }
}
private int getNetworkCapability(int agpsType) {
@@ -619,7 +629,10 @@ class GnssNetworkConnectivityHandler {
}
mAGpsDataConnectionState = AGPS_DATA_CONNECTION_CLOSED;
- mConnMgr.unregisterNetworkCallback(mSuplConnectivityCallback);
+ if (mSuplConnectivityCallback != null) {
+ mConnMgr.unregisterNetworkCallback(mSuplConnectivityCallback);
+ mSuplConnectivityCallback = null;
+ }
switch (agpsDataConnStatus) {
case GPS_AGPS_DATA_CONN_FAILED:
native_agps_data_conn_failed();
diff --git a/services/core/java/com/android/server/notification/NotificationManagerService.java b/services/core/java/com/android/server/notification/NotificationManagerService.java
index 3330211b0b92..0128366e1f2b 100755
--- a/services/core/java/com/android/server/notification/NotificationManagerService.java
+++ b/services/core/java/com/android/server/notification/NotificationManagerService.java
@@ -656,7 +656,6 @@ public class NotificationManagerService extends SystemService {
private int mWarnRemoteViewsSizeBytes;
private int mStripRemoteViewsSizeBytes;
- private boolean mForceUserSetOnUpgrade;
private MetricsLogger mMetricsLogger;
private NotificationChannelLogger mNotificationChannelLogger;
@@ -2284,6 +2283,7 @@ public class NotificationManagerService extends SystemService {
mNotificationChannelLogger,
mAppOps,
new SysUiStatsEvent.BuilderFactory());
+ mPreferencesHelper.updateFixedImportance(mUm.getUsers());
mRankingHelper = new RankingHelper(getContext(),
mRankingHandler,
mPreferencesHelper,
@@ -2471,9 +2471,6 @@ public class NotificationManagerService extends SystemService {
WorkerHandler handler = new WorkerHandler(Looper.myLooper());
- mForceUserSetOnUpgrade = getContext().getResources().getBoolean(
- R.bool.config_notificationForceUserSetOnUpgrade);
-
init(handler, new RankingHandlerWorker(mRankingThread.getLooper()),
AppGlobals.getPackageManager(), getContext().getPackageManager(),
getLocalService(LightsManager.class),
@@ -2502,8 +2499,7 @@ public class NotificationManagerService extends SystemService {
LocalServices.getService(ActivityManagerInternal.class),
createToastRateLimiter(), new PermissionHelper(LocalServices.getService(
PermissionManagerServiceInternal.class), AppGlobals.getPackageManager(),
- AppGlobals.getPermissionManager(),
- mForceUserSetOnUpgrade),
+ AppGlobals.getPermissionManager()),
LocalServices.getService(UsageStatsManagerInternal.class),
getContext().getSystemService(TelecomManager.class),
new NotificationChannelLoggerImpl());
@@ -3632,6 +3628,12 @@ public class NotificationManagerService extends SystemService {
}
@Override
+ public boolean isImportanceLocked(String pkg, int uid) {
+ checkCallerIsSystem();
+ return mPreferencesHelper.isImportanceLocked(pkg, uid);
+ }
+
+ @Override
public boolean canShowBadge(String pkg, int uid) {
checkCallerIsSystem();
return mPreferencesHelper.canShowBadge(pkg, uid);
@@ -6146,7 +6148,6 @@ public class NotificationManagerService extends SystemService {
pw.println(" mMaxPackageEnqueueRate=" + mMaxPackageEnqueueRate);
pw.println(" hideSilentStatusBar="
+ mPreferencesHelper.shouldHideSilentStatusIcons());
- pw.println(" mForceUserSetOnUpgrade=" + mForceUserSetOnUpgrade);
}
pw.println(" mArchive=" + mArchive.toString());
mArchive.dumpImpl(pw, filter);
diff --git a/services/core/java/com/android/server/notification/PermissionHelper.java b/services/core/java/com/android/server/notification/PermissionHelper.java
index b2fee1e8b545..09ed56745e54 100644
--- a/services/core/java/com/android/server/notification/PermissionHelper.java
+++ b/services/core/java/com/android/server/notification/PermissionHelper.java
@@ -16,7 +16,6 @@
package com.android.server.notification;
-import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
import static android.content.pm.PackageManager.GET_PERMISSIONS;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
@@ -55,14 +54,12 @@ public final class PermissionHelper {
private final PermissionManagerServiceInternal mPmi;
private final IPackageManager mPackageManager;
private final IPermissionManager mPermManager;
- private final boolean mForceUserSetOnUpgrade;
public PermissionHelper(PermissionManagerServiceInternal pmi, IPackageManager packageManager,
- IPermissionManager permManager, boolean forceUserSetOnUpgrade) {
+ IPermissionManager permManager) {
mPmi = pmi;
mPackageManager = packageManager;
mPermManager = permManager;
- mForceUserSetOnUpgrade = forceUserSetOnUpgrade;
}
/**
@@ -72,8 +69,7 @@ public final class PermissionHelper {
public boolean hasPermission(int uid) {
final long callingId = Binder.clearCallingIdentity();
try {
- return mPmi.checkPostNotificationsPermissionGrantedOrLegacyAccess(uid)
- == PERMISSION_GRANTED;
+ return mPmi.checkUidPermission(uid, NOTIFICATION_PERMISSION) == PERMISSION_GRANTED;
} finally {
Binder.restoreCallingIdentity(callingId);
}
@@ -153,21 +149,13 @@ public final class PermissionHelper {
}
/**
- * @see setNotificationPermission(String, int, boolean, boolean, boolean)
- */
- public void setNotificationPermission(String packageName, @UserIdInt int userId, boolean grant,
- boolean userSet) {
- setNotificationPermission(packageName, userId, grant, userSet, false);
- }
-
- /**
* Grants or revokes the notification permission for a given package/user. UserSet should
* only be true if this method is being called to migrate existing user choice, because it
* can prevent the user from seeing the in app permission dialog. Must not be called
* with a lock held.
*/
public void setNotificationPermission(String packageName, @UserIdInt int userId, boolean grant,
- boolean userSet, boolean reviewRequired) {
+ boolean userSet) {
final long callingId = Binder.clearCallingIdentity();
try {
// Do not change the permission if the package doesn't request it, do not change fixed
@@ -181,7 +169,7 @@ public final class PermissionHelper {
boolean currentlyGranted = mPmi.checkPermission(packageName, NOTIFICATION_PERMISSION,
userId) != PackageManager.PERMISSION_DENIED;
- if (grant && !reviewRequired && !currentlyGranted) {
+ if (grant && !currentlyGranted) {
mPermManager.grantRuntimePermission(packageName, NOTIFICATION_PERMISSION, userId);
} else if (!grant && currentlyGranted) {
mPermManager.revokeRuntimePermission(packageName, NOTIFICATION_PERMISSION,
@@ -189,12 +177,10 @@ public final class PermissionHelper {
}
if (userSet) {
mPermManager.updatePermissionFlags(packageName, NOTIFICATION_PERMISSION,
- FLAG_PERMISSION_USER_SET | FLAG_PERMISSION_REVIEW_REQUIRED,
- FLAG_PERMISSION_USER_SET, true, userId);
- } else if (reviewRequired) {
+ FLAG_PERMISSION_USER_SET, FLAG_PERMISSION_USER_SET, true, userId);
+ } else {
mPermManager.updatePermissionFlags(packageName, NOTIFICATION_PERMISSION,
- FLAG_PERMISSION_REVIEW_REQUIRED, FLAG_PERMISSION_REVIEW_REQUIRED, true,
- userId);
+ 0, FLAG_PERMISSION_USER_SET, true, userId);
}
} catch (RemoteException e) {
Slog.e(TAG, "Could not reach system server", e);
@@ -212,9 +198,8 @@ public final class PermissionHelper {
return;
}
if (!isPermissionFixed(pkgPerm.packageName, pkgPerm.userId)) {
- boolean userSet = mForceUserSetOnUpgrade ? true : pkgPerm.userModifiedSettings;
setNotificationPermission(pkgPerm.packageName, pkgPerm.userId, pkgPerm.granted,
- userSet, !userSet);
+ true /* userSet always true on upgrade */);
}
}
diff --git a/services/core/java/com/android/server/notification/PreferencesHelper.java b/services/core/java/com/android/server/notification/PreferencesHelper.java
index 4e3fbaa18870..97133a56779d 100644
--- a/services/core/java/com/android/server/notification/PreferencesHelper.java
+++ b/services/core/java/com/android/server/notification/PreferencesHelper.java
@@ -42,8 +42,10 @@ import android.app.NotificationChannelGroup;
import android.app.NotificationManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ParceledListSlice;
+import android.content.pm.UserInfo;
import android.metrics.LogMaker;
import android.os.Binder;
import android.os.Build;
@@ -146,7 +148,6 @@ public class PreferencesHelper implements RankingConfig {
static final boolean DEFAULT_HIDE_SILENT_STATUS_BAR_ICONS = false;
private static final boolean DEFAULT_SHOW_BADGE = true;
- private static final boolean DEFAULT_OEM_LOCKED_IMPORTANCE = false;
private static final boolean DEFAULT_APP_LOCKED_IMPORTANCE = false;
static final boolean DEFAULT_BUBBLES_ENABLED = true;
@@ -193,8 +194,6 @@ public class PreferencesHelper implements RankingConfig {
private boolean mAllowInvalidShortcuts = false;
- private Map<String, List<String>> mOemLockedApps = new HashMap();
-
public PreferencesHelper(Context context, PackageManager pm, RankingHandler rankingHandler,
ZenModeHelper zenHelper, PermissionHelper permHelper,
NotificationChannelLogger notificationChannelLogger,
@@ -411,7 +410,7 @@ public class PreferencesHelper implements RankingConfig {
channel.populateFromXml(parser);
}
channel.setImportanceLockedByCriticalDeviceFunction(
- r.defaultAppLockedImportance);
+ r.defaultAppLockedImportance || r.fixedImportance);
if (isShortcutOk(channel) && isDeletionOk(channel)) {
r.channels.put(id, channel);
@@ -484,14 +483,6 @@ public class PreferencesHelper implements RankingConfig {
r.visibility = visibility;
r.showBadge = showBadge;
r.bubblePreference = bubblePreference;
- if (mOemLockedApps.containsKey(r.pkg)) {
- List<String> channels = mOemLockedApps.get(r.pkg);
- if (channels == null || channels.isEmpty()) {
- r.oemLockedImportance = true;
- } else {
- r.oemLockedChannels = channels;
- }
- }
try {
createDefaultChannelIfNeededLocked(r);
@@ -818,6 +809,13 @@ public class PreferencesHelper implements RankingConfig {
}
}
+ boolean isImportanceLocked(String pkg, int uid) {
+ synchronized (mPackagePreferences) {
+ PackagePreferences r = getOrCreatePackagePreferencesLocked(pkg, uid);
+ return r.fixedImportance || r.defaultAppLockedImportance;
+ }
+ }
+
@Override
public boolean isGroupBlocked(String packageName, int uid, String groupId) {
if (groupId == null) {
@@ -1008,7 +1006,7 @@ public class PreferencesHelper implements RankingConfig {
clearLockedFieldsLocked(channel);
channel.setImportanceLockedByCriticalDeviceFunction(
- r.defaultAppLockedImportance);
+ r.defaultAppLockedImportance || r.fixedImportance);
if (channel.getLockscreenVisibility() == Notification.VISIBILITY_PUBLIC) {
channel.setLockscreenVisibility(
@@ -1090,8 +1088,7 @@ public class PreferencesHelper implements RankingConfig {
updatedChannel.unlockFields(updatedChannel.getUserLockedFields());
}
- if ((mPermissionHelper.isPermissionFixed(r.pkg, UserHandle.getUserId(r.uid))
- || channel.isImportanceLockedByCriticalDeviceFunction())
+ if (channel.isImportanceLockedByCriticalDeviceFunction()
&& !(channel.isBlockable() || channel.getImportance() == IMPORTANCE_NONE)) {
updatedChannel.setImportance(channel.getImportance());
}
@@ -1267,6 +1264,28 @@ public class PreferencesHelper implements RankingConfig {
mHideSilentStatusBarIcons = hide;
}
+ public void updateFixedImportance(List<UserInfo> users) {
+ for (UserInfo user : users) {
+ List<PackageInfo> packages = mPm.getInstalledPackagesAsUser(
+ PackageManager.PackageInfoFlags.of(PackageManager.MATCH_SYSTEM_ONLY),
+ user.getUserHandle().getIdentifier());
+ for (PackageInfo pi : packages) {
+ boolean fixed = mPermissionHelper.isPermissionFixed(
+ pi.packageName, user.getUserHandle().getIdentifier());
+ if (fixed) {
+ synchronized (mPackagePreferences) {
+ PackagePreferences p = getOrCreatePackagePreferencesLocked(
+ pi.packageName, pi.applicationInfo.uid);
+ p.fixedImportance = true;
+ for (NotificationChannel channel : p.channels.values()) {
+ channel.setImportanceLockedByCriticalDeviceFunction(true);
+ }
+ }
+ }
+ }
+ }
+ }
+
public void updateDefaultApps(int userId, ArraySet<String> toRemove,
ArraySet<Pair<String, Integer>> toAdd) {
synchronized (mPackagePreferences) {
@@ -1274,8 +1293,10 @@ public class PreferencesHelper implements RankingConfig {
if (userId == UserHandle.getUserId(p.uid)) {
if (toRemove != null && toRemove.contains(p.pkg)) {
p.defaultAppLockedImportance = false;
- for (NotificationChannel channel : p.channels.values()) {
- channel.setImportanceLockedByCriticalDeviceFunction(false);
+ if (!p.fixedImportance) {
+ for (NotificationChannel channel : p.channels.values()) {
+ channel.setImportanceLockedByCriticalDeviceFunction(false);
+ }
}
}
}
@@ -1934,13 +1955,9 @@ public class PreferencesHelper implements RankingConfig {
pw.print(" defaultAppLocked=");
pw.print(r.defaultAppLockedImportance);
}
- if (r.oemLockedImportance != DEFAULT_OEM_LOCKED_IMPORTANCE) {
- pw.print(" oemLocked=");
- pw.print(r.oemLockedImportance);
- }
- if (!r.oemLockedChannels.isEmpty()) {
- pw.print(" futureLockedChannels=");
- pw.print(r.oemLockedChannels);
+ if (r.fixedImportance != DEFAULT_APP_LOCKED_IMPORTANCE) {
+ pw.print(" fixedImportance=");
+ pw.print(r.fixedImportance);
}
pw.println();
for (NotificationChannel channel : r.channels.values()) {
@@ -2682,9 +2699,8 @@ public class PreferencesHelper implements RankingConfig {
int lockedAppFields = DEFAULT_LOCKED_APP_FIELDS;
// these fields are loaded on boot from a different source of truth and so are not
// written to notification policy xml
- boolean oemLockedImportance = DEFAULT_OEM_LOCKED_IMPORTANCE;
- List<String> oemLockedChannels = new ArrayList<>();
boolean defaultAppLockedImportance = DEFAULT_APP_LOCKED_IMPORTANCE;
+ boolean fixedImportance = DEFAULT_APP_LOCKED_IMPORTANCE;
boolean hasSentInvalidMessage = false;
boolean hasSentValidMessage = false;
diff --git a/services/core/java/com/android/server/pm/ApexManager.java b/services/core/java/com/android/server/pm/ApexManager.java
index beca71486899..1a6155b43f6b 100644
--- a/services/core/java/com/android/server/pm/ApexManager.java
+++ b/services/core/java/com/android/server/pm/ApexManager.java
@@ -121,17 +121,19 @@ public abstract class ApexManager {
public final File apexDirectory;
public final File preInstalledApexPath;
public final File apexFile;
+ public final boolean activeApexChanged;
private ActiveApexInfo(File apexDirectory, File preInstalledApexPath, File apexFile) {
- this(null, apexDirectory, preInstalledApexPath, apexFile);
+ this(null, apexDirectory, preInstalledApexPath, apexFile, false);
}
private ActiveApexInfo(@Nullable String apexModuleName, File apexDirectory,
- File preInstalledApexPath, File apexFile) {
+ File preInstalledApexPath, File apexFile, boolean activeApexChanged) {
this.apexModuleName = apexModuleName;
this.apexDirectory = apexDirectory;
this.preInstalledApexPath = preInstalledApexPath;
this.apexFile = apexFile;
+ this.activeApexChanged = activeApexChanged;
}
private ActiveApexInfo(ApexInfo apexInfo) {
@@ -140,7 +142,8 @@ public abstract class ApexManager {
new File(Environment.getApexDirectory() + File.separator
+ apexInfo.moduleName),
new File(apexInfo.preinstalledModulePath),
- new File(apexInfo.modulePath));
+ new File(apexInfo.modulePath),
+ apexInfo.activeApexChanged);
}
}
diff --git a/services/core/java/com/android/server/pm/BackgroundDexOptService.java b/services/core/java/com/android/server/pm/BackgroundDexOptService.java
index d26a1ac4fba0..5a01ccbb7d6f 100644
--- a/services/core/java/com/android/server/pm/BackgroundDexOptService.java
+++ b/services/core/java/com/android/server/pm/BackgroundDexOptService.java
@@ -17,6 +17,7 @@
package com.android.server.pm;
import static com.android.server.pm.PackageManagerService.PLATFORM_PACKAGE_NAME;
+import static com.android.server.pm.dex.ArtStatsLogUtils.BackgroundDexoptJobStatsLogger;
import android.annotation.IntDef;
import android.annotation.NonNull;
@@ -77,43 +78,46 @@ public final class BackgroundDexOptService {
private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
- @VisibleForTesting
- static final int JOB_IDLE_OPTIMIZE = 800;
- @VisibleForTesting
- static final int JOB_POST_BOOT_UPDATE = 801;
+ @VisibleForTesting static final int JOB_IDLE_OPTIMIZE = 800;
+ @VisibleForTesting static final int JOB_POST_BOOT_UPDATE = 801;
private static final long IDLE_OPTIMIZATION_PERIOD = TimeUnit.DAYS.toMillis(1);
private static final long CANCELLATION_WAIT_CHECK_INTERVAL_MS = 200;
- private static ComponentName sDexoptServiceName = new ComponentName("android",
- BackgroundDexOptJobService.class.getName());
+ private static ComponentName sDexoptServiceName =
+ new ComponentName("android", BackgroundDexOptJobService.class.getName());
// Possible return codes of individual optimization steps.
/** Ok status: Optimizations finished, All packages were processed, can continue */
- private static final int STATUS_OK = 0;
+ public static final int STATUS_OK = 0;
/** Optimizations should be aborted. Job scheduler requested it. */
- private static final int STATUS_ABORT_BY_CANCELLATION = 1;
+ public static final int STATUS_ABORT_BY_CANCELLATION = 1;
/** Optimizations should be aborted. No space left on device. */
- private static final int STATUS_ABORT_NO_SPACE_LEFT = 2;
+ public static final int STATUS_ABORT_NO_SPACE_LEFT = 2;
/** Optimizations should be aborted. Thermal throttling level too high. */
- private static final int STATUS_ABORT_THERMAL = 3;
+ public static final int STATUS_ABORT_THERMAL = 3;
/** Battery level too low */
- private static final int STATUS_ABORT_BATTERY = 4;
- /** {@link PackageDexOptimizer#DEX_OPT_FAILED} case */
- private static final int STATUS_DEX_OPT_FAILED = 5;
-
- @IntDef(prefix = {"STATUS_"}, value = {
- STATUS_OK,
- STATUS_ABORT_BY_CANCELLATION,
- STATUS_ABORT_NO_SPACE_LEFT,
- STATUS_ABORT_THERMAL,
- STATUS_ABORT_BATTERY,
- STATUS_DEX_OPT_FAILED,
- })
+ public static final int STATUS_ABORT_BATTERY = 4;
+ /**
+ * {@link PackageDexOptimizer#DEX_OPT_FAILED} case. This state means some packages have failed
+ * compilation during the job. Note that the failure will not be permanent as the next dexopt
+ * job will exclude those failed packages.
+ */
+ public static final int STATUS_DEX_OPT_FAILED = 5;
+
+ @IntDef(prefix = {"STATUS_"},
+ value =
+ {
+ STATUS_OK,
+ STATUS_ABORT_BY_CANCELLATION,
+ STATUS_ABORT_NO_SPACE_LEFT,
+ STATUS_ABORT_THERMAL,
+ STATUS_ABORT_BATTERY,
+ STATUS_DEX_OPT_FAILED,
+ })
@Retention(RetentionPolicy.SOURCE)
- private @interface Status {
- }
+ public @interface Status {}
// Used for calculating space threshold for downgrading unused apps.
private static final int LOW_THRESHOLD_MULTIPLIER_FOR_DOWNGRADE = 2;
@@ -125,33 +129,30 @@ public final class BackgroundDexOptService {
private final DexOptHelper mDexOptHelper;
+ private final BackgroundDexoptJobStatsLogger mStatsLogger =
+ new BackgroundDexoptJobStatsLogger();
+
private final Object mLock = new Object();
// Thread currently running dexopt. This will be null if dexopt is not running.
// The thread running dexopt make sure to set this into null when the pending dexopt is
// completed.
- @GuardedBy("mLock")
- @Nullable
- private Thread mDexOptThread;
+ @GuardedBy("mLock") @Nullable private Thread mDexOptThread;
// Thread currently cancelling dexopt. This thread is in blocked wait state until
// cancellation is done. Only this thread can change states for control. The other threads, if
// need to wait for cancellation, should just wait without doing any control.
- @GuardedBy("mLock")
- @Nullable
- private Thread mDexOptCancellingThread;
+ @GuardedBy("mLock") @Nullable private Thread mDexOptCancellingThread;
// Tells whether post boot update is completed or not.
- @GuardedBy("mLock")
- private boolean mFinishedPostBootUpdate;
+ @GuardedBy("mLock") private boolean mFinishedPostBootUpdate;
- @GuardedBy("mLock")
- @Status private int mLastExecutionStatus = STATUS_OK;
+ @GuardedBy("mLock") @Status private int mLastExecutionStatus = STATUS_OK;
- @GuardedBy("mLock")
- private long mLastExecutionStartTimeMs;
- @GuardedBy("mLock")
- private long mLastExecutionDurationMs;
+ @GuardedBy("mLock") private long mLastExecutionStartTimeMs;
+ @GuardedBy("mLock") private long mLastExecutionDurationIncludingSleepMs;
+ @GuardedBy("mLock") private long mLastExecutionStartUptimeMs;
+ @GuardedBy("mLock") private long mLastExecutionDurationMs;
// Keeps packages cancelled from PDO for last session. This is for debugging.
@GuardedBy("mLock")
@@ -177,8 +178,8 @@ public final class BackgroundDexOptService {
void onPackagesUpdated(ArraySet<String> updatedPackages);
}
- public BackgroundDexOptService(Context context, DexManager dexManager,
- PackageManagerService pm) {
+ public BackgroundDexOptService(
+ Context context, DexManager dexManager, PackageManagerService pm) {
this(new Injector(context, dexManager, pm));
}
@@ -230,6 +231,10 @@ public final class BackgroundDexOptService {
writer.println(mLastExecutionStatus);
writer.print("mLastExecutionStartTimeMs:");
writer.println(mLastExecutionStartTimeMs);
+ writer.print("mLastExecutionDurationIncludingSleepMs:");
+ writer.println(mLastExecutionDurationIncludingSleepMs);
+ writer.print("mLastExecutionStartUptimeMs:");
+ writer.println(mLastExecutionStartUptimeMs);
writer.print("mLastExecutionDurationMs:");
writer.println(mLastExecutionDurationMs);
writer.print("now:");
@@ -357,17 +362,20 @@ public final class BackgroundDexOptService {
resetStatesForNewDexOptRunLocked(mInjector.createAndStartThread(
"BackgroundDexOptService_" + (isPostBootUpdateJob ? "PostBoot" : "Idle"),
() -> {
- TimingsTraceAndSlog tr = new TimingsTraceAndSlog(TAG,
- Trace.TRACE_TAG_PACKAGE_MANAGER);
+ TimingsTraceAndSlog tr =
+ new TimingsTraceAndSlog(TAG, Trace.TRACE_TAG_PACKAGE_MANAGER);
tr.traceBegin("jobExecution");
boolean completed = false;
try {
- completed = runIdleOptimization(pm, pkgs,
- params.getJobId() == JOB_POST_BOOT_UPDATE);
+ completed = runIdleOptimization(
+ pm, pkgs, params.getJobId() == JOB_POST_BOOT_UPDATE);
} finally { // Those cleanup should be done always.
tr.traceEnd();
- Slog.i(TAG, "dexopt finishing. jobid:" + params.getJobId()
- + " completed:" + completed);
+ Slog.i(TAG,
+ "dexopt finishing. jobid:" + params.getJobId()
+ + " completed:" + completed);
+
+ writeStatsLog(params);
if (params.getJobId() == JOB_POST_BOOT_UPDATE) {
if (completed) {
@@ -451,7 +459,7 @@ public final class BackgroundDexOptService {
if (mDexOptThread != Thread.currentThread()) {
throw new IllegalStateException(
"Only mDexOptThread can mark completion, mDexOptThread:" + mDexOptThread
- + " current:" + Thread.currentThread());
+ + " current:" + Thread.currentThread());
}
mDexOptThread = null;
// Other threads may be waiting for completion.
@@ -481,11 +489,10 @@ public final class BackgroundDexOptService {
private void scheduleAJob(int jobId) {
JobScheduler js = mInjector.getJobScheduler();
- JobInfo.Builder builder = new JobInfo.Builder(jobId, sDexoptServiceName)
- .setRequiresDeviceIdle(true);
+ JobInfo.Builder builder =
+ new JobInfo.Builder(jobId, sDexoptServiceName).setRequiresDeviceIdle(true);
if (jobId == JOB_IDLE_OPTIMIZE) {
- builder.setRequiresCharging(true)
- .setPeriodic(IDLE_OPTIMIZATION_PERIOD);
+ builder.setRequiresCharging(true).setPeriodic(IDLE_OPTIMIZATION_PERIOD);
}
js.schedule(builder.build());
}
@@ -525,30 +532,36 @@ public final class BackgroundDexOptService {
}
}
- /** Returns true if completed */
- private boolean runIdleOptimization(PackageManagerService pm, List<String> pkgs,
- boolean isPostBootUpdate) {
+ /**
+ * Returns whether we've successfully run the job. Note that it will return true even if some
+ * packages may have failed compiling.
+ */
+ private boolean runIdleOptimization(
+ PackageManagerService pm, List<String> pkgs, boolean isPostBootUpdate) {
synchronized (mLock) {
mLastExecutionStartTimeMs = SystemClock.elapsedRealtime();
+ mLastExecutionDurationIncludingSleepMs = -1;
+ mLastExecutionStartUptimeMs = SystemClock.uptimeMillis();
mLastExecutionDurationMs = -1;
}
long lowStorageThreshold = getLowStorageThreshold();
- int status = idleOptimizePackages(pm, pkgs, lowStorageThreshold,
- isPostBootUpdate);
+ int status = idleOptimizePackages(pm, pkgs, lowStorageThreshold, isPostBootUpdate);
logStatus(status);
synchronized (mLock) {
mLastExecutionStatus = status;
- mLastExecutionDurationMs = SystemClock.elapsedRealtime() - mLastExecutionStartTimeMs;
+ mLastExecutionDurationIncludingSleepMs =
+ SystemClock.elapsedRealtime() - mLastExecutionStartTimeMs;
+ mLastExecutionDurationMs = SystemClock.uptimeMillis() - mLastExecutionStartUptimeMs;
}
- return status == STATUS_OK;
+ return status == STATUS_OK || status == STATUS_DEX_OPT_FAILED;
}
/** Gets the size of the directory. It uses recursion to go over all files. */
private long getDirectorySize(File f) {
long size = 0;
if (f.isDirectory()) {
- for (File file: f.listFiles()) {
+ for (File file : f.listFiles()) {
size += getDirectorySize(file);
}
} else {
@@ -599,8 +612,8 @@ public final class BackgroundDexOptService {
// Only downgrade apps when space is low on device.
// Threshold is selected above the lowStorageThreshold so that we can pro-actively clean
// up disk before user hits the actual lowStorageThreshold.
- long lowStorageThresholdForDowngrade = LOW_THRESHOLD_MULTIPLIER_FOR_DOWNGRADE
- * lowStorageThreshold;
+ long lowStorageThresholdForDowngrade =
+ LOW_THRESHOLD_MULTIPLIER_FOR_DOWNGRADE * lowStorageThreshold;
boolean shouldDowngrade = shouldDowngrade(lowStorageThresholdForDowngrade);
if (DEBUG) {
Slog.d(TAG, "Should Downgrade " + shouldDowngrade);
@@ -620,19 +633,20 @@ public final class BackgroundDexOptService {
// Should be aborted by the scheduler.
return abortCode;
}
- @DexOptResult int downgradeResult = downgradePackage(snapshot, pm, pkg,
+ @DexOptResult
+ int downgradeResult = downgradePackage(snapshot, pm, pkg,
/* isForPrimaryDex= */ true, isPostBootUpdate);
if (downgradeResult == PackageDexOptimizer.DEX_OPT_PERFORMED) {
updatedPackages.add(pkg);
}
- @Status int status = convertPackageDexOptimizerStatusToInternal(
- downgradeResult);
+ @Status
+ int status = convertPackageDexOptimizerStatusToInternal(downgradeResult);
if (status != STATUS_OK) {
return status;
}
if (supportSecondaryDex) {
downgradeResult = downgradePackage(snapshot, pm, pkg,
- /* isForPrimaryDex= */false, isPostBootUpdate);
+ /* isForPrimaryDex= */ false, isPostBootUpdate);
status = convertPackageDexOptimizerStatusToInternal(downgradeResult);
if (status != STATUS_OK) {
return status;
@@ -661,6 +675,11 @@ public final class BackgroundDexOptService {
ArraySet<String> updatedPackages, boolean isPostBootUpdate) {
boolean supportSecondaryDex = mInjector.supportSecondaryDex();
+ // Keep the error if there is any error from any package.
+ @Status int status = STATUS_OK;
+
+ // Other than cancellation, all packages will be processed even if an error happens
+ // in a package.
for (String pkg : pkgs) {
int abortCode = abortIdleOptimizations(lowStorageThreshold);
if (abortCode != STATUS_OK) {
@@ -668,26 +687,32 @@ public final class BackgroundDexOptService {
return abortCode;
}
- @DexOptResult int primaryResult =
- optimizePackage(pkg, true /* isForPrimaryDex */, isPostBootUpdate);
+ @DexOptResult
+ int primaryResult = optimizePackage(pkg, true /* isForPrimaryDex */, isPostBootUpdate);
+ if (primaryResult == PackageDexOptimizer.DEX_OPT_CANCELLED) {
+ return STATUS_ABORT_BY_CANCELLATION;
+ }
if (primaryResult == PackageDexOptimizer.DEX_OPT_PERFORMED) {
updatedPackages.add(pkg);
- } else if (primaryResult != PackageDexOptimizer.DEX_OPT_SKIPPED) {
- return convertPackageDexOptimizerStatusToInternal(primaryResult);
+ } else if (primaryResult == PackageDexOptimizer.DEX_OPT_FAILED) {
+ status = convertPackageDexOptimizerStatusToInternal(primaryResult);
}
if (!supportSecondaryDex) {
continue;
}
- @DexOptResult int secondaryResult =
+ @DexOptResult
+ int secondaryResult =
optimizePackage(pkg, false /* isForPrimaryDex */, isPostBootUpdate);
- if (secondaryResult != PackageDexOptimizer.DEX_OPT_PERFORMED
- && secondaryResult != PackageDexOptimizer.DEX_OPT_SKIPPED) {
- return convertPackageDexOptimizerStatusToInternal(secondaryResult);
+ if (secondaryResult == PackageDexOptimizer.DEX_OPT_CANCELLED) {
+ return STATUS_ABORT_BY_CANCELLATION;
+ }
+ if (secondaryResult == PackageDexOptimizer.DEX_OPT_FAILED) {
+ status = convertPackageDexOptimizerStatusToInternal(secondaryResult);
}
}
- return STATUS_OK;
+ return status;
}
/**
@@ -731,7 +756,7 @@ public final class BackgroundDexOptService {
if (result == PackageDexOptimizer.DEX_OPT_PERFORMED) {
final Computer newSnapshot = pm.snapshotComputer();
FrameworkStatsLog.write(FrameworkStatsLog.APP_DOWNGRADED, pkg, package_size_before,
- getPackageSize(newSnapshot, pkg), /*aggressive=*/ false);
+ getPackageSize(newSnapshot, pkg), /*aggressive=*/false);
}
return result;
}
@@ -760,7 +785,7 @@ public final class BackgroundDexOptService {
@DexOptResult
private int optimizePackage(String pkg, boolean isForPrimaryDex, boolean isPostBootUpdate) {
int reason = isPostBootUpdate ? PackageManagerService.REASON_POST_BOOT
- : PackageManagerService.REASON_BACKGROUND_DEXOPT;
+ : PackageManagerService.REASON_BACKGROUND_DEXOPT;
int dexoptFlags = DexoptOptions.DEXOPT_BOOT_COMPLETE;
if (!isPostBootUpdate) {
dexoptFlags |= DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES
@@ -777,22 +802,21 @@ public final class BackgroundDexOptService {
}
@DexOptResult
- private int performDexOptPrimary(String pkg, int reason,
- int dexoptFlags) {
- return trackPerformDexOpt(pkg, /*isForPrimaryDex=*/ true,
- () -> mDexOptHelper.performDexOptWithStatus(
- new DexoptOptions(pkg, reason, dexoptFlags)));
+ private int performDexOptPrimary(String pkg, int reason, int dexoptFlags) {
+ DexoptOptions dexoptOptions = new DexoptOptions(pkg, reason, dexoptFlags);
+ return trackPerformDexOpt(pkg, /*isForPrimaryDex=*/true,
+ () -> mDexOptHelper.performDexOptWithStatus(dexoptOptions));
}
@DexOptResult
- private int performDexOptSecondary(String pkg, int reason,
- int dexoptFlags) {
- DexoptOptions dexoptOptions = new DexoptOptions(pkg, reason,
- dexoptFlags | DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX);
- return trackPerformDexOpt(pkg, /*isForPrimaryDex=*/ false,
- () -> mDexOptHelper.performDexOpt(dexoptOptions)
- ? PackageDexOptimizer.DEX_OPT_PERFORMED : PackageDexOptimizer.DEX_OPT_FAILED
- );
+ private int performDexOptSecondary(String pkg, int reason, int dexoptFlags) {
+ DexoptOptions dexoptOptions = new DexoptOptions(
+ pkg, reason, dexoptFlags | DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX);
+ return trackPerformDexOpt(pkg, /*isForPrimaryDex=*/false,
+ ()
+ -> mDexOptHelper.performDexOpt(dexoptOptions)
+ ? PackageDexOptimizer.DEX_OPT_PERFORMED
+ : PackageDexOptimizer.DEX_OPT_FAILED);
}
/**
@@ -805,8 +829,8 @@ public final class BackgroundDexOptService {
* {@link PackageDexOptimizer#DEX_OPT_FAILED}
*/
@DexOptResult
- private int trackPerformDexOpt(String pkg, boolean isForPrimaryDex,
- Supplier<Integer> performDexOptWrapper) {
+ private int trackPerformDexOpt(
+ String pkg, boolean isForPrimaryDex, Supplier<Integer> performDexOptWrapper) {
ArraySet<String> failedPackageNames;
synchronized (mLock) {
failedPackageNames =
@@ -923,6 +947,19 @@ public final class BackgroundDexOptService {
}
}
+ private void writeStatsLog(JobParameters params) {
+ @Status int status;
+ long durationMs;
+ long durationIncludingSleepMs;
+ synchronized (mLock) {
+ status = mLastExecutionStatus;
+ durationMs = mLastExecutionDurationMs;
+ durationIncludingSleepMs = mLastExecutionDurationIncludingSleepMs;
+ }
+
+ mStatsLogger.write(status, params.getStopReason(), durationMs, durationIncludingSleepMs);
+ }
+
/** Injector pattern for testing purpose */
@VisibleForTesting
static final class Injector {
@@ -962,8 +999,8 @@ public final class BackgroundDexOptService {
}
boolean isBackgroundDexOptDisabled() {
- return SystemProperties.getBoolean("pm.dexopt.disable_bg_dexopt" /* key */,
- false /* default */);
+ return SystemProperties.getBoolean(
+ "pm.dexopt.disable_bg_dexopt" /* key */, false /* default */);
}
boolean isBatteryLevelLow() {
@@ -993,8 +1030,8 @@ public final class BackgroundDexOptService {
}
int getCurrentThermalStatus() {
- IThermalService thermalService = IThermalService.Stub
- .asInterface(ServiceManager.getService(Context.THERMAL_SERVICE));
+ IThermalService thermalService = IThermalService.Stub.asInterface(
+ ServiceManager.getService(Context.THERMAL_SERVICE));
try {
return thermalService.getCurrentThermalStatus();
} catch (RemoteException e) {
@@ -1003,8 +1040,8 @@ public final class BackgroundDexOptService {
}
int getDexOptThermalCutoff() {
- return SystemProperties.getInt("dalvik.vm.dexopt.thermal-cutoff",
- THERMAL_CUTOFF_DEFAULT);
+ return SystemProperties.getInt(
+ "dalvik.vm.dexopt.thermal-cutoff", THERMAL_CUTOFF_DEFAULT);
}
Thread createAndStartThread(String name, Runnable target) {
diff --git a/services/core/java/com/android/server/pm/BroadcastHelper.java b/services/core/java/com/android/server/pm/BroadcastHelper.java
index ed71f1eb5313..9d1f0704a3cf 100644
--- a/services/core/java/com/android/server/pm/BroadcastHelper.java
+++ b/services/core/java/com/android/server/pm/BroadcastHelper.java
@@ -197,7 +197,7 @@ public final class BroadcastHelper {
final BroadcastOptions bOptions = getTemporaryAppAllowlistBroadcastOptions(
REASON_LOCKED_BOOT_COMPLETED);
am.broadcastIntentWithFeature(null, null, lockedBcIntent, null, null, 0, null, null,
- requiredPermissions, null, android.app.AppOpsManager.OP_NONE,
+ requiredPermissions, null, null, android.app.AppOpsManager.OP_NONE,
bOptions.toBundle(), false, false, userId);
// Deliver BOOT_COMPLETED only if user is unlocked
@@ -207,7 +207,7 @@ public final class BroadcastHelper {
bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
}
am.broadcastIntentWithFeature(null, null, bcIntent, null, null, 0, null, null,
- requiredPermissions, null, android.app.AppOpsManager.OP_NONE,
+ requiredPermissions, null, null, android.app.AppOpsManager.OP_NONE,
bOptions.toBundle(), false, false, userId);
}
} catch (RemoteException e) {
@@ -263,7 +263,7 @@ public final class BroadcastHelper {
};
try {
am.broadcastIntentWithFeature(null, null, intent, null, null, 0, null, null,
- requiredPermissions, null, android.app.AppOpsManager.OP_NONE, null, false,
+ requiredPermissions, null, null, android.app.AppOpsManager.OP_NONE, null, false,
false, UserHandle.USER_ALL);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
@@ -301,7 +301,7 @@ public final class BroadcastHelper {
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
try {
am.broadcastIntentWithFeature(null, null, intent, null, null,
- 0, null, null, null, null, android.app.AppOpsManager.OP_NONE,
+ 0, null, null, null, null, null, android.app.AppOpsManager.OP_NONE,
null, false, false, userId);
} catch (RemoteException e) {
}
diff --git a/services/core/java/com/android/server/pm/Computer.java b/services/core/java/com/android/server/pm/Computer.java
index db48a1f63099..eb635500580a 100644
--- a/services/core/java/com/android/server/pm/Computer.java
+++ b/services/core/java/com/android/server/pm/Computer.java
@@ -94,12 +94,13 @@ import java.util.Set;
@VisibleForTesting(visibility = VisibleForTesting.Visibility.PRIVATE)
public interface Computer extends PackageDataSnapshot {
+ int getVersion();
+
/**
* Administrative statistics: record that the snapshot has been used. Every call
* to use() increments the usage counter.
*/
- default void use() {
- }
+ Computer use();
/**
* Fetch the snapshot usage counter.
* @return The number of times this snapshot was used.
diff --git a/services/core/java/com/android/server/pm/ComputerEngine.java b/services/core/java/com/android/server/pm/ComputerEngine.java
index bf9f4fa8a211..f3c41af05da3 100644
--- a/services/core/java/com/android/server/pm/ComputerEngine.java
+++ b/services/core/java/com/android/server/pm/ComputerEngine.java
@@ -367,6 +367,8 @@ public class ComputerEngine implements Computer {
return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
};
+ private final int mVersion;
+
// The administrative use counter.
private int mUsed = 0;
@@ -424,7 +426,8 @@ public class ComputerEngine implements Computer {
return mLocalAndroidApplication;
}
- ComputerEngine(PackageManagerService.Snapshot args) {
+ ComputerEngine(PackageManagerService.Snapshot args, int version) {
+ mVersion = version;
mSettings = new Settings(args.settings);
mIsolatedOwners = args.isolatedOwners;
mPackages = args.packages;
@@ -464,11 +467,17 @@ public class ComputerEngine implements Computer {
mService = args.service;
}
+ @Override
+ public int getVersion() {
+ return mVersion;
+ }
+
/**
* Record that the snapshot was used.
*/
- public final void use() {
+ public final Computer use() {
mUsed++;
+ return this;
}
/**
diff --git a/services/core/java/com/android/server/pm/ComputerLocked.java b/services/core/java/com/android/server/pm/ComputerLocked.java
index af196d51331f..37070dbe7131 100644
--- a/services/core/java/com/android/server/pm/ComputerLocked.java
+++ b/services/core/java/com/android/server/pm/ComputerLocked.java
@@ -30,7 +30,7 @@ import com.android.internal.annotations.VisibleForTesting;
public final class ComputerLocked extends ComputerEngine {
ComputerLocked(PackageManagerService.Snapshot args) {
- super(args);
+ super(args, -1);
}
protected ComponentName resolveComponentName() {
diff --git a/services/core/java/com/android/server/pm/DeletePackageHelper.java b/services/core/java/com/android/server/pm/DeletePackageHelper.java
index cb38d522f3bd..0cdf7bf62f55 100644
--- a/services/core/java/com/android/server/pm/DeletePackageHelper.java
+++ b/services/core/java/com/android/server/pm/DeletePackageHelper.java
@@ -166,9 +166,10 @@ final class DeletePackageHelper {
if (PackageManagerServiceUtils.isSystemApp(uninstalledPs)) {
UserInfo userInfo = mUserManagerInternal.getUserInfo(userId);
- if (userInfo == null || !userInfo.isAdmin()) {
+ if (userInfo == null || (!userInfo.isAdmin() && !mUserManagerInternal.getUserInfo(
+ mUserManagerInternal.getProfileParentId(userId)).isAdmin())) {
Slog.w(TAG, "Not removing package " + packageName
- + " as only admin user may downgrade system apps");
+ + " as only admin user (or their profile) may downgrade system apps");
EventLog.writeEvent(0x534e4554, "170646036", -1, packageName);
return PackageManager.DELETE_FAILED_USER_RESTRICTED;
}
diff --git a/services/core/java/com/android/server/pm/DexOptHelper.java b/services/core/java/com/android/server/pm/DexOptHelper.java
index f1296e0cd7b0..29b122d56ac5 100644
--- a/services/core/java/com/android/server/pm/DexOptHelper.java
+++ b/services/core/java/com/android/server/pm/DexOptHelper.java
@@ -26,6 +26,7 @@ import static com.android.server.pm.PackageManagerService.REASON_CMDLINE;
import static com.android.server.pm.PackageManagerService.REASON_FIRST_BOOT;
import static com.android.server.pm.PackageManagerService.STUB_SUFFIX;
import static com.android.server.pm.PackageManagerService.TAG;
+import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
import static com.android.server.pm.PackageManagerServiceUtils.REMOVE_IF_NULL_PKG;
@@ -58,6 +59,8 @@ import com.android.server.pm.parsing.pkg.AndroidPackage;
import com.android.server.pm.parsing.pkg.AndroidPackageUtils;
import com.android.server.pm.pkg.PackageStateInternal;
+import dalvik.system.DexFile;
+
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
@@ -267,31 +270,42 @@ final class DexOptHelper {
return;
}
- boolean useProfileForDexopt = false;
- File profileFile = new File(getPrebuildProfilePath(pkg));
- // Copy the profile to the reference profile path if it exists. Installd can only use a
- // profile at the reference profile path for dexopt.
- if (profileFile.exists()) {
- try {
- synchronized (mPm.mInstallLock) {
- if (mPm.mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
- pkg.getUid(), pkg.getPackageName(),
- ArtManager.getProfileName(null))) {
- useProfileForDexopt = true;
- } else {
- Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath());
+ // It could also be after mainline update, but we're not introducing a new reason just for
+ // this special case.
+ int reason = REASON_BOOT_AFTER_OTA;
+
+ String defaultCompilerFilter = getCompilerFilterForReason(reason);
+ String targetCompilerFilter =
+ SystemProperties.get("dalvik.vm.systemuicompilerfilter", defaultCompilerFilter);
+ String compilerFilter;
+
+ if (DexFile.isProfileGuidedCompilerFilter(targetCompilerFilter)) {
+ compilerFilter = defaultCompilerFilter;
+ File profileFile = new File(getPrebuildProfilePath(pkg));
+
+ // Copy the profile to the reference profile path if it exists. Installd can only use a
+ // profile at the reference profile path for dexopt.
+ if (profileFile.exists()) {
+ try {
+ synchronized (mPm.mInstallLock) {
+ if (mPm.mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
+ pkg.getUid(), pkg.getPackageName(),
+ ArtManager.getProfileName(null))) {
+ compilerFilter = targetCompilerFilter;
+ } else {
+ Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath());
+ }
}
+ } catch (Exception e) {
+ Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath(), e);
}
- } catch (Exception e) {
- Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath(), e);
}
+ } else {
+ compilerFilter = targetCompilerFilter;
}
- // It could also be after mainline update, but we're not introducing a new reason just for
- // this special case.
performDexOptTraced(new DexoptOptions(pkg.getPackageName(), REASON_BOOT_AFTER_OTA,
- useProfileForDexopt ? "speed-profile" : "speed", null /* splitName */,
- 0 /* dexoptFlags */));
+ compilerFilter, null /* splitName */, 0 /* dexoptFlags */));
}
@RequiresPermission(Manifest.permission.READ_DEVICE_CONFIG)
diff --git a/services/core/java/com/android/server/pm/FileInstallArgs.java b/services/core/java/com/android/server/pm/FileInstallArgs.java
index 85c3cc91ecf0..e3ceccd1abb8 100644
--- a/services/core/java/com/android/server/pm/FileInstallArgs.java
+++ b/services/core/java/com/android/server/pm/FileInstallArgs.java
@@ -172,9 +172,22 @@ class FileInstallArgs extends InstallArgs {
return false;
}
- if (!onIncremental && !SELinux.restoreconRecursive(afterCodeFile)) {
- Slog.w(TAG, "Failed to restorecon");
- return false;
+ if (onIncremental) {
+ Slog.i(TAG, PackageManagerServiceUtils.SELINUX_BUG
+ + ": Skipping restorecon for Incremental install of " + beforeCodeFile);
+ } else {
+ try {
+ if (!SELinux.restoreconRecursive(afterCodeFile)) {
+ Slog.w(TAG, "Failed to restorecon");
+ return false;
+ }
+ PackageManagerServiceUtils.verifySelinuxLabels(afterCodeFile.getAbsolutePath());
+ } catch (Exception e) {
+ Slog.e(TAG,
+ PackageManagerServiceUtils.SELINUX_BUG + ": Exception from restorecon on "
+ + beforeCodeFile, e);
+ throw e;
+ }
}
// Reflect the rename internally
diff --git a/services/core/java/com/android/server/pm/InstallPackageHelper.java b/services/core/java/com/android/server/pm/InstallPackageHelper.java
index 2d8d4f588192..7932897f295a 100644
--- a/services/core/java/com/android/server/pm/InstallPackageHelper.java
+++ b/services/core/java/com/android/server/pm/InstallPackageHelper.java
@@ -648,6 +648,10 @@ final class InstallPackageHelper {
Log.v(TAG, "restoreAndPostInstall userId=" + userId + " package=" + res.mPkg);
}
+ if (res.mPkg != null) {
+ PackageManagerServiceUtils.verifySelinuxLabels(res.mPkg.getPath());
+ }
+
// A restore should be requested at this point if (a) the install
// succeeded, (b) the operation is not an update.
final boolean update = res.mRemovedInfo != null
@@ -3566,6 +3570,7 @@ final class InstallPackageHelper {
@ParsingPackageUtils.ParseFlags int parseFlags,
@PackageManagerService.ScanFlags int scanFlags,
@Nullable UserHandle user) throws PackageManagerException {
+ PackageManagerServiceUtils.verifySelinuxLabels(parsedPackage.getPath());
final Pair<ScanResult, Boolean> scanResultPair = scanSystemPackageLI(
parsedPackage, parseFlags, scanFlags, user);
diff --git a/services/core/java/com/android/server/pm/Installer.java b/services/core/java/com/android/server/pm/Installer.java
index 32f0f109821d..a078b5d4e8b1 100644
--- a/services/core/java/com/android/server/pm/Installer.java
+++ b/services/core/java/com/android/server/pm/Installer.java
@@ -44,6 +44,8 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
public class Installer extends SystemService {
private static final String TAG = "Installer";
@@ -118,9 +120,13 @@ public class Installer extends SystemService {
public static final int FLAG_CLEAR_APP_DATA_KEEP_ART_PROFILES =
IInstalld.FLAG_CLEAR_APP_DATA_KEEP_ART_PROFILES;
+ private static final long CONNECT_RETRY_DELAY_MS = DateUtils.SECOND_IN_MILLIS;
+ private static final long CONNECT_WAIT_MS = 10 * DateUtils.SECOND_IN_MILLIS;
+
private final boolean mIsolated;
private volatile boolean mDeferSetFirstBoot;
- private volatile IInstalld mInstalld;
+ private volatile IInstalld mInstalld = null;
+ private volatile CountDownLatch mInstalldLatch = new CountDownLatch(1);
private volatile Object mWarnIfHeld;
public Installer(Context context) {
@@ -149,6 +155,7 @@ public class Installer extends SystemService {
public void onStart() {
if (mIsolated) {
mInstalld = null;
+ mInstalldLatch.countDown();
} else {
connect();
}
@@ -160,6 +167,7 @@ public class Installer extends SystemService {
try {
binder.linkToDeath(() -> {
Slog.w(TAG, "installd died; reconnecting");
+ mInstalldLatch = new CountDownLatch(1);
connect();
}, 0);
} catch (RemoteException e) {
@@ -168,7 +176,9 @@ public class Installer extends SystemService {
}
if (binder != null) {
- mInstalld = IInstalld.Stub.asInterface(binder);
+ IInstalld installd = IInstalld.Stub.asInterface(binder);
+ mInstalld = installd;
+ mInstalldLatch.countDown();
try {
invalidateMounts();
executeDeferredActions();
@@ -176,7 +186,7 @@ public class Installer extends SystemService {
}
} else {
Slog.w(TAG, "installd not found; trying again");
- BackgroundThread.getHandler().postDelayed(this::connect, DateUtils.SECOND_IN_MILLIS);
+ BackgroundThread.getHandler().postDelayed(this::connect, CONNECT_RETRY_DELAY_MS);
}
}
@@ -194,7 +204,7 @@ public class Installer extends SystemService {
*
* @return if the remote call should continue.
*/
- private boolean checkBeforeRemote() {
+ private boolean checkBeforeRemote() throws InstallerException {
if (mWarnIfHeld != null && Thread.holdsLock(mWarnIfHeld)) {
Slog.wtf(TAG, "Calling thread " + Thread.currentThread().getName() + " is holding 0x"
+ Integer.toHexString(System.identityHashCode(mWarnIfHeld)), new Throwable());
@@ -202,9 +212,17 @@ public class Installer extends SystemService {
if (mIsolated) {
Slog.i(TAG, "Ignoring request because this installer is isolated");
return false;
- } else {
- return true;
}
+
+ try {
+ if (!mInstalldLatch.await(CONNECT_WAIT_MS, TimeUnit.MILLISECONDS)) {
+ throw new InstallerException("time out waiting for the installer to be ready");
+ }
+ } catch (InterruptedException e) {
+ // Do nothing.
+ }
+
+ return true;
}
// We explicitly do NOT set previousAppId because the default value should always be 0.
diff --git a/services/core/java/com/android/server/pm/IntentResolverInterceptor.java b/services/core/java/com/android/server/pm/IntentResolverInterceptor.java
deleted file mode 100644
index f5eee5ac160d..000000000000
--- a/services/core/java/com/android/server/pm/IntentResolverInterceptor.java
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * Copyright (C) 2022 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.server.pm;
-
-import static com.android.server.wm.ActivityInterceptorCallback.INTENT_RESOLVER_ORDERED_ID;
-
-import android.Manifest;
-import android.annotation.Nullable;
-import android.annotation.RequiresPermission;
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.res.Resources;
-import android.provider.DeviceConfig;
-import android.util.Slog;
-
-import com.android.internal.R;
-import com.android.internal.app.ChooserActivity;
-import com.android.internal.config.sysui.SystemUiDeviceConfigFlags;
-import com.android.server.LocalServices;
-import com.android.server.wm.ActivityInterceptorCallback;
-import com.android.server.wm.ActivityInterceptorCallback.ActivityInterceptorInfo;
-import com.android.server.wm.ActivityTaskManagerInternal;
-
-/**
- * Redirects Activity starts for the system bundled {@link ChooserActivity} to an external
- * Sharesheet implementation by modifying the target component when appropriate.
- * <p>
- * Note: config_chooserActivity (Used also by ActivityTaskSupervisor) is already updated to point
- * to the new instance. This value is read and used for the new target component.
- */
-public final class IntentResolverInterceptor {
- private static final String TAG = "IntentResolverIntercept";
- private final Context mContext;
- private final ComponentName mFrameworkChooserComponent;
- private final ComponentName mUnbundledChooserComponent;
- private boolean mUseUnbundledSharesheet;
-
- private final ActivityInterceptorCallback mActivityInterceptorCallback =
- new ActivityInterceptorCallback() {
- @Nullable
- @Override
- public ActivityInterceptResult intercept(ActivityInterceptorInfo info) {
- if (mUseUnbundledSharesheet && isSystemChooserActivity(info)) {
- Slog.d(TAG, "Redirecting to UNBUNDLED Sharesheet");
- info.intent.setComponent(mUnbundledChooserComponent);
- return new ActivityInterceptResult(info.intent, info.checkedOptions);
- }
- return null;
- }
- };
-
- public IntentResolverInterceptor(Context context) {
- mContext = context;
- mFrameworkChooserComponent = new ComponentName(mContext, ChooserActivity.class);
- mUnbundledChooserComponent = ComponentName.unflattenFromString(
- Resources.getSystem().getString(R.string.config_chooserActivity));
- }
-
- /**
- * Start listening for intents and USE_UNBUNDLED_SHARESHEET property changes.
- */
- @RequiresPermission(Manifest.permission.READ_DEVICE_CONFIG)
- public void registerListeners() {
- LocalServices.getService(ActivityTaskManagerInternal.class)
- .registerActivityStartInterceptor(INTENT_RESOLVER_ORDERED_ID,
- mActivityInterceptorCallback);
-
- DeviceConfig.addOnPropertiesChangedListener(DeviceConfig.NAMESPACE_SYSTEMUI,
- mContext.getMainExecutor(), properties -> updateUseUnbundledSharesheet());
- updateUseUnbundledSharesheet();
- }
-
- @RequiresPermission(Manifest.permission.READ_DEVICE_CONFIG)
- private void updateUseUnbundledSharesheet() {
- mUseUnbundledSharesheet = DeviceConfig.getBoolean(
- DeviceConfig.NAMESPACE_SYSTEMUI,
- SystemUiDeviceConfigFlags.USE_UNBUNDLED_SHARESHEET,
- false);
- if (mUseUnbundledSharesheet) {
- Slog.d(TAG, "using UNBUNDLED Sharesheet");
- } else {
- Slog.d(TAG, "using FRAMEWORK Sharesheet");
- }
- }
-
- private boolean isSystemChooserActivity(ActivityInterceptorInfo info) {
- return mFrameworkChooserComponent.getPackageName().equals(info.aInfo.packageName)
- && mFrameworkChooserComponent.getClassName().equals(info.aInfo.name);
- }
-}
diff --git a/services/core/java/com/android/server/pm/PackageManagerInternalBase.java b/services/core/java/com/android/server/pm/PackageManagerInternalBase.java
index ec6443db9f0f..652847ad1647 100644
--- a/services/core/java/com/android/server/pm/PackageManagerInternalBase.java
+++ b/services/core/java/com/android/server/pm/PackageManagerInternalBase.java
@@ -315,9 +315,9 @@ abstract class PackageManagerInternalBase extends PackageManagerInternal {
@Deprecated
public final List<ResolveInfo> queryIntentReceivers(Intent intent,
String resolvedType, @PackageManager.ResolveInfoFlagsBits long flags,
- int filterCallingUid, int userId) {
- return getResolveIntentHelper().queryIntentReceiversInternal(
- snapshot(), intent, resolvedType, flags, userId, filterCallingUid);
+ int filterCallingUid, int userId, boolean forSend) {
+ return getResolveIntentHelper().queryIntentReceiversInternal(snapshot(), intent,
+ resolvedType, flags, userId, filterCallingUid, forSend);
}
@Override
@@ -352,10 +352,9 @@ abstract class PackageManagerInternalBase extends PackageManagerInternal {
@Override
@Deprecated
- public final void setDeviceOwnerProtectedPackages(
- String deviceOwnerPackageName, List<String> packageNames) {
- getProtectedPackages().setDeviceOwnerProtectedPackages(
- deviceOwnerPackageName, packageNames);
+ public final void setOwnerProtectedPackages(
+ @UserIdInt int userId, @NonNull List<String> packageNames) {
+ getProtectedPackages().setOwnerProtectedPackages(userId, packageNames);
}
@Override
diff --git a/services/core/java/com/android/server/pm/PackageManagerService.java b/services/core/java/com/android/server/pm/PackageManagerService.java
index 2cef35fcf0f6..386c4372ca65 100644
--- a/services/core/java/com/android/server/pm/PackageManagerService.java
+++ b/services/core/java/com/android/server/pm/PackageManagerService.java
@@ -271,8 +271,8 @@ import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
/**
@@ -939,7 +939,6 @@ public class PackageManagerService implements PackageSender, TestUtilityService
private final DexOptHelper mDexOptHelper;
private final SuspendPackageHelper mSuspendPackageHelper;
private final DistractingPackageHelper mDistractingPackageHelper;
- private final IntentResolverInterceptor mIntentResolverInterceptor;
private final StorageEventHelper mStorageEventHelper;
/**
@@ -1038,22 +1037,15 @@ public class PackageManagerService implements PackageSender, TestUtilityService
// times during the PackageManagerService constructor but it should not be modified thereafter.
private ComputerLocked mLiveComputer;
- // A lock-free cache for frequently called functions.
- private volatile Computer mSnapshotComputer;
+ private static final AtomicReference<Computer> sSnapshot = new AtomicReference<>();
- // If true, the snapshot is invalid (stale). The attribute is static since it may be
- // set from outside classes. The attribute may be set to true anywhere, although it
- // should only be set true while holding mLock. However, the attribute id guaranteed
- // to be set false only while mLock and mSnapshotLock are both held.
- private static final AtomicBoolean sSnapshotInvalid = new AtomicBoolean(true);
-
- static final ThreadLocal<ThreadComputer> sThreadComputer =
- ThreadLocal.withInitial(ThreadComputer::new);
+ // If this differs from Computer#getVersion, the snapshot is invalid (stale).
+ private static final AtomicInteger sSnapshotPendingVersion = new AtomicInteger(1);
/**
- * This lock is used to make reads from {@link #sSnapshotInvalid} and
- * {@link #mSnapshotComputer} atomic inside {@code snapshotComputer()}. This lock is
- * not meant to be used outside that method. This lock must be taken before
+ * This lock is used to make reads from {@link #sSnapshotPendingVersion} and
+ * {@link #sSnapshot} atomic inside {@code snapshotComputer()} when the versions mismatch.
+ * This lock is not meant to be used outside that method. This lock must be taken before
* {@link #mLock} is taken.
*/
private final Object mSnapshotLock = new Object();
@@ -1077,48 +1069,53 @@ public class PackageManagerService implements PackageSender, TestUtilityService
// yet invalidated the snapshot. Always give the thread the live computer.
return mLiveComputer;
}
+
+ var oldSnapshot = sSnapshot.get();
+ var pendingVersion = sSnapshotPendingVersion.get();
+
+ if (oldSnapshot != null && oldSnapshot.getVersion() == pendingVersion) {
+ return oldSnapshot.use();
+ }
+
synchronized (mSnapshotLock) {
- // This synchronization block serializes access to the snapshot computer and
- // to the code that samples mSnapshotInvalid.
- Computer c = mSnapshotComputer;
- if (sSnapshotInvalid.getAndSet(false) || (c == null)) {
- // The snapshot is invalid if it is marked as invalid or if it is null. If it
- // is null, then it is currently being rebuilt by rebuildSnapshot().
- synchronized (mLock) {
- // Rebuild the snapshot if it is invalid. Note that the snapshot might be
- // invalidated as it is rebuilt. However, the snapshot is still
- // self-consistent (the lock is being held) and is current as of the time
- // this function is entered.
- rebuildSnapshot();
-
- // Guaranteed to be non-null. mSnapshotComputer is only be set to null
- // temporarily in rebuildSnapshot(), which is guarded by mLock(). Since
- // the mLock is held in this block and since rebuildSnapshot() is
- // complete, the attribute can not now be null.
- c = mSnapshotComputer;
- }
+ // Re-capture pending version in case a new invalidation occurred since last check
+ var rebuildSnapshot = sSnapshot.get();
+ var rebuildVersion = sSnapshotPendingVersion.get();
+
+ // Check the versions again while the lock is held, in case the rebuild time caused
+ // multiple threads to wait on the snapshot lock. When the first thread finishes
+ // a rebuild, the snapshot is now valid and the other waiting threads can use it
+ // without kicking off their own rebuilds.
+ if (rebuildSnapshot != null && rebuildSnapshot.getVersion() == rebuildVersion) {
+ return rebuildSnapshot.use();
+ }
+
+ synchronized (mLock) {
+ // Fetch version one last time to ensure that the rebuilt snapshot matches
+ // the latest invalidation, which could have come in between entering the
+ // SnapshotLock and mLock sync blocks.
+ rebuildVersion = sSnapshotPendingVersion.get();
+
+ // Build the snapshot for this version
+ var newSnapshot = rebuildSnapshot(rebuildSnapshot, rebuildVersion);
+ sSnapshot.set(newSnapshot);
+ return newSnapshot.use();
}
- c.use();
- return c;
}
}
- /**
- * Rebuild the cached computer. mSnapshotComputer is temporarily set to null to block other
- * threads from using the invalid computer until it is rebuilt.
- */
@GuardedBy({ "mLock", "mSnapshotLock"})
- private void rebuildSnapshot() {
- final long now = SystemClock.currentTimeMicro();
- final int hits = mSnapshotComputer == null ? -1 : mSnapshotComputer.getUsed();
- mSnapshotComputer = null;
- final Snapshot args = new Snapshot(Snapshot.SNAPPED);
- mSnapshotComputer = new ComputerEngine(args);
- final long done = SystemClock.currentTimeMicro();
+ private Computer rebuildSnapshot(@Nullable Computer oldSnapshot, int newVersion) {
+ var now = SystemClock.currentTimeMicro();
+ var hits = oldSnapshot == null ? -1 : oldSnapshot.getUsed();
+ var args = new Snapshot(Snapshot.SNAPPED);
+ var newSnapshot = new ComputerEngine(args, newVersion);
+ var done = SystemClock.currentTimeMicro();
if (mSnapshotStatistics != null) {
mSnapshotStatistics.rebuild(now, done, hits);
}
+ return newSnapshot;
}
/**
@@ -1138,7 +1135,7 @@ public class PackageManagerService implements PackageSender, TestUtilityService
if (TRACE_SNAPSHOTS) {
Log.i(TAG, "snapshot: onChange(" + what + ")");
}
- sSnapshotInvalid.set(true);
+ sSnapshotPendingVersion.incrementAndGet();
}
/**
@@ -1665,7 +1662,6 @@ public class PackageManagerService implements PackageSender, TestUtilityService
mRequiredSdkSandboxPackage = testParams.requiredSdkSandboxPackage;
mLiveComputer = createLiveComputer();
- mSnapshotComputer = null;
mSnapshotStatistics = null;
mPackages.putAll(testParams.packages);
@@ -1691,7 +1687,6 @@ public class PackageManagerService implements PackageSender, TestUtilityService
mSharedLibraries.setDeletePackageHelper(mDeletePackageHelper);
- mIntentResolverInterceptor = null;
mStorageEventHelper = testParams.storageEventHelper;
registerObservers(false);
@@ -1855,9 +1850,8 @@ public class PackageManagerService implements PackageSender, TestUtilityService
// cached computer is the same as the live computer until the end of the
// constructor, at which time the invalidation method updates it.
mSnapshotStatistics = new SnapshotStatistics();
- sSnapshotInvalid.set(true);
+ sSnapshotPendingVersion.incrementAndGet();
mLiveComputer = createLiveComputer();
- mSnapshotComputer = null;
registerObservers(true);
}
@@ -2252,8 +2246,6 @@ public class PackageManagerService implements PackageSender, TestUtilityService
mServiceStartWithDelay = SystemClock.uptimeMillis() + (60 * 1000L);
- mIntentResolverInterceptor = new IntentResolverInterceptor(mContext);
-
Slog.i(TAG, "Fix for b/169414761 is applied");
}
@@ -4143,11 +4135,6 @@ public class PackageManagerService implements PackageSender, TestUtilityService
// Prune unused static shared libraries which have been cached a period of time
schedulePruneUnusedStaticSharedLibraries(false /* delay */);
-
- // TODO(b/222706900): Remove this intent interceptor before T launch
- if (mIntentResolverInterceptor != null) {
- mIntentResolverInterceptor.registerListeners();
- }
}
//TODO: b/111402650
@@ -5388,10 +5375,8 @@ public class PackageManagerService implements PackageSender, TestUtilityService
@Override
public void setApplicationCategoryHint(String packageName, int categoryHint,
String callerPackageName) {
- final PackageStateMutator.InitialState initialState = recordInitialState();
-
- final FunctionalUtils.ThrowingFunction<Computer, PackageStateMutator.Result>
- implementation = computer -> {
+ final FunctionalUtils.ThrowingBiFunction<PackageStateMutator.InitialState, Computer,
+ PackageStateMutator.Result> implementation = (initialState, computer) -> {
if (computer.getInstantAppPackageName(Binder.getCallingUid()) != null) {
throw new SecurityException(
"Instant applications don't have access to this method");
@@ -5419,12 +5404,13 @@ public class PackageManagerService implements PackageSender, TestUtilityService
}
};
- PackageStateMutator.Result result = implementation.apply(snapshotComputer());
+ PackageStateMutator.Result result =
+ implementation.apply(recordInitialState(), snapshotComputer());
if (result != null && result.isStateChanged() && !result.isSpecificPackageNull()) {
// TODO: Specific return value of what state changed?
// The installer on record might have changed, retry with lock
synchronized (mPackageStateWriteLock) {
- result = implementation.apply(snapshotComputer());
+ result = implementation.apply(recordInitialState(), snapshotComputer());
}
}
@@ -7156,9 +7142,19 @@ public class PackageManagerService implements PackageSender, TestUtilityService
public PackageStateMutator.Result commitPackageStateMutation(
@Nullable PackageStateMutator.InitialState initialState, @NonNull String packageName,
@NonNull Consumer<PackageStateWrite> consumer) {
+ PackageStateMutator.Result result = null;
+ if (Thread.holdsLock(mPackageStateWriteLock)) {
+ // If the thread is already holding the lock, this is likely a retry based on a prior
+ // failure, and re-calculating whether a state change occurred can be skipped.
+ result = PackageStateMutator.Result.SUCCESS;
+ }
synchronized (mPackageStateWriteLock) {
- final PackageStateMutator.Result result = mPackageStateMutator.generateResult(
- initialState, mChangedPackagesTracker.getSequenceNumber());
+ if (result == null) {
+ // If the thread wasn't previously holding, this is a first-try commit and so a
+ // state change may have happened.
+ result = mPackageStateMutator.generateResult(
+ initialState, mChangedPackagesTracker.getSequenceNumber());
+ }
if (result != PackageStateMutator.Result.SUCCESS) {
return result;
}
diff --git a/services/core/java/com/android/server/pm/PackageManagerServiceUtils.java b/services/core/java/com/android/server/pm/PackageManagerServiceUtils.java
index 4d11b13510e9..703be169f14c 100644
--- a/services/core/java/com/android/server/pm/PackageManagerServiceUtils.java
+++ b/services/core/java/com/android/server/pm/PackageManagerServiceUtils.java
@@ -19,6 +19,7 @@ package com.android.server.pm;
import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
+import static android.content.pm.SigningDetails.CertCapabilities.SHARED_USER_ID;
import static android.system.OsConstants.O_CREAT;
import static android.system.OsConstants.O_RDWR;
@@ -60,6 +61,7 @@ import android.os.Debug;
import android.os.Environment;
import android.os.FileUtils;
import android.os.Process;
+import android.os.SELinux;
import android.os.SystemProperties;
import android.os.incremental.IncrementalManager;
import android.os.incremental.IncrementalStorage;
@@ -564,13 +566,8 @@ public class PackageManagerServiceUtils {
// the older ones. We check to see if either the new package is signed by an older cert
// with which the current sharedUser is ok, or if it is signed by a newer one, and is ok
// with being sharedUser with the existing signing cert.
- boolean match =
- parsedSignatures.checkCapability(
- sharedUserSetting.getSigningDetails(),
- SigningDetails.CertCapabilities.SHARED_USER_ID)
- || sharedUserSetting.getSigningDetails().checkCapability(
- parsedSignatures,
- SigningDetails.CertCapabilities.SHARED_USER_ID);
+ boolean match = canJoinSharedUserId(parsedSignatures,
+ sharedUserSetting.getSigningDetails());
// Special case: if the sharedUserId capability check failed it could be due to this
// being the only package in the sharedUserId so far and the lineage being updated to
// deny the sharedUserId capability of the previous key in the lineage.
@@ -645,6 +642,28 @@ public class PackageManagerServiceUtils {
}
/**
+ * Returns whether the package with {@code packageSigningDetails} can join the sharedUserId
+ * with {@code sharedUserSigningDetails}.
+ * <p>
+ * A sharedUserId maintains a shared {@link SigningDetails} containing the full lineage and
+ * capabilities for each package in the sharedUserId. A package can join the sharedUserId if
+ * its current signer is the same as the shared signer, or if the current signer of either
+ * is in the signing lineage of the other with the {@link
+ * SigningDetails.CertCapabilities#SHARED_USER_ID} capability granted to that previous signer
+ * in the lineage.
+ *
+ * @param packageSigningDetails the {@code SigningDetails} of the package seeking to join the
+ * sharedUserId
+ * @param sharedUserSigningDetails the {@code SigningDetails} of the sharedUserId
+ * @return true if the package seeking to join the sharedUserId meets the requirements
+ */
+ public static boolean canJoinSharedUserId(@NonNull SigningDetails packageSigningDetails,
+ @NonNull SigningDetails sharedUserSigningDetails) {
+ return packageSigningDetails.checkCapability(sharedUserSigningDetails, SHARED_USER_ID)
+ || sharedUserSigningDetails.checkCapability(packageSigningDetails, SHARED_USER_ID);
+ }
+
+ /**
* Extract native libraries to a target path
*/
public static int extractNativeBinaries(File dstCodePath, String packageName) {
@@ -1388,4 +1407,28 @@ public class PackageManagerServiceUtils {
}
}
}
+
+ // TODO(b/231951809): remove this workaround after figuring out why apk_tmp_file labels stay
+ // on the installed apps instead of the correct apk_data_file ones
+
+ public static final String SELINUX_BUG = "b/231951809";
+
+ /**
+ * A workaround for b/231951809:
+ * Verifies the SELinux labels of the passed path, and tries to correct them if detects them
+ * wrong or missing.
+ */
+ public static void verifySelinuxLabels(String path) {
+ final String expectedCon = SELinux.fileSelabelLookup(path);
+ final String actualCon = SELinux.getFileContext(path);
+ Slog.i(TAG, SELINUX_BUG + ": checking selinux labels for " + path + " expected / actual: "
+ + expectedCon + " / " + actualCon);
+ if (expectedCon == null || !expectedCon.equals(actualCon)) {
+ Slog.w(TAG, SELINUX_BUG + ": labels don't match, reapplying for " + path);
+ if (!SELinux.restoreconRecursive(new File(path))) {
+ Slog.w(TAG, SELINUX_BUG + ": Failed to reapply restorecon");
+ }
+ // well, if it didn't work now after not working at first, not much else can be done
+ }
+ }
}
diff --git a/services/core/java/com/android/server/pm/PackageManagerShellCommand.java b/services/core/java/com/android/server/pm/PackageManagerShellCommand.java
index 6b10d4c17527..1eb74facb840 100644
--- a/services/core/java/com/android/server/pm/PackageManagerShellCommand.java
+++ b/services/core/java/com/android/server/pm/PackageManagerShellCommand.java
@@ -2269,10 +2269,23 @@ class PackageManagerShellCommand extends ShellCommand {
}
private int runClear() throws RemoteException {
+ final PrintWriter pw = getOutPrintWriter();
int userId = UserHandle.USER_SYSTEM;
- String option = getNextOption();
- if (option != null && option.equals("--user")) {
- userId = UserHandle.parseUserArg(getNextArgRequired());
+ boolean cacheOnly = false;
+
+ String opt;
+ while ((opt = getNextOption()) != null) {
+ switch (opt) {
+ case "--user":
+ userId = UserHandle.parseUserArg(getNextArgRequired());
+ break;
+ case "--cache-only":
+ cacheOnly = true;
+ break;
+ default:
+ pw.println("Error: Unknown option: " + opt);
+ return 1;
+ }
}
String pkg = getNextArg();
@@ -2284,7 +2297,12 @@ class PackageManagerShellCommand extends ShellCommand {
final int translatedUserId =
translateUserId(userId, UserHandle.USER_NULL, "runClear");
final ClearDataObserver obs = new ClearDataObserver();
- ActivityManager.getService().clearApplicationUserData(pkg, false, obs, translatedUserId);
+ if (!cacheOnly) {
+ ActivityManager.getService()
+ .clearApplicationUserData(pkg, false, obs, translatedUserId);
+ } else {
+ mInterface.deleteApplicationCacheFilesAsUser(pkg, translatedUserId, obs);
+ }
synchronized (obs) {
while (!obs.finished) {
try {
@@ -4042,8 +4060,10 @@ class PackageManagerShellCommand extends ShellCommand {
pw.println(" --user: remove the app from the given user.");
pw.println(" --versionCode: only uninstall if the app has the given version code.");
pw.println("");
- pw.println(" clear [--user USER_ID] PACKAGE");
- pw.println(" Deletes all data associated with a package.");
+ pw.println(" clear [--user USER_ID] [--cache-only] PACKAGE");
+ pw.println(" Deletes data associated with a package. Options are:");
+ pw.println(" --user: specifies the user for which we need to clear data");
+ pw.println(" --cache-only: a flag which tells if we only need to clear cache data");
pw.println("");
pw.println(" enable [--user USER_ID] PACKAGE_OR_COMPONENT");
pw.println(" disable [--user USER_ID] PACKAGE_OR_COMPONENT");
diff --git a/services/core/java/com/android/server/pm/ProtectedPackages.java b/services/core/java/com/android/server/pm/ProtectedPackages.java
index bf4612973023..e9239889973a 100644
--- a/services/core/java/com/android/server/pm/ProtectedPackages.java
+++ b/services/core/java/com/android/server/pm/ProtectedPackages.java
@@ -16,11 +16,11 @@
package com.android.server.pm;
+import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.UserIdInt;
import android.content.Context;
import android.os.UserHandle;
-import android.util.ArrayMap;
import android.util.ArraySet;
import android.util.SparseArray;
@@ -56,7 +56,7 @@ public class ProtectedPackages {
@Nullable
@GuardedBy("this")
- private final ArrayMap<String, Set<String>> mDeviceOwnerProtectedPackages = new ArrayMap<>();
+ private final SparseArray<Set<String>> mOwnerProtectedPackages = new SparseArray<>();
private final Context mContext;
@@ -79,13 +79,13 @@ public class ProtectedPackages {
: profileOwnerPackages.clone();
}
- /** Sets the protected packages for the device owner. */
- public synchronized void setDeviceOwnerProtectedPackages(
- String deviceOwnerPackageName, List<String> packageNames) {
+ /** Sets packages protected by a device or profile owner. */
+ public synchronized void setOwnerProtectedPackages(
+ @UserIdInt int userId, @NonNull List<String> packageNames) {
if (packageNames.isEmpty()) {
- mDeviceOwnerProtectedPackages.remove(deviceOwnerPackageName);
+ mOwnerProtectedPackages.remove(userId);
} else {
- mDeviceOwnerProtectedPackages.put(deviceOwnerPackageName, new ArraySet<>(packageNames));
+ mOwnerProtectedPackages.put(userId, new ArraySet<>(packageNames));
}
}
@@ -123,19 +123,24 @@ public class ProtectedPackages {
* <p>A protected package means that, apart from the package owner, no system or privileged apps
* can modify its data or package state.
*/
- private synchronized boolean isProtectedPackage(String packageName) {
+ private synchronized boolean isProtectedPackage(@UserIdInt int userId, String packageName) {
return packageName != null && (packageName.equals(mDeviceProvisioningPackage)
- || isDeviceOwnerProtectedPackage(packageName));
+ || isOwnerProtectedPackage(userId, packageName));
}
- /** Returns {@code true} if the given package is a protected package set by any device owner. */
- private synchronized boolean isDeviceOwnerProtectedPackage(String packageName) {
- for (Set<String> protectedPackages : mDeviceOwnerProtectedPackages.values()) {
- if (protectedPackages.contains(packageName)) {
- return true;
- }
- }
- return false;
+ /**
+ * Returns {@code true} if the given package is a protected package set by any device or
+ * profile owner.
+ */
+ private synchronized boolean isOwnerProtectedPackage(
+ @UserIdInt int userId, String packageName) {
+ return isPackageProtectedForUser(UserHandle.USER_ALL, packageName)
+ || isPackageProtectedForUser(userId, packageName);
+ }
+
+ private synchronized boolean isPackageProtectedForUser(int userId, String packageName) {
+ int userIdx = mOwnerProtectedPackages.indexOfKey(userId);
+ return userIdx >= 0 && mOwnerProtectedPackages.valueAt(userIdx).contains(packageName);
}
/**
@@ -146,7 +151,7 @@ public class ProtectedPackages {
*/
public boolean isPackageStateProtected(@UserIdInt int userId, String packageName) {
return hasDeviceOwnerOrProfileOwner(userId, packageName)
- || isProtectedPackage(packageName);
+ || isProtectedPackage(userId, packageName);
}
/**
@@ -155,6 +160,6 @@ public class ProtectedPackages {
*/
public boolean isPackageDataProtected(@UserIdInt int userId, String packageName) {
return hasDeviceOwnerOrProfileOwner(userId, packageName)
- || isProtectedPackage(packageName);
+ || isProtectedPackage(userId, packageName);
}
}
diff --git a/services/core/java/com/android/server/pm/ReconcilePackageUtils.java b/services/core/java/com/android/server/pm/ReconcilePackageUtils.java
index 5fc916f888f3..d6a133e43789 100644
--- a/services/core/java/com/android/server/pm/ReconcilePackageUtils.java
+++ b/services/core/java/com/android/server/pm/ReconcilePackageUtils.java
@@ -22,11 +22,9 @@ import static android.content.pm.SigningDetails.CapabilityMergeRule.MERGE_RESTRI
import static com.android.server.pm.PackageManagerService.SCAN_BOOTING;
import static com.android.server.pm.PackageManagerService.SCAN_DONT_KILL_APP;
-import static com.android.server.pm.PackageManagerServiceUtils.compareSignatures;
import android.content.pm.PackageManager;
import android.content.pm.SharedLibraryInfo;
-import android.content.pm.Signature;
import android.content.pm.SigningDetails;
import android.os.SystemProperties;
import android.util.ArrayMap;
@@ -212,12 +210,10 @@ final class ReconcilePackageUtils {
// the signatures on the first package scanned for the shared user (i.e. if the
// signaturesChanged state hasn't been initialized yet in SharedUserSetting).
if (sharedUserSetting != null) {
- final Signature[] sharedUserSignatures = sharedUserSetting
- .signatures.mSigningDetails.getSignatures();
if (sharedUserSetting.signaturesChanged != null
- && compareSignatures(sharedUserSignatures,
- parsedPackage.getSigningDetails().getSignatures())
- != PackageManager.SIGNATURE_MATCH) {
+ && !PackageManagerServiceUtils.canJoinSharedUserId(
+ parsedPackage.getSigningDetails(),
+ sharedUserSetting.getSigningDetails())) {
if (SystemProperties.getInt("ro.product.first_api_level", 0) <= 29) {
// Mismatched signatures is an error and silently skipping system
// packages will likely break the device in unforeseen ways.
diff --git a/services/core/java/com/android/server/pm/ResolveIntentHelper.java b/services/core/java/com/android/server/pm/ResolveIntentHelper.java
index b74670b77a11..2db1c2029d9c 100644
--- a/services/core/java/com/android/server/pm/ResolveIntentHelper.java
+++ b/services/core/java/com/android/server/pm/ResolveIntentHelper.java
@@ -306,16 +306,32 @@ final class ResolveIntentHelper {
return new IntentSender(target);
}
- // In this method, we have to know the actual calling UID, but in some cases Binder's
- // call identity is removed, so the UID has to be passed in explicitly.
- public @NonNull List<ResolveInfo> queryIntentReceiversInternal(Computer computer, Intent intent,
+ /**
+ * Retrieve all receivers that can handle a broadcast of the given intent.
+ * @param queryingUid the results will be filtered in the context of this UID instead.
+ */
+ @NonNull
+ public List<ResolveInfo> queryIntentReceiversInternal(Computer computer, Intent intent,
+ String resolvedType, @PackageManager.ResolveInfoFlagsBits long flags, int userId,
+ int queryingUid) {
+ return queryIntentReceiversInternal(computer, intent, resolvedType, flags, userId,
+ queryingUid, false);
+ }
+
+ /**
+ * @see PackageManagerInternal#queryIntentReceivers(Intent, String, long, int, int, boolean)
+ */
+ @NonNull
+ public List<ResolveInfo> queryIntentReceiversInternal(Computer computer, Intent intent,
String resolvedType, @PackageManager.ResolveInfoFlagsBits long flags, int userId,
- int filterCallingUid) {
+ int filterCallingUid, boolean forSend) {
if (!mUserManager.exists(userId)) return Collections.emptyList();
- computer.enforceCrossUserPermission(filterCallingUid, userId, false /*requireFullPermission*/,
- false /*checkShell*/, "query intent receivers");
- final String instantAppPkgName = computer.getInstantAppPackageName(filterCallingUid);
- flags = computer.updateFlagsForResolve(flags, userId, filterCallingUid,
+ // The identity used to filter the receiver components
+ final int queryingUid = forSend ? Process.SYSTEM_UID : filterCallingUid;
+ computer.enforceCrossUserPermission(queryingUid, userId,
+ false /*requireFullPermission*/, false /*checkShell*/, "query intent receivers");
+ final String instantAppPkgName = computer.getInstantAppPackageName(queryingUid);
+ flags = computer.updateFlagsForResolve(flags, userId, queryingUid,
false /*includeInstantApps*/,
computer.isImplicitImageCaptureIntentAndNotSetByDpc(intent, userId,
resolvedType, flags));
@@ -397,7 +413,7 @@ final class ResolveIntentHelper {
list, true, originalIntent, resolvedType, filterCallingUid);
}
- return computer.applyPostResolutionFilter(list, instantAppPkgName, false, filterCallingUid,
+ return computer.applyPostResolutionFilter(list, instantAppPkgName, false, queryingUid,
false, userId, intent);
}
diff --git a/services/core/java/com/android/server/pm/ThreadComputer.java b/services/core/java/com/android/server/pm/ThreadComputer.java
deleted file mode 100644
index f603e635f75d..000000000000
--- a/services/core/java/com/android/server/pm/ThreadComputer.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.server.pm;
-
-/**
- * This class records the Computer being used by a thread and the Computer's reference
- * count. There is a thread-local copy of this class.
- */
-public final class ThreadComputer implements AutoCloseable {
- Computer mComputer = null;
- int mRefCount = 0;
-
- void acquire(Computer c) {
- if (mRefCount != 0 && mComputer != c) {
- throw new RuntimeException("computer mismatch, count = " + mRefCount);
- }
- mComputer = c;
- mRefCount++;
- }
-
- void acquire() {
- if (mRefCount == 0 || mComputer == null) {
- throw new RuntimeException("computer acquire on empty ref count");
- }
- mRefCount++;
- }
-
- void release() {
- if (--mRefCount == 0) {
- mComputer = null;
- }
- }
-
- @Override
- public void close() {
- release();
- }
-}
diff --git a/services/core/java/com/android/server/pm/UserDataPreparer.java b/services/core/java/com/android/server/pm/UserDataPreparer.java
index 95482d7c7f1a..974a1e1cd59d 100644
--- a/services/core/java/com/android/server/pm/UserDataPreparer.java
+++ b/services/core/java/com/android/server/pm/UserDataPreparer.java
@@ -70,9 +70,16 @@ class UserDataPreparer {
void prepareUserData(int userId, int userSerial, int flags) {
synchronized (mInstallLock) {
final StorageManager storage = mContext.getSystemService(StorageManager.class);
+ /*
+ * Internal storage must be prepared before adoptable storage, since the user's volume
+ * keys are stored in their internal storage.
+ */
+ prepareUserDataLI(null /* internal storage */, userId, userSerial, flags, true);
for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
final String volumeUuid = vol.getFsUuid();
- prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
+ if (volumeUuid != null) {
+ prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
+ }
}
}
}
@@ -136,10 +143,17 @@ class UserDataPreparer {
void destroyUserData(int userId, int flags) {
synchronized (mInstallLock) {
final StorageManager storage = mContext.getSystemService(StorageManager.class);
+ /*
+ * Volume destruction order isn't really important, but to avoid any weird issues we
+ * process internal storage last, the opposite of prepareUserData.
+ */
for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
final String volumeUuid = vol.getFsUuid();
- destroyUserDataLI(volumeUuid, userId, flags);
+ if (volumeUuid != null) {
+ destroyUserDataLI(volumeUuid, userId, flags);
+ }
}
+ destroyUserDataLI(null /* internal storage */, userId, flags);
}
}
diff --git a/services/core/java/com/android/server/pm/dex/ArtStatsLogUtils.java b/services/core/java/com/android/server/pm/dex/ArtStatsLogUtils.java
index b26b6940a1af..d49227dec454 100644
--- a/services/core/java/com/android/server/pm/dex/ArtStatsLogUtils.java
+++ b/services/core/java/com/android/server/pm/dex/ArtStatsLogUtils.java
@@ -22,11 +22,13 @@ import static com.android.internal.art.ArtStatsLog.ART_DATUM_REPORTED__COMPILATI
import static com.android.internal.art.ArtStatsLog.ART_DATUM_REPORTED__COMPILE_FILTER__ART_COMPILATION_FILTER_FAKE_RUN_FROM_APK_FALLBACK;
import static com.android.internal.art.ArtStatsLog.ART_DATUM_REPORTED__COMPILE_FILTER__ART_COMPILATION_FILTER_FAKE_RUN_FROM_VDEX_FALLBACK;
+import android.app.job.JobParameters;
import android.os.SystemClock;
import android.util.Slog;
import android.util.jar.StrictJarFile;
import com.android.internal.art.ArtStatsLog;
+import com.android.server.pm.BackgroundDexOptService;
import com.android.server.pm.PackageManagerService;
import java.io.IOException;
@@ -299,4 +301,31 @@ public class ArtStatsLogUtils {
ArtStatsLog.ART_DATUM_REPORTED__ISA__ART_ISA_UNKNOWN));
}
}
+
+ private static final Map<Integer, Integer> STATUS_MAP =
+ Map.of(BackgroundDexOptService.STATUS_OK,
+ ArtStatsLog.BACKGROUND_DEXOPT_JOB_ENDED__STATUS__STATUS_JOB_FINISHED,
+ BackgroundDexOptService.STATUS_ABORT_BY_CANCELLATION,
+ ArtStatsLog.BACKGROUND_DEXOPT_JOB_ENDED__STATUS__STATUS_ABORT_BY_CANCELLATION,
+ BackgroundDexOptService.STATUS_ABORT_NO_SPACE_LEFT,
+ ArtStatsLog.BACKGROUND_DEXOPT_JOB_ENDED__STATUS__STATUS_ABORT_NO_SPACE_LEFT,
+ BackgroundDexOptService.STATUS_ABORT_THERMAL,
+ ArtStatsLog.BACKGROUND_DEXOPT_JOB_ENDED__STATUS__STATUS_ABORT_THERMAL,
+ BackgroundDexOptService.STATUS_ABORT_BATTERY,
+ ArtStatsLog.BACKGROUND_DEXOPT_JOB_ENDED__STATUS__STATUS_ABORT_BATTERY,
+ BackgroundDexOptService.STATUS_DEX_OPT_FAILED,
+ ArtStatsLog.BACKGROUND_DEXOPT_JOB_ENDED__STATUS__STATUS_JOB_FINISHED);
+
+ /** Helper class to write background dexopt job stats to statsd. */
+ public static class BackgroundDexoptJobStatsLogger {
+ /** Writes background dexopt job stats to statsd. */
+ public void write(@BackgroundDexOptService.Status int status,
+ @JobParameters.StopReason int cancellationReason, long durationMs,
+ long durationIncludingSleepMs) {
+ ArtStatsLog.write(ArtStatsLog.BACKGROUND_DEXOPT_JOB_ENDED,
+ STATUS_MAP.getOrDefault(status,
+ ArtStatsLog.BACKGROUND_DEXOPT_JOB_ENDED__STATUS__STATUS_UNKNOWN),
+ cancellationReason, durationMs, durationIncludingSleepMs);
+ }
+ }
}
diff --git a/services/core/java/com/android/server/pm/permission/DefaultPermissionGrantPolicy.java b/services/core/java/com/android/server/pm/permission/DefaultPermissionGrantPolicy.java
index f727c11879b0..67960655b618 100644
--- a/services/core/java/com/android/server/pm/permission/DefaultPermissionGrantPolicy.java
+++ b/services/core/java/com/android/server/pm/permission/DefaultPermissionGrantPolicy.java
@@ -57,7 +57,6 @@ import android.provider.Telephony.Sms.Intents;
import android.security.Credentials;
import android.speech.RecognitionService;
import android.telephony.TelephonyManager;
-import android.text.TextUtils;
import android.util.ArrayMap;
import android.util.ArraySet;
import android.util.Log;
@@ -618,6 +617,10 @@ final class DefaultPermissionGrantPolicy {
grantPermissionsToSystemPackage(pm, getDefaultSearchSelectorPackage(), userId,
NOTIFICATION_PERMISSIONS);
+ // Captive Portal Login
+ grantPermissionsToSystemPackage(pm, getDefaultCaptivePortalLoginPackage(), userId,
+ NOTIFICATION_PERMISSIONS);
+
// Camera
grantPermissionsToSystemPackage(pm,
getDefaultSystemHandlerActivityPackage(pm, MediaStore.ACTION_IMAGE_CAPTURE, userId),
@@ -909,14 +912,6 @@ final class DefaultPermissionGrantPolicy {
grantSystemFixedPermissionsToSystemPackage(pm, "com.android.sharedstoragebackup", userId,
STORAGE_PERMISSIONS);
- // System Captions Service
- String systemCaptionsServicePackageName =
- mContext.getPackageManager().getSystemCaptionsServicePackageName();
- if (!TextUtils.isEmpty(systemCaptionsServicePackageName)) {
- grantPermissionsToSystemPackage(pm, systemCaptionsServicePackageName, userId,
- MICROPHONE_PERMISSIONS);
- }
-
// Bluetooth MIDI Service
grantSystemFixedPermissionsToSystemPackage(pm,
MidiManager.BLUETOOTH_MIDI_SERVICE_PACKAGE, userId,
@@ -933,6 +928,10 @@ final class DefaultPermissionGrantPolicy {
return mContext.getString(R.string.config_defaultSearchSelectorPackageName);
}
+ private String getDefaultCaptivePortalLoginPackage() {
+ return mContext.getString(R.string.config_defaultCaptivePortalLoginPackageName);
+ }
+
@SafeVarargs
private final void grantPermissionToEachSystemPackage(PackageManagerWrapper pm,
ArrayList<String> packages, int userId, Set<String>... permissions) {
diff --git a/services/core/java/com/android/server/pm/permission/LegacyPermissionManagerInternal.java b/services/core/java/com/android/server/pm/permission/LegacyPermissionManagerInternal.java
index 446e20b70279..6c2354f1b3e6 100644
--- a/services/core/java/com/android/server/pm/permission/LegacyPermissionManagerInternal.java
+++ b/services/core/java/com/android/server/pm/permission/LegacyPermissionManagerInternal.java
@@ -17,6 +17,7 @@
package com.android.server.pm.permission;
import android.annotation.NonNull;
+import android.annotation.Nullable;
import android.annotation.UserIdInt;
/**
@@ -105,6 +106,20 @@ public interface LegacyPermissionManagerInternal {
void scheduleReadDefaultPermissionExceptions();
/**
+ * Check whether a particular package should have access to the microphone data from the
+ * SoundTrigger.
+ *
+ * @param uid the uid of the package you are checking against
+ * @param packageName the name of the package you are checking against
+ * @param attributionTag the attributionTag to attach to the app op transaction
+ * @param reason the reason to attach to the app op transaction
+ * @return {@code PERMISSION_GRANTED} if the permission is granted,
+ * or {@code PERMISSION_SOFT/HARD DENIED otherwise
+ */
+ int checkSoundTriggerRecordAudioPermissionForDataDelivery(int uid,
+ @NonNull String packageName, @Nullable String attributionTag, @NonNull String reason);
+
+ /**
* Provider for package names.
*/
interface PackagesProvider {
diff --git a/services/core/java/com/android/server/pm/permission/LegacyPermissionManagerService.java b/services/core/java/com/android/server/pm/permission/LegacyPermissionManagerService.java
index 360a04f7e9bc..88b4a94f7027 100644
--- a/services/core/java/com/android/server/pm/permission/LegacyPermissionManagerService.java
+++ b/services/core/java/com/android/server/pm/permission/LegacyPermissionManagerService.java
@@ -16,12 +16,15 @@
package com.android.server.pm.permission;
+import static android.Manifest.permission.RECORD_AUDIO;
+
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.UserIdInt;
import android.app.AppOpsManager;
import android.app.admin.DevicePolicyManager;
import android.content.Context;
+import android.content.PermissionChecker;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManagerInternal;
@@ -399,6 +402,21 @@ public class LegacyPermissionManagerService extends ILegacyPermissionManager.Stu
public void scheduleReadDefaultPermissionExceptions() {
mDefaultPermissionGrantPolicy.scheduleReadDefaultPermissionExceptions();
}
+
+ @Override
+ public int checkSoundTriggerRecordAudioPermissionForDataDelivery(int uid,
+ @NonNull String packageName, @Nullable String attributionTag,
+ @NonNull String reason) {
+ int result = PermissionChecker.checkPermissionForPreflight(mContext, RECORD_AUDIO, -1,
+ uid, packageName);
+ if (result != PermissionChecker.PERMISSION_GRANTED) {
+ return result;
+ }
+ mContext.getSystemService(AppOpsManager.class).noteOpNoThrow(
+ AppOpsManager.OP_RECEIVE_AMBIENT_TRIGGER_AUDIO, uid, packageName,
+ attributionTag, reason);
+ return result;
+ }
}
/**
diff --git a/services/core/java/com/android/server/pm/permission/PermissionManagerService.java b/services/core/java/com/android/server/pm/permission/PermissionManagerService.java
index 5a05134bed81..a83cb5e37ba2 100644
--- a/services/core/java/com/android/server/pm/permission/PermissionManagerService.java
+++ b/services/core/java/com/android/server/pm/permission/PermissionManagerService.java
@@ -17,7 +17,6 @@
package com.android.server.pm.permission;
import static android.Manifest.permission.CAPTURE_AUDIO_HOTWORD;
-import static android.Manifest.permission.POST_NOTIFICATIONS;
import static android.Manifest.permission.RECORD_AUDIO;
import static android.Manifest.permission.UPDATE_APP_OPS_STATS;
import static android.app.AppOpsManager.ATTRIBUTION_CHAIN_ID_NONE;
@@ -51,7 +50,6 @@ import android.content.pm.PermissionGroupInfo;
import android.content.pm.PermissionInfo;
import android.content.pm.permission.SplitPermissionInfoParcelable;
import android.os.Binder;
-import android.os.Build;
import android.os.IBinder;
import android.os.Process;
import android.os.RemoteException;
@@ -596,26 +594,6 @@ public class PermissionManagerService extends IPermissionManager.Stub {
}
@Override
- public int checkPostNotificationsPermissionGrantedOrLegacyAccess(int uid) {
- int granted = PermissionManagerService.this.checkUidPermission(uid,
- POST_NOTIFICATIONS);
- AndroidPackage pkg = mPackageManagerInt.getPackage(uid);
- if (pkg == null) {
- Slog.e(LOG_TAG, "No package for uid " + uid);
- return granted;
- }
- if (granted != PackageManager.PERMISSION_GRANTED
- && pkg.getTargetSdkVersion() >= Build.VERSION_CODES.M) {
- int flags = PermissionManagerService.this.getPermissionFlags(pkg.getPackageName(),
- POST_NOTIFICATIONS, UserHandle.getUserId(uid));
- if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
- return PackageManager.PERMISSION_GRANTED;
- }
- }
- return granted;
- }
-
- @Override
public void startShellPermissionIdentityDelegation(int uid, @NonNull String packageName,
@Nullable List<String> permissionNames) {
Objects.requireNonNull(packageName, "packageName");
diff --git a/services/core/java/com/android/server/pm/permission/PermissionManagerServiceImpl.java b/services/core/java/com/android/server/pm/permission/PermissionManagerServiceImpl.java
index 7be83b03243a..d34682df3413 100644
--- a/services/core/java/com/android/server/pm/permission/PermissionManagerServiceImpl.java
+++ b/services/core/java/com/android/server/pm/permission/PermissionManagerServiceImpl.java
@@ -42,6 +42,7 @@ import static android.content.pm.PackageManager.FLAG_PERMISSION_WHITELIST_SYSTEM
import static android.content.pm.PackageManager.FLAG_PERMISSION_WHITELIST_UPGRADE;
import static android.content.pm.PackageManager.MASK_PERMISSION_FLAGS_ALL;
import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
+import static android.content.pm.PackageManager.PERMISSION_GRANTED;
import static android.os.Process.INVALID_UID;
import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
import static android.permission.PermissionManager.KILL_APP_REASON_GIDS_CHANGED;
@@ -97,6 +98,7 @@ import android.os.storage.StorageManager;
import android.permission.IOnPermissionsChangeListener;
import android.permission.PermissionControllerManager;
import android.permission.PermissionManager;
+import android.provider.Settings;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.util.ArraySet;
@@ -333,7 +335,8 @@ public class PermissionManagerServiceImpl implements PermissionManagerServiceInt
mPackageManagerInt.writeSettings(true);
}
@Override
- public void onPermissionRevoked(int uid, int userId, String reason, boolean overrideKill) {
+ public void onPermissionRevoked(int uid, int userId, String reason, boolean overrideKill,
+ @Nullable String permissionName) {
mOnPermissionChangeListeners.onPermissionsChanged(uid);
// Critical; after this call the application should never have the permission
@@ -342,13 +345,41 @@ public class PermissionManagerServiceImpl implements PermissionManagerServiceInt
return;
}
- final int appId = UserHandle.getAppId(uid);
- if (reason == null) {
- mHandler.post(() -> killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED));
- } else {
- mHandler.post(() -> killUid(appId, userId, reason));
+ mHandler.post(() -> {
+ if (POST_NOTIFICATIONS.equals(permissionName)
+ && isAppBackupAndRestoreRunning(uid)) {
+ return;
+ }
+
+ final int appId = UserHandle.getAppId(uid);
+ if (reason == null) {
+ killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
+ } else {
+ killUid(appId, userId, reason);
+ }
+ });
+ }
+
+ private boolean isAppBackupAndRestoreRunning(int uid) {
+ if (checkUidPermission(uid, Manifest.permission.BACKUP) != PERMISSION_GRANTED) {
+ return false;
+ }
+
+ try {
+ int userId = UserHandle.getUserId(uid);
+ boolean isInSetup = Settings.Secure.getIntForUser(mContext.getContentResolver(),
+ Settings.Secure.USER_SETUP_COMPLETE, userId) == 0;
+ boolean isInDeferredSetup = Settings.Secure.getIntForUser(
+ mContext.getContentResolver(),
+ Settings.Secure.USER_SETUP_PERSONALIZATION_STATE, userId)
+ == Settings.Secure.USER_SETUP_PERSONALIZATION_STARTED;
+ return isInSetup || isInDeferredSetup;
+ } catch (Settings.SettingNotFoundException e) {
+ Slog.w(LOG_TAG, "Failed to check if the user is in restore: " + e);
+ return false;
}
}
+
@Override
public void onInstallPermissionRevoked() {
mPackageManagerInt.writeSettings(true);
@@ -1600,7 +1631,7 @@ public class PermissionManagerServiceImpl implements PermissionManagerServiceInt
if (callback != null) {
if (isRuntimePermission) {
callback.onPermissionRevoked(UserHandle.getUid(userId, pkg.getUid()), userId,
- reason, overrideKill);
+ reason, overrideKill, permName);
} else {
mDefaultPermissionCallback.onInstallPermissionRevoked();
}
@@ -5246,7 +5277,11 @@ public class PermissionManagerServiceImpl implements PermissionManagerServiceInt
onPermissionRevoked(uid, userId, reason, false);
}
public void onPermissionRevoked(int uid, @UserIdInt int userId, String reason,
- boolean overrideKill) {}
+ boolean overrideKill) {
+ onPermissionRevoked(uid, userId, reason, false, null);
+ }
+ public void onPermissionRevoked(int uid, @UserIdInt int userId, String reason,
+ boolean overrideKill, @Nullable String permissionName) {}
public void onInstallPermissionRevoked() {}
public void onPermissionUpdated(@UserIdInt int[] updatedUserIds, boolean sync) {}
public void onPermissionUpdatedNotifyListener(@UserIdInt int[] updatedUserIds, boolean sync,
diff --git a/services/core/java/com/android/server/pm/permission/PermissionManagerServiceInternal.java b/services/core/java/com/android/server/pm/permission/PermissionManagerServiceInternal.java
index 812d7a04dc13..d2c4ec4cc5a5 100644
--- a/services/core/java/com/android/server/pm/permission/PermissionManagerServiceInternal.java
+++ b/services/core/java/com/android/server/pm/permission/PermissionManagerServiceInternal.java
@@ -63,17 +63,6 @@ public interface PermissionManagerServiceInternal extends PermissionManagerInter
int checkUidPermission(int uid, @NonNull String permissionName);
/**
- * Check whether a particular UID has been granted the POST_NOTIFICATIONS permission, or if
- * access should be granted based on legacy access (currently symbolized by the REVIEW_REQUIRED
- * permission flag
- *
- * @param uid the UID
- * @return {@code PERMISSION_GRANTED} if the permission is granted, or legacy access is granted,
- * {@code PERMISSION_DENIED} otherwise
- */
- int checkPostNotificationsPermissionGrantedOrLegacyAccess(int uid);
-
- /**
* Adds a listener for runtime permission state (permissions or flags) changes.
*
* @param listener The listener.
diff --git a/services/core/java/com/android/server/pm/pkg/component/ParsedPermissionUtils.java b/services/core/java/com/android/server/pm/pkg/component/ParsedPermissionUtils.java
index f2e2f4f009a9..281e1bd2824d 100644
--- a/services/core/java/com/android/server/pm/pkg/component/ParsedPermissionUtils.java
+++ b/services/core/java/com/android/server/pm/pkg/component/ParsedPermissionUtils.java
@@ -26,6 +26,7 @@ import android.content.res.Resources;
import android.content.res.TypedArray;
import android.content.res.XmlResourceParser;
import android.util.ArrayMap;
+import android.util.EventLog;
import android.util.Slog;
import com.android.internal.R;
@@ -36,6 +37,7 @@ import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.List;
+import java.util.Objects;
/**
* @hide
@@ -277,8 +279,28 @@ public class ParsedPermissionUtils {
}
/**
- * @return {@code true} if the package declares duplicate permissions with different
- * protection levels.
+ * Determines if a duplicate permission is malformed .i.e. defines different protection level
+ * or group.
+ */
+ private static boolean isMalformedDuplicate(ParsedPermission p1, ParsedPermission p2) {
+ // Since a permission tree is also added as a permission with normal protection
+ // level, we need to skip if the parsedPermission is a permission tree.
+ if (p1 == null || p2 == null || p1.isTree() || p2.isTree()) {
+ return false;
+ }
+
+ if (p1.getProtectionLevel() != p2.getProtectionLevel()) {
+ return true;
+ }
+ if (!Objects.equals(p1.getGroup(), p2.getGroup())) {
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * @return {@code true} if the package declares malformed duplicate permissions.
*/
public static boolean declareDuplicatePermission(@NonNull ParsingPackage pkg) {
final List<ParsedPermission> permissions = pkg.getPermissions();
@@ -289,10 +311,10 @@ public class ParsedPermissionUtils {
final ParsedPermission parsedPermission = permissions.get(i);
final String name = parsedPermission.getName();
final ParsedPermission perm = checkDuplicatePerm.get(name);
- // Since a permission tree is also added as a permission with normal protection
- // level, we need to skip if the parsedPermission is a permission tree.
- if (perm != null && !(perm.isTree() || parsedPermission.isTree())
- && perm.getProtectionLevel() != parsedPermission.getProtectionLevel()) {
+ if (isMalformedDuplicate(parsedPermission, perm)) {
+ // Fix for b/213323615
+ EventLog.writeEvent(0x534e4554, "213323615",
+ "The package " + pkg.getPackageName() + " seems malicious");
return true;
}
checkDuplicatePerm.put(name, parsedPermission);
diff --git a/services/core/java/com/android/server/pm/pkg/parsing/ParsingPackageUtils.java b/services/core/java/com/android/server/pm/pkg/parsing/ParsingPackageUtils.java
index 3799dbb630f0..08a7f6dffa6b 100644
--- a/services/core/java/com/android/server/pm/pkg/parsing/ParsingPackageUtils.java
+++ b/services/core/java/com/android/server/pm/pkg/parsing/ParsingPackageUtils.java
@@ -968,7 +968,7 @@ public class ParsingPackageUtils {
if (ParsedPermissionUtils.declareDuplicatePermission(pkg)) {
return input.error(
INSTALL_PARSE_FAILED_MANIFEST_MALFORMED,
- "Declare duplicate permissions with different protection levels."
+ "Found duplicate permission with a different attribute value."
);
}
diff --git a/services/core/java/com/android/server/policy/AppOpsPolicy.java b/services/core/java/com/android/server/policy/AppOpsPolicy.java
index a8ed70b91442..ebd9126d1439 100644
--- a/services/core/java/com/android/server/policy/AppOpsPolicy.java
+++ b/services/core/java/com/android/server/policy/AppOpsPolicy.java
@@ -87,8 +87,8 @@ public final class AppOpsPolicy implements AppOpsManagerInternal.CheckOpsDelegat
private final VoiceInteractionManagerInternal mVoiceInteractionManagerInternal;
/**
- * Whether this device allows only the HotwordDetectionService to use OP_RECORD_AUDIO_HOTWORD
- * which doesn't incur the privacy indicator.
+ * Whether this device allows only the HotwordDetectionService to use
+ * OP_RECORD_AUDIO_HOTWORD which doesn't incur the privacy indicator.
*/
private final boolean mIsHotwordDetectionServiceRequired;
@@ -427,8 +427,8 @@ public final class AppOpsPolicy implements AppOpsManagerInternal.CheckOpsDelegat
if (!mIsHotwordDetectionServiceRequired) {
return code;
}
- // Only the HotwordDetectionService can use the HOTWORD op which doesn't incur the
- // privacy indicator. Downgrade to standard RECORD_AUDIO for other processes.
+ // Only the HotwordDetectionService can use the RECORD_AUDIO_HOTWORD op which doesn't
+ // incur the privacy indicator. Downgrade to standard RECORD_AUDIO for other processes.
final HotwordDetectionServiceIdentity hotwordDetectionServiceIdentity =
mVoiceInteractionManagerInternal.getHotwordDetectionServiceIdentity();
if (hotwordDetectionServiceIdentity != null
diff --git a/services/core/java/com/android/server/policy/PermissionPolicyService.java b/services/core/java/com/android/server/policy/PermissionPolicyService.java
index 977f79f6175d..b56e1120f16a 100644
--- a/services/core/java/com/android/server/policy/PermissionPolicyService.java
+++ b/services/core/java/com/android/server/policy/PermissionPolicyService.java
@@ -915,8 +915,7 @@ public final class PermissionPolicyService extends SystemService {
int permissionFlags = mPackageManager.getPermissionFlags(permissionName,
packageName, mContext.getUser());
boolean isReviewRequired = (permissionFlags & FLAG_PERMISSION_REVIEW_REQUIRED) != 0;
- if (isReviewRequired && !CompatChanges.isChangeEnabled(
- NOTIFICATION_PERM_CHANGE_ID, packageName, user)) {
+ if (isReviewRequired) {
return;
}
@@ -1118,48 +1117,13 @@ public final class PermissionPolicyService extends SystemService {
private class Internal extends PermissionPolicyInternal {
- // UIDs that, if a grant dialog is shown for POST_NOTIFICATIONS before next reboot,
- // should display a "continue allowing" message, rather than an "allow" message
- private final ArraySet<Integer> mContinueNotifGrantMessageUids = new ArraySet<>();
-
private final ActivityInterceptorCallback mActivityInterceptorCallback =
new ActivityInterceptorCallback() {
@Nullable
@Override
public ActivityInterceptorCallback.ActivityInterceptResult intercept(
ActivityInterceptorInfo info) {
- String action = info.intent.getAction();
- ActivityInterceptResult result = null;
- if (!ACTION_REQUEST_PERMISSIONS_FOR_OTHER.equals(action)
- && !PackageManager.ACTION_REQUEST_PERMISSIONS.equals(action)) {
- return null;
- }
- // Only this interceptor can add LEGACY_ACCESS_PERMISSION_NAMES
- if (info.intent.getStringArrayExtra(PackageManager
- .EXTRA_REQUEST_PERMISSIONS_LEGACY_ACCESS_PERMISSION_NAMES)
- != null) {
- result = new ActivityInterceptResult(
- new Intent(info.intent), info.checkedOptions);
- result.intent.removeExtra(PackageManager
- .EXTRA_REQUEST_PERMISSIONS_LEGACY_ACCESS_PERMISSION_NAMES);
- }
- if (PackageManager.ACTION_REQUEST_PERMISSIONS.equals(action)
- && !mContinueNotifGrantMessageUids.contains(info.realCallingUid)) {
- return result;
- }
- if (ACTION_REQUEST_PERMISSIONS_FOR_OTHER.equals(action)) {
- String otherPkg = info.intent.getStringExtra(Intent.EXTRA_PACKAGE_NAME);
- if (otherPkg == null || (mPackageManager.getPermissionFlags(
- POST_NOTIFICATIONS, otherPkg, UserHandle.of(info.userId))
- & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
- return result;
- }
- }
-
- mContinueNotifGrantMessageUids.remove(info.realCallingUid);
- return new ActivityInterceptResult(info.intent.putExtra(PackageManager
- .EXTRA_REQUEST_PERMISSIONS_LEGACY_ACCESS_PERMISSION_NAMES,
- new String[] { POST_NOTIFICATIONS }), info.checkedOptions);
+ return null;
}
@Override
@@ -1173,10 +1137,8 @@ public final class PermissionPolicyService extends SystemService {
return;
}
UserHandle user = UserHandle.of(taskInfo.userId);
- if (CompatChanges.isChangeEnabled(NOTIFICATION_PERM_CHANGE_ID,
+ if (!CompatChanges.isChangeEnabled(NOTIFICATION_PERM_CHANGE_ID,
activityInfo.packageName, user)) {
- clearNotificationReviewFlagsIfNeeded(activityInfo.packageName, user);
- } else {
// Post the activity start checks to ensure the notification channel
// checks happen outside the WindowManager global lock.
mHandler.post(() -> showNotificationPromptIfNeeded(
@@ -1337,22 +1299,6 @@ public final class PermissionPolicyService extends SystemService {
&& isLauncherIntent(taskInfo.baseIntent);
}
- private void clearNotificationReviewFlagsIfNeeded(String packageName, UserHandle user) {
- if ((mPackageManager.getPermissionFlags(POST_NOTIFICATIONS, packageName, user)
- & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
- return;
- }
- try {
- int uid = mPackageManager.getPackageUidAsUser(packageName, 0,
- user.getIdentifier());
- mContinueNotifGrantMessageUids.add(uid);
- mPackageManager.updatePermissionFlags(POST_NOTIFICATIONS, packageName,
- FLAG_PERMISSION_REVIEW_REQUIRED, 0, user);
- } catch (PackageManager.NameNotFoundException e) {
- // Do nothing
- }
- }
-
private void launchNotificationPermissionRequestDialog(String pkgName, UserHandle user,
int taskId, @Nullable ActivityInterceptorInfo info) {
Intent grantPermission = mPackageManager
@@ -1469,8 +1415,7 @@ public final class PermissionPolicyService extends SystemService {
== PackageManager.PERMISSION_GRANTED;
int flags = mPackageManager.getPermissionFlags(POST_NOTIFICATIONS, pkgName, user);
boolean explicitlySet = (flags & PermissionManager.EXPLICIT_SET_FLAGS) != 0;
- boolean needsReview = (flags & FLAG_PERMISSION_REVIEW_REQUIRED) != 0;
- return !granted && hasCreatedNotificationChannels && (needsReview || !explicitlySet);
+ return !granted && hasCreatedNotificationChannels && !explicitlySet;
}
}
}
diff --git a/services/core/java/com/android/server/sensorprivacy/CameraPrivacyLightController.java b/services/core/java/com/android/server/sensorprivacy/CameraPrivacyLightController.java
index 750d4004cb60..fd6ec065d421 100644
--- a/services/core/java/com/android/server/sensorprivacy/CameraPrivacyLightController.java
+++ b/services/core/java/com/android/server/sensorprivacy/CameraPrivacyLightController.java
@@ -16,44 +16,105 @@
package com.android.server.sensorprivacy;
+import static android.hardware.SensorManager.SENSOR_DELAY_NORMAL;
+
+import android.annotation.ColorInt;
import android.app.AppOpsManager;
import android.content.Context;
+import android.hardware.Sensor;
+import android.hardware.SensorEvent;
+import android.hardware.SensorEventListener;
+import android.hardware.SensorManager;
import android.hardware.lights.Light;
import android.hardware.lights.LightState;
import android.hardware.lights.LightsManager;
import android.hardware.lights.LightsRequest;
+import android.os.Handler;
+import android.os.HandlerExecutor;
+import android.os.Looper;
+import android.os.SystemClock;
import android.permission.PermissionManager;
import android.util.ArraySet;
+import android.util.Pair;
import com.android.internal.R;
+import com.android.internal.annotations.VisibleForTesting;
import com.android.server.FgThread;
+import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
+import java.util.concurrent.Executor;
+
+class CameraPrivacyLightController implements AppOpsManager.OnOpActiveChangedListener,
+ SensorEventListener {
-class CameraPrivacyLightController implements AppOpsManager.OnOpActiveChangedListener {
+ @VisibleForTesting
+ static final double LIGHT_VALUE_MULTIPLIER = 1 / Math.log(1.1);
+ private final Handler mHandler;
+ private final Executor mExecutor;
private final Context mContext;
+ private final AppOpsManager mAppOpsManager;
private final LightsManager mLightsManager;
+ private final SensorManager mSensorManager;
private final Set<String> mActivePackages = new ArraySet<>();
private final Set<String> mActivePhonePackages = new ArraySet<>();
- private final int mCameraPrivacyLightColor;
-
private final List<Light> mCameraLights = new ArrayList<>();
- private final AppOpsManager mAppOpsManager;
private LightsManager.LightsSession mLightsSession = null;
+ @ColorInt
+ private final int mDayColor;
+ @ColorInt
+ private final int mNightColor;
+
+ private final Sensor mLightSensor;
+
+ private boolean mIsAmbientLightListenerRegistered = false;
+ private final long mMovingAverageIntervalMillis;
+ /** When average of the time integral over the past {@link #mMovingAverageIntervalMillis}
+ * milliseconds of the log_1.1(lux(t)) is greater than this value, use the daytime brightness
+ * else use nighttime brightness. */
+ private final long mNightThreshold;
+ private final ArrayDeque<Pair<Long, Integer>> mAmbientLightValues = new ArrayDeque<>();
+ /** Tracks the Riemann sum of {@link #mAmbientLightValues} to avoid O(n) operations when sum is
+ * needed */
+ private long mAlvSum = 0;
+ private int mLastLightColor = 0;
+ /** The elapsed real time that the ALS was started watching */
+ private long mElapsedTimeStartedReading;
+
+ private final Object mDelayedUpdateToken = new Object();
+
+ // Can't mock static native methods, workaround for testing
+ private long mElapsedRealTime = -1;
+
CameraPrivacyLightController(Context context) {
+ this(context, FgThread.get().getLooper());
+ }
+
+ @VisibleForTesting
+ CameraPrivacyLightController(Context context, Looper looper) {
mContext = context;
+ mHandler = new Handler(looper);
+ mExecutor = new HandlerExecutor(mHandler);
+
mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
mLightsManager = mContext.getSystemService(LightsManager.class);
+ mSensorManager = mContext.getSystemService(SensorManager.class);
- mCameraPrivacyLightColor = mContext.getColor(R.color.camera_privacy_light);
+ mDayColor = mContext.getColor(R.color.camera_privacy_light_day);
+ mNightColor = mContext.getColor(R.color.camera_privacy_light_night);
+ mMovingAverageIntervalMillis = mContext.getResources()
+ .getInteger(R.integer.config_cameraPrivacyLightAlsAveragingIntervalMillis);
+ mNightThreshold = (long) (Math.log(mContext.getResources()
+ .getInteger(R.integer.config_cameraPrivacyLightAlsNightThreshold))
+ * LIGHT_VALUE_MULTIPLIER);
List<Light> lights = mLightsManager.getLights();
for (int i = 0; i < lights.size(); i++) {
@@ -64,12 +125,60 @@ class CameraPrivacyLightController implements AppOpsManager.OnOpActiveChangedLis
}
if (mCameraLights.isEmpty()) {
+ mLightSensor = null;
return;
}
mAppOpsManager.startWatchingActive(
new String[] {AppOpsManager.OPSTR_CAMERA, AppOpsManager.OPSTR_PHONE_CALL_CAMERA},
- FgThread.getExecutor(), this);
+ mExecutor, this);
+
+ // It may be useful in the future to configure devices to know which lights are near which
+ // sensors so that we can control individual lights based on their environment.
+ mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
+ }
+
+ private void addElement(long time, int value) {
+ if (mAmbientLightValues.isEmpty()) {
+ // Eliminate the size == 1 edge case and assume the light value has been constant for
+ // the previous interval
+ mAmbientLightValues.add(new Pair<>(time - getCurrentIntervalMillis() - 1, value));
+ }
+ Pair<Long, Integer> lastElement = mAmbientLightValues.peekLast();
+ mAmbientLightValues.add(new Pair<>(time, value));
+
+ mAlvSum += (time - lastElement.first) * lastElement.second;
+ removeObsoleteData(time);
+ }
+
+ private void removeObsoleteData(long time) {
+ while (mAmbientLightValues.size() > 1) {
+ Pair<Long, Integer> element0 = mAmbientLightValues.pollFirst(); // NOTICE: POLL
+ Pair<Long, Integer> element1 = mAmbientLightValues.peekFirst(); // NOTICE: PEEK
+ if (element1.first > time - getCurrentIntervalMillis()) {
+ mAmbientLightValues.addFirst(element0);
+ break;
+ }
+ mAlvSum -= (element1.first - element0.first) * element0.second;
+ }
+ }
+
+ /**
+ * Gives the Riemann sum of {@link #mAmbientLightValues} where the part of the interval that
+ * stretches outside the time window is removed and the time since the last change is added in.
+ */
+ private long getLiveAmbientLightTotal() {
+ if (mAmbientLightValues.isEmpty()) {
+ return mAlvSum;
+ }
+ long time = getElapsedRealTime();
+ removeObsoleteData(time);
+
+ Pair<Long, Integer> firstElement = mAmbientLightValues.peekFirst();
+ Pair<Long, Integer> lastElement = mAmbientLightValues.peekLast();
+
+ return mAlvSum - Math.max(0, time - getCurrentIntervalMillis() - firstElement.first)
+ * firstElement.second + (time - lastElement.first) * lastElement.second;
}
@Override
@@ -93,10 +202,16 @@ class CameraPrivacyLightController implements AppOpsManager.OnOpActiveChangedLis
}
private void updateLightSession() {
+ if (Looper.myLooper() != mHandler.getLooper()) {
+ mHandler.post(this::updateLightSession);
+ return;
+ }
+
Set<String> exemptedPackages = PermissionManager.getIndicatorExemptedPackages(mContext);
boolean shouldSessionEnd = exemptedPackages.containsAll(mActivePackages)
&& exemptedPackages.containsAll(mActivePhonePackages);
+ updateSensorListener(shouldSessionEnd);
if (shouldSessionEnd) {
if (mLightsSession == null) {
@@ -106,20 +221,73 @@ class CameraPrivacyLightController implements AppOpsManager.OnOpActiveChangedLis
mLightsSession.close();
mLightsSession = null;
} else {
- if (mLightsSession != null) {
+ int lightColor;
+ if (mLightSensor != null && getLiveAmbientLightTotal()
+ < getCurrentIntervalMillis() * mNightThreshold) {
+ lightColor = mNightColor;
+ } else {
+ lightColor = mDayColor;
+ }
+
+ if (mLastLightColor == lightColor && mLightsSession != null) {
return;
}
+ mLastLightColor = lightColor;
LightsRequest.Builder requestBuilder = new LightsRequest.Builder();
for (int i = 0; i < mCameraLights.size(); i++) {
requestBuilder.addLight(mCameraLights.get(i),
new LightState.Builder()
- .setColor(mCameraPrivacyLightColor)
+ .setColor(lightColor)
.build());
}
- mLightsSession = mLightsManager.openSession(Integer.MAX_VALUE);
+ if (mLightsSession == null) {
+ mLightsSession = mLightsManager.openSession(Integer.MAX_VALUE);
+ }
+
mLightsSession.requestLights(requestBuilder.build());
}
}
+
+ private void updateSensorListener(boolean shouldSessionEnd) {
+ if (shouldSessionEnd && mIsAmbientLightListenerRegistered) {
+ mSensorManager.unregisterListener(this);
+ mIsAmbientLightListenerRegistered = false;
+ }
+ if (!shouldSessionEnd && !mIsAmbientLightListenerRegistered && mLightSensor != null) {
+ mSensorManager.registerListener(this, mLightSensor, SENSOR_DELAY_NORMAL, mHandler);
+ mIsAmbientLightListenerRegistered = true;
+ mElapsedTimeStartedReading = getElapsedRealTime();
+ }
+ }
+
+ private long getElapsedRealTime() {
+ return mElapsedRealTime == -1 ? SystemClock.elapsedRealtime() : mElapsedRealTime;
+ }
+
+ @VisibleForTesting
+ void setElapsedRealTime(long time) {
+ mElapsedRealTime = time;
+ }
+
+ @Override
+ public void onSensorChanged(SensorEvent event) {
+ // Using log space to represent human sensation (Fechner's Law) instead of lux
+ // because lux values causes bright flashes to skew the average very high.
+ addElement(event.timestamp, Math.max(0,
+ (int) (Math.log(event.values[0]) * LIGHT_VALUE_MULTIPLIER)));
+ updateLightSession();
+ mHandler.removeCallbacksAndMessages(mDelayedUpdateToken);
+ mHandler.postDelayed(CameraPrivacyLightController.this::updateLightSession,
+ mDelayedUpdateToken, mMovingAverageIntervalMillis);
+ }
+
+ @Override
+ public void onAccuracyChanged(Sensor sensor, int accuracy) {}
+
+ private long getCurrentIntervalMillis() {
+ return Math.min(mMovingAverageIntervalMillis,
+ getElapsedRealTime() - mElapsedTimeStartedReading);
+ }
}
diff --git a/services/core/java/com/android/server/sensorprivacy/SensorPrivacyService.java b/services/core/java/com/android/server/sensorprivacy/SensorPrivacyService.java
index 3c779f387673..c354f116af5f 100644
--- a/services/core/java/com/android/server/sensorprivacy/SensorPrivacyService.java
+++ b/services/core/java/com/android/server/sensorprivacy/SensorPrivacyService.java
@@ -25,6 +25,7 @@ import static android.app.AppOpsManager.MODE_IGNORED;
import static android.app.AppOpsManager.OP_CAMERA;
import static android.app.AppOpsManager.OP_PHONE_CALL_CAMERA;
import static android.app.AppOpsManager.OP_PHONE_CALL_MICROPHONE;
+import static android.app.AppOpsManager.OP_RECEIVE_AMBIENT_TRIGGER_AUDIO;
import static android.app.AppOpsManager.OP_RECORD_AUDIO;
import static android.content.Intent.EXTRA_PACKAGE_NAME;
import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
@@ -1067,6 +1068,10 @@ public final class SensorPrivacyService extends SystemService {
mAppOpsRestrictionToken);
mAppOpsManagerInternal.setGlobalRestriction(OP_PHONE_CALL_MICROPHONE, enabled,
mAppOpsRestrictionToken);
+ // We don't show the dialog for RECEIVE_SOUNDTRIGGER_AUDIO, but still want to
+ // restrict it when the microphone is disabled
+ mAppOpsManagerInternal.setGlobalRestriction(OP_RECEIVE_AMBIENT_TRIGGER_AUDIO,
+ enabled, mAppOpsRestrictionToken);
break;
case CAMERA:
mAppOpsManagerInternal.setGlobalRestriction(OP_CAMERA, enabled,
diff --git a/services/core/java/com/android/server/soundtrigger_middleware/SoundTriggerMiddlewarePermission.java b/services/core/java/com/android/server/soundtrigger_middleware/SoundTriggerMiddlewarePermission.java
index 24eb0ebe3311..6318a99fc9a2 100644
--- a/services/core/java/com/android/server/soundtrigger_middleware/SoundTriggerMiddlewarePermission.java
+++ b/services/core/java/com/android/server/soundtrigger_middleware/SoundTriggerMiddlewarePermission.java
@@ -42,6 +42,9 @@ import android.os.IBinder;
import android.os.RemoteException;
import android.os.ServiceSpecificException;
+import com.android.server.LocalServices;
+import com.android.server.pm.permission.LegacyPermissionManagerInternal;
+
import java.io.PrintWriter;
import java.util.Objects;
@@ -123,19 +126,8 @@ public class SoundTriggerMiddlewarePermission implements ISoundTriggerMiddleware
* Throws a {@link SecurityException} iff the originator has permission to receive data.
*/
void enforcePermissionsForDataDelivery(@NonNull Identity identity, @NonNull String reason) {
- // SoundTrigger data is treated the same as Hotword-source audio. This should incur the
- // HOTWORD op instead of the RECORD_AUDIO op. The RECORD_AUDIO permission is still required,
- // and since this is a data delivery check, soft denials aren't accepted.
- // TODO(b/212458940): Find a better approach for checking the permission that doesn't
- // require the client to know such details about the permissions logic.
- enforcePermissionForPreflight(mContext, identity, RECORD_AUDIO,
- /* allowSoftDenial= */ false);
- int hotwordOp = AppOpsManager.strOpToOp(AppOpsManager.OPSTR_RECORD_AUDIO_HOTWORD);
- mContext.getSystemService(AppOpsManager.class).noteOpNoThrow(hotwordOp, identity.uid,
- identity.packageName, identity.attributionTag, reason);
-
- enforcePermissionForDataDelivery(mContext, identity, CAPTURE_AUDIO_HOTWORD,
- reason);
+ enforceSoundTriggerRecordAudioPermissionForDataDelivery(identity, reason);
+ enforcePermissionForDataDelivery(mContext, identity, CAPTURE_AUDIO_HOTWORD, reason);
}
/**
@@ -159,6 +151,19 @@ public class SoundTriggerMiddlewarePermission implements ISoundTriggerMiddleware
}
}
+ private static void enforceSoundTriggerRecordAudioPermissionForDataDelivery(
+ @NonNull Identity identity, @NonNull String reason) {
+ LegacyPermissionManagerInternal lpmi =
+ LocalServices.getService(LegacyPermissionManagerInternal.class);
+ final int status = lpmi.checkSoundTriggerRecordAudioPermissionForDataDelivery(identity.uid,
+ identity.packageName, identity.attributionTag, reason);
+ if (status != PermissionChecker.PERMISSION_GRANTED) {
+ throw new SecurityException(
+ String.format("Failed to obtain permission RECORD_AUDIO for identity %s",
+ ObjectPrinter.print(identity, 16)));
+ }
+ }
+
/**
* Throws a {@link SecurityException} if originator permanently doesn't have the given
* permission.
diff --git a/services/core/java/com/android/server/stats/pull/StatsPullAtomService.java b/services/core/java/com/android/server/stats/pull/StatsPullAtomService.java
index 977f6fd7b528..06646d30eb7b 100644
--- a/services/core/java/com/android/server/stats/pull/StatsPullAtomService.java
+++ b/services/core/java/com/android/server/stats/pull/StatsPullAtomService.java
@@ -4366,7 +4366,8 @@ public class StatsPullAtomService extends SystemService {
}
RkpErrorStats atom = atomWrapper.payload.getRkpErrorStats();
pulledData.add(FrameworkStatsLog.buildStatsEvent(
- FrameworkStatsLog.RKP_ERROR_STATS, atom.rkpError, atomWrapper.count));
+ FrameworkStatsLog.RKP_ERROR_STATS, atom.rkpError, atomWrapper.count,
+ atom.security_level));
}
return StatsManager.PULL_SUCCESS;
}
diff --git a/services/core/java/com/android/server/vcn/util/PersistableBundleUtils.java b/services/core/java/com/android/server/vcn/util/PersistableBundleUtils.java
index 08e8eebb8740..999d4064c951 100644
--- a/services/core/java/com/android/server/vcn/util/PersistableBundleUtils.java
+++ b/services/core/java/com/android/server/vcn/util/PersistableBundleUtils.java
@@ -23,6 +23,8 @@ import android.os.PersistableBundle;
import com.android.internal.util.HexDump;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
@@ -296,6 +298,30 @@ public class PersistableBundleUtils {
}
/**
+ * Converts a PersistableBundle into a disk-stable byte array format
+ *
+ * @param bundle the PersistableBundle to be converted to a disk-stable format
+ * @return the byte array representation of the PersistableBundle
+ */
+ @Nullable
+ public static byte[] toDiskStableBytes(@NonNull PersistableBundle bundle) throws IOException {
+ final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+ bundle.writeToStream(outputStream);
+ return outputStream.toByteArray();
+ }
+
+ /**
+ * Converts from a disk-stable byte array format to a PersistableBundle
+ *
+ * @param bytes the disk-stable byte array
+ * @return the PersistableBundle parsed from this byte array.
+ */
+ public static PersistableBundle fromDiskStableBytes(@NonNull byte[] bytes) throws IOException {
+ final ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
+ return PersistableBundle.readFromStream(inputStream);
+ }
+
+ /**
* Ensures safe reading and writing of {@link PersistableBundle}s to and from disk.
*
* <p>This class will enforce exclusion between reads and writes using the standard semantics of
diff --git a/services/core/java/com/android/server/wm/ActivityClientController.java b/services/core/java/com/android/server/wm/ActivityClientController.java
index d7a0ca0231d1..6113af45d6be 100644
--- a/services/core/java/com/android/server/wm/ActivityClientController.java
+++ b/services/core/java/com/android/server/wm/ActivityClientController.java
@@ -246,6 +246,18 @@ class ActivityClientController extends IActivityClientController.Stub {
}
@Override
+ public void activityLocalRelaunch(IBinder token) {
+ final long origId = Binder.clearCallingIdentity();
+ synchronized (mGlobalLock) {
+ final ActivityRecord r = ActivityRecord.forTokenLocked(token);
+ if (r != null) {
+ r.startRelaunching();
+ }
+ }
+ Binder.restoreCallingIdentity(origId);
+ }
+
+ @Override
public void activityRelaunched(IBinder token) {
final long origId = Binder.clearCallingIdentity();
synchronized (mGlobalLock) {
diff --git a/services/core/java/com/android/server/wm/ActivityInterceptorCallback.java b/services/core/java/com/android/server/wm/ActivityInterceptorCallback.java
index 34483957ca12..48e6f972fc8e 100644
--- a/services/core/java/com/android/server/wm/ActivityInterceptorCallback.java
+++ b/services/core/java/com/android/server/wm/ActivityInterceptorCallback.java
@@ -59,7 +59,6 @@ public abstract class ActivityInterceptorCallback {
@IntDef(suffix = { "_ORDERED_ID" }, value = {
FIRST_ORDERED_ID,
PERMISSION_POLICY_ORDERED_ID,
- INTENT_RESOLVER_ORDERED_ID,
VIRTUAL_DEVICE_SERVICE_ORDERED_ID,
DREAM_MANAGER_ORDERED_ID,
LAST_ORDERED_ID // Update this when adding new ids
@@ -78,11 +77,6 @@ public abstract class ActivityInterceptorCallback {
public static final int PERMISSION_POLICY_ORDERED_ID = 1;
/**
- * The identifier for {@link com.android.server.pm.IntentResolverInterceptor}.
- */
- public static final int INTENT_RESOLVER_ORDERED_ID = 2;
-
- /**
* The identifier for {@link com.android.server.companion.virtual.VirtualDeviceManagerService}
* interceptor.
*/
diff --git a/services/core/java/com/android/server/wm/ActivityRecord.java b/services/core/java/com/android/server/wm/ActivityRecord.java
index d19bfa182914..f4d215e5f2f1 100644
--- a/services/core/java/com/android/server/wm/ActivityRecord.java
+++ b/services/core/java/com/android/server/wm/ActivityRecord.java
@@ -873,7 +873,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A
boolean mEnteringAnimation;
boolean mOverrideTaskTransition;
- boolean mDismissKeyguardIfInsecure;
+ boolean mDismissKeyguard;
boolean mAppStopped;
// A hint to override the window specified rotation animation, or -1 to use the window specified
@@ -1987,7 +1987,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A
}
mOverrideTaskTransition = options.getOverrideTaskTransition();
- mDismissKeyguardIfInsecure = options.getDismissKeyguardIfInsecure();
+ mDismissKeyguard = options.getDismissKeyguard();
}
ColorDisplayService.ColorDisplayServiceInternal cds = LocalServices.getService(
@@ -5076,13 +5076,15 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A
// still check DC#okToAnimate again if the transition animation is fine to apply.
// TODO(new-app-transition): Rewrite this logic using WM Shell.
final boolean recentsAnimating = isAnimating(PARENTS, ANIMATION_TYPE_RECENTS);
+ final boolean isEnteringPipWithoutVisibleChange = mWaitForEnteringPinnedMode
+ && mVisible == visible;
if (okToAnimate(true /* ignoreFrozen */, canTurnScreenOn())
&& (appTransition.isTransitionSet()
|| (recentsAnimating && !isActivityTypeHome()))
- // If the visibility change during enter PIP, we don't want to include it in app
- // transition to affect the animation theme, because the Pip organizer will animate
- // the entering PIP instead.
- && !mWaitForEnteringPinnedMode) {
+ // If the visibility is not changed during enter PIP, we don't want to include it in
+ // app transition to affect the animation theme, because the Pip organizer will
+ // animate the entering PIP instead.
+ && !isEnteringPipWithoutVisibleChange) {
if (visible) {
displayContent.mOpeningApps.add(this);
mEnteringAnimation = true;
@@ -6324,8 +6326,10 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A
mSharedStartingData != null ? mSharedStartingData.mAssociatedTask : null;
if (associatedTask == null) {
removeStartingWindow();
- } else if (associatedTask.getActivity(
- r -> r.mVisibleRequested && !r.firstWindowDrawn) == null) {
+ } else if (associatedTask.getActivity(r -> r.mVisibleRequested && !r.firstWindowDrawn
+ // Don't block starting window removal if an Activity can't be a starting window
+ // target.
+ && r.mSharedStartingData != null) == null) {
// The last drawn activity may not be the one that owns the starting window.
final ActivityRecord r = associatedTask.topActivityContainsStartingWindow();
if (r != null) {
@@ -7709,7 +7713,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A
if (isFixedOrientationLetterboxAllowed || mCompatDisplayInsets != null
// In fullscreen, can be letterboxed for aspect ratio.
|| !inMultiWindowMode()) {
- updateResolvedBoundsHorizontalPosition(newParentConfiguration);
+ updateResolvedBoundsPosition(newParentConfiguration);
}
if (mVisibleRequested) {
@@ -7812,39 +7816,61 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A
}
/**
- * Adjusts horizontal position of resolved bounds if they doesn't fill the parent using gravity
+ * Adjusts position of resolved bounds if they doesn't fill the parent using gravity
* requested in the config or via an ADB command. For more context see {@link
- * LetterboxUiController#getHorizontalPositionMultiplier(Configuration)}.
+ * LetterboxUiController#getHorizontalPositionMultiplier(Configuration)} and
+ * {@link LetterboxUiController#getVerticalPositionMultiplier(Configuration)}
*/
- private void updateResolvedBoundsHorizontalPosition(Configuration newParentConfiguration) {
+ private void updateResolvedBoundsPosition(Configuration newParentConfiguration) {
final Configuration resolvedConfig = getResolvedOverrideConfiguration();
final Rect resolvedBounds = resolvedConfig.windowConfiguration.getBounds();
final Rect screenResolvedBounds =
mSizeCompatBounds != null ? mSizeCompatBounds : resolvedBounds;
final Rect parentAppBounds = newParentConfiguration.windowConfiguration.getAppBounds();
final Rect parentBounds = newParentConfiguration.windowConfiguration.getBounds();
- if (resolvedBounds.isEmpty() || parentBounds.width() == screenResolvedBounds.width()) {
+ if (resolvedBounds.isEmpty()) {
return;
}
-
+ // Horizontal position
int offsetX = 0;
- if (screenResolvedBounds.width() >= parentAppBounds.width()) {
- // If resolved bounds overlap with insets, center within app bounds.
- offsetX = getHorizontalCenterOffset(
- parentAppBounds.width(), screenResolvedBounds.width());
- } else {
- float positionMultiplier =
- mLetterboxUiController.getHorizontalPositionMultiplier(newParentConfiguration);
- offsetX = (int) Math.ceil((parentAppBounds.width() - screenResolvedBounds.width())
- * positionMultiplier);
+ if (parentBounds.width() != screenResolvedBounds.width()) {
+ if (screenResolvedBounds.width() >= parentAppBounds.width()) {
+ // If resolved bounds overlap with insets, center within app bounds.
+ offsetX = getCenterOffset(
+ parentAppBounds.width(), screenResolvedBounds.width());
+ } else {
+ float positionMultiplier =
+ mLetterboxUiController.getHorizontalPositionMultiplier(
+ newParentConfiguration);
+ offsetX = (int) Math.ceil((parentAppBounds.width() - screenResolvedBounds.width())
+ * positionMultiplier);
+ }
+ }
+
+ // Vertical position
+ int offsetY = 0;
+ if (parentBounds.height() != screenResolvedBounds.height()) {
+
+ if (screenResolvedBounds.height() >= parentAppBounds.height()) {
+ // If resolved bounds overlap with insets, center within app bounds.
+ offsetY = getCenterOffset(
+ parentAppBounds.height(), screenResolvedBounds.height());
+ } else {
+ float positionMultiplier =
+ mLetterboxUiController.getVerticalPositionMultiplier(
+ newParentConfiguration);
+ offsetY = (int) Math.ceil((parentAppBounds.height() - screenResolvedBounds.height())
+ * positionMultiplier);
+ }
}
if (mSizeCompatBounds != null) {
- mSizeCompatBounds.offset(offsetX, 0 /* offsetY */);
+ mSizeCompatBounds.offset(offsetX , offsetY);
+ final int dy = mSizeCompatBounds.top - resolvedBounds.top;
final int dx = mSizeCompatBounds.left - resolvedBounds.left;
- offsetBounds(resolvedConfig, dx, 0 /* offsetY */);
+ offsetBounds(resolvedConfig, dx, dy);
} else {
- offsetBounds(resolvedConfig, offsetX, 0 /* offsetY */);
+ offsetBounds(resolvedConfig, offsetX, offsetY);
}
// Since bounds has changed, the configuration needs to be computed accordingly.
@@ -7968,20 +7994,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A
// orientation with insets applied.
return;
}
- // Not using Task#isResizeable() or ActivityRecord#isResizeable() directly because app
- // compatibility testing showed that android:supportsPictureInPicture="true" alone is not
- // sufficient signal for not letterboxing an app.
- // TODO(214602463): Remove multi-window check since orientation and aspect ratio
- // restrictions should always be applied in multi-window.
- final boolean isResizeable = task != null
- // Activity should be resizable if the task is.
- ? task.isResizeable(/* checkPictureInPictureSupport */ false)
- || isResizeable(/* checkPictureInPictureSupport */ false)
- : isResizeable(/* checkPictureInPictureSupport */ false);
- if (WindowConfiguration.inMultiWindowMode(windowingMode) && isResizeable) {
- // Ignore orientation request for resizable apps in multi window.
- return;
- }
+
if (windowingMode == WINDOWING_MODE_PINNED) {
// PiP bounds have higher priority than the requested orientation. Otherwise the
// activity may be squeezed into a small piece.
@@ -8059,14 +8072,6 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A
mIsAspectRatioApplied = applyAspectRatio(resolvedBounds, containingBoundsWithInsets,
containingBounds, desiredAspectRatio, true);
- // Vertically center if orientation is landscape. Center within parent bounds with insets
- // to ensure that insets do not trim height. Bounds will later be horizontally centered in
- // {@link updateResolvedBoundsHorizontalPosition()} regardless of orientation.
- if (forcedOrientation == ORIENTATION_LANDSCAPE) {
- final int offsetY = parentBoundsWithInsets.centerY() - resolvedBounds.centerY();
- resolvedBounds.offset(0, offsetY);
- }
-
if (mCompatDisplayInsets != null) {
mCompatDisplayInsets.getBoundsByRotation(
mTmpBounds, newParentConfig.windowConfiguration.getRotation());
@@ -8089,10 +8094,9 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A
/**
* Resolves aspect ratio restrictions for an activity. If the bounds are restricted by
- * aspect ratio, the position will be adjusted later in {@link
- * updateResolvedBoundsHorizontalPosition} within parent's app bounds to balance the visual
- * appearance. The policy of aspect ratio has higher priority than the requested override
- * bounds.
+ * aspect ratio, the position will be adjusted later in {@link #updateResolvedBoundsPosition
+ * within parent's app bounds to balance the visual appearance. The policy of aspect ratio has
+ * higher priority than the requested override bounds.
*/
private void resolveAspectRatioRestriction(Configuration newParentConfiguration) {
final Configuration resolvedConfig = getResolvedOverrideConfiguration();
@@ -8104,7 +8108,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A
mTmpBounds.setEmpty();
mIsAspectRatioApplied = applyAspectRatio(mTmpBounds, parentAppBounds, parentBounds);
// If the out bounds is not empty, it means the activity cannot fill parent's app bounds,
- // then they should be aligned later in #updateResolvedBoundsHorizontalPosition().
+ // then they should be aligned later in #updateResolvedBoundsPosition()
if (!mTmpBounds.isEmpty()) {
resolvedBounds.set(mTmpBounds);
}
@@ -8238,22 +8242,11 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A
forAllWindows(WindowState::updateGlobalScale, false /* traverseTopToBottom */);
}
- // Vertically center within parent (bounds) - this is a UX choice and exclude the horizontal
- // decor if needed. Horizontal position is adjusted in
- // updateResolvedBoundsHorizontalPosition.
+ // The position will be later adjusted in updateResolvedBoundsPosition.
// Above coordinates are in "@" space, now place "*" and "#" to screen space.
final boolean fillContainer = resolvedBounds.equals(containingBounds);
final int screenPosX = fillContainer ? containerBounds.left : containerAppBounds.left;
- // If the activity is not in size compat mode, calculate vertical centering
- // from the container and resolved bounds.
- // If the activity is in size compat mode, calculate vertical centering
- // from the container and size compat bounds.
- // The container bounds contain the parent bounds offset in the display, for
- // example when an activity is in the lower split of split screen.
- final int screenPosY = (mSizeCompatBounds == null
- ? (containerBounds.height() - resolvedBounds.height()) / 2
- : (containerBounds.height() - mSizeCompatBounds.height()) / 2)
- + containerBounds.top;
+ final int screenPosY = fillContainer ? containerBounds.top : containerAppBounds.top;
if (screenPosX != 0 || screenPosY != 0) {
if (mSizeCompatBounds != null) {
@@ -8313,9 +8306,9 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A
return true;
}
- /** @return The horizontal offset of putting the content in the center of viewport. */
- private static int getHorizontalCenterOffset(int viewportW, int contentW) {
- return (int) ((viewportW - contentW + 1) * 0.5f);
+ /** @return The horizontal / vertical offset of putting the content in the center of viewport.*/
+ private static int getCenterOffset(int viewportDim, int contentDim) {
+ return (int) ((viewportDim - contentDim + 1) * 0.5f);
}
private static void offsetBounds(Configuration inOutConfig, int offsetX, int offsetY) {
@@ -9578,7 +9571,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A
outBounds.bottom = dH;
outBounds.right = (int) ((float) dH * dH / dW);
}
- outBounds.offset(getHorizontalCenterOffset(mWidth, outBounds.width()), 0 /* dy */);
+ outBounds.offset(getCenterOffset(mWidth, outBounds.width()), 0 /* dy */);
}
outAppBounds.set(outBounds);
diff --git a/services/core/java/com/android/server/wm/ActivityStartController.java b/services/core/java/com/android/server/wm/ActivityStartController.java
index 9771b347cfb1..4e2d1aa803af 100644
--- a/services/core/java/com/android/server/wm/ActivityStartController.java
+++ b/services/core/java/com/android/server/wm/ActivityStartController.java
@@ -528,6 +528,8 @@ public class ActivityStartController {
.setRequestCode(-1)
.setCallingUid(callingUid)
.setCallingPid(callingPid)
+ .setRealCallingUid(callingUid)
+ .setRealCallingPid(callingPid)
.setUserId(caller != null ? caller.mUserId : mService.getCurrentUserId())
.execute();
}
diff --git a/services/core/java/com/android/server/wm/ActivityStarter.java b/services/core/java/com/android/server/wm/ActivityStarter.java
index 85305cc6403f..0d447e34502e 100644
--- a/services/core/java/com/android/server/wm/ActivityStarter.java
+++ b/services/core/java/com/android/server/wm/ActivityStarter.java
@@ -1674,6 +1674,7 @@ class ActivityStarter {
private @Nullable Task handleStartResult(@NonNull ActivityRecord started,
ActivityOptions options, int result, Transition newTransition,
RemoteTransition remoteTransition) {
+ final boolean userLeaving = mSupervisor.mUserLeaving;
mSupervisor.mUserLeaving = false;
final Task currentRootTask = started.getRootTask();
final Task startedActivityRootTask =
@@ -1747,7 +1748,7 @@ class ActivityStarter {
// until after we launched to identify the relevant activity.
transitionController.setTransientLaunch(mLastStartActivityRecord, mPriorAboveTask);
}
- if (!mSupervisor.mUserLeaving) {
+ if (!userLeaving) {
// no-user-leaving implies not entering PiP.
transitionController.setCanPipOnFinish(false /* canPipOnFinish */);
}
diff --git a/services/core/java/com/android/server/wm/AppTransitionController.java b/services/core/java/com/android/server/wm/AppTransitionController.java
index 05321df16d00..ad3bb2dcc322 100644
--- a/services/core/java/com/android/server/wm/AppTransitionController.java
+++ b/services/core/java/com/android/server/wm/AppTransitionController.java
@@ -673,11 +673,16 @@ public class AppTransitionController {
"Override with TaskFragment remote animation for transit=%s",
AppTransition.appTransitionOldToString(transit));
+ final int organizerUid = mDisplayContent.mAtmService.mTaskFragmentOrganizerController
+ .getTaskFragmentOrganizerUid(organizer);
+ final boolean shouldDisableInputForRemoteAnimation = !task.isFullyTrustedEmbedding(
+ organizerUid);
final RemoteAnimationController remoteAnimationController =
mDisplayContent.mAppTransition.getRemoteAnimationController();
- if (remoteAnimationController != null) {
+ if (shouldDisableInputForRemoteAnimation && remoteAnimationController != null) {
// We are going to use client-driven animation, Disable all input on activity windows
- // during the animation to ensure it is safe to allow client to animate the surfaces.
+ // during the animation (unless it is fully trusted) to ensure it is safe to allow
+ // client to animate the surfaces.
// This is needed for all activity windows in the animation Task.
remoteAnimationController.setOnRemoteAnimationReady(() -> {
final Consumer<ActivityRecord> updateActivities =
@@ -904,7 +909,11 @@ public class AppTransitionController {
// We cannot promote the animation on Task's parent when the task is in
// clearing task in case the animating get stuck when performing the opening
// task that behind it.
- || (current.asTask() != null && current.asTask().mInRemoveTask)) {
+ || (current.asTask() != null && current.asTask().mInRemoveTask)
+ // We cannot promote the animation to changing window. This may happen when an
+ // activity is open in a TaskFragment that is resizing, while the existing
+ // activity in the TaskFragment is reparented to another TaskFragment.
+ || parent.isChangingAppTransition()) {
canPromote = false;
} else {
// In case a descendant of the parent belongs to the other group, we cannot promote
diff --git a/services/core/java/com/android/server/wm/Dimmer.java b/services/core/java/com/android/server/wm/Dimmer.java
index 029056ac26fb..e7ab63eab202 100644
--- a/services/core/java/com/android/server/wm/Dimmer.java
+++ b/services/core/java/com/android/server/wm/Dimmer.java
@@ -50,11 +50,16 @@ class Dimmer {
}
@Override
- public SurfaceControl.Transaction getPendingTransaction() {
+ public SurfaceControl.Transaction getSyncTransaction() {
return mHost.getSyncTransaction();
}
@Override
+ public SurfaceControl.Transaction getPendingTransaction() {
+ return mHost.getPendingTransaction();
+ }
+
+ @Override
public void commitPendingTransaction() {
mHost.commitPendingTransaction();
}
@@ -105,7 +110,7 @@ class Dimmer {
void removeSurface() {
if (mDimLayer != null && mDimLayer.isValid()) {
- getPendingTransaction().remove(mDimLayer);
+ getSyncTransaction().remove(mDimLayer);
}
mDimLayer = null;
}
diff --git a/services/core/java/com/android/server/wm/DisplayContent.java b/services/core/java/com/android/server/wm/DisplayContent.java
index dcd8f0fb4db2..1f73a784932e 100644
--- a/services/core/java/com/android/server/wm/DisplayContent.java
+++ b/services/core/java/com/android/server/wm/DisplayContent.java
@@ -556,7 +556,8 @@ class DisplayContent extends RootDisplayArea implements WindowManagerPolicy.Disp
final FixedRotationTransitionListener mFixedRotationTransitionListener =
new FixedRotationTransitionListener();
- private PhysicalDisplaySwitchTransitionLauncher mDisplaySwitchTransitionLauncher;
+ private final PhysicalDisplaySwitchTransitionLauncher mDisplaySwitchTransitionLauncher;
+ final RemoteDisplayChangeController mRemoteDisplayChangeController;
/** Windows added since {@link #mCurrentFocus} was set to null. Used for ANR blaming. */
final ArrayList<WindowState> mWinAddedSinceNullFocus = new ArrayList<>();
@@ -1052,6 +1053,7 @@ class DisplayContent extends RootDisplayArea implements WindowManagerPolicy.Disp
mUnknownAppVisibilityController = new UnknownAppVisibilityController(mWmService, this);
mDisplaySwitchTransitionLauncher = new PhysicalDisplaySwitchTransitionLauncher(this,
mTransitionController);
+ mRemoteDisplayChangeController = new RemoteDisplayChangeController(mWmService, mDisplayId);
final InputChannel inputChannel = mWmService.mInputManager.monitorInput(
"PointerEventDispatcher" + mDisplayId, mDisplayId);
@@ -1433,7 +1435,7 @@ class DisplayContent extends RootDisplayArea implements WindowManagerPolicy.Disp
if (!isReady()) {
return;
}
- if (mDisplayRotation.isWaitingForRemoteRotation()) {
+ if (mRemoteDisplayChangeController.isWaitingForRemoteDisplayChange()) {
return;
}
@@ -1533,8 +1535,8 @@ class DisplayContent extends RootDisplayArea implements WindowManagerPolicy.Disp
config = new Configuration();
computeScreenConfiguration(config);
} else if (!(mTransitionController.isCollecting(this)
- // If waiting for a remote rotation, don't prematurely update configuration.
- || mDisplayRotation.isWaitingForRemoteRotation())) {
+ // If waiting for a remote display change, don't prematurely update configuration.
+ || mRemoteDisplayChangeController.isWaitingForRemoteDisplayChange())) {
// No obvious action we need to take, but if our current state mismatches the
// activity manager's, update it, disregarding font scale, which should remain set
// to the value of the previous configuration.
@@ -1596,7 +1598,7 @@ class DisplayContent extends RootDisplayArea implements WindowManagerPolicy.Disp
boolean isSyncFinished() {
// Do not consider children because if they are requested to be synced, they should be
// added to sync group explicitly.
- return !mDisplayRotation.isWaitingForRemoteRotation();
+ return !mRemoteDisplayChangeController.isWaitingForRemoteDisplayChange();
}
/**
@@ -1829,8 +1831,8 @@ class DisplayContent extends RootDisplayArea implements WindowManagerPolicy.Disp
sendNewConfiguration();
return;
}
- if (mDisplayRotation.isWaitingForRemoteRotation()) {
- // There is pending rotation change to apply.
+ if (mRemoteDisplayChangeController.isWaitingForRemoteDisplayChange()) {
+ // There is pending display change to apply.
return;
}
// The orientation of display is not changed.
@@ -2210,9 +2212,9 @@ class DisplayContent extends RootDisplayArea implements WindowManagerPolicy.Disp
final float density = mDisplayMetrics.density;
outConfig.screenWidthDp = (int) (mDisplayPolicy.getConfigDisplayWidth(dw, dh, rotation,
- uiMode, displayCutout) / density);
+ uiMode, displayCutout) / density + 0.5f);
outConfig.screenHeightDp = (int) (mDisplayPolicy.getConfigDisplayHeight(dw, dh, rotation,
- uiMode, displayCutout) / density);
+ uiMode, displayCutout) / density + 0.5f);
outConfig.compatScreenWidthDp = (int) (outConfig.screenWidthDp / mCompatibleScreenScale);
outConfig.compatScreenHeightDp = (int) (outConfig.screenHeightDp / mCompatibleScreenScale);
@@ -2758,6 +2760,7 @@ class DisplayContent extends RootDisplayArea implements WindowManagerPolicy.Disp
private void updateBaseDisplayMetricsIfNeeded() {
// Get real display metrics without overrides from WM.
mWmService.mDisplayManagerInternal.getNonOverrideDisplayInfo(mDisplayId, mDisplayInfo);
+ final int currentRotation = getRotation();
final int orientation = mDisplayInfo.rotation;
final boolean rotated = (orientation == ROTATION_90 || orientation == ROTATION_270);
final int newWidth = rotated ? mDisplayInfo.logicalHeight : mDisplayInfo.logicalWidth;
@@ -2818,7 +2821,8 @@ class DisplayContent extends RootDisplayArea implements WindowManagerPolicy.Disp
reconfigureDisplayLocked();
if (physicalDisplayChanged) {
- mDisplaySwitchTransitionLauncher.onDisplayUpdated();
+ mDisplaySwitchTransitionLauncher.onDisplayUpdated(currentRotation, getRotation(),
+ getDisplayAreaInfo());
}
}
}
diff --git a/services/core/java/com/android/server/wm/DisplayPolicy.java b/services/core/java/com/android/server/wm/DisplayPolicy.java
index c4e50795fb93..daeba967ec76 100644
--- a/services/core/java/com/android/server/wm/DisplayPolicy.java
+++ b/services/core/java/com/android/server/wm/DisplayPolicy.java
@@ -1206,7 +1206,8 @@ public class DisplayPolicy {
if (attrs.providesInsetsTypes != null) {
for (@InternalInsetsType int insetsType : attrs.providesInsetsTypes) {
final TriConsumer<DisplayFrames, WindowContainer, Rect> imeFrameProvider =
- (displayFrames, windowContainer, inOutFrame) -> {
+ win.getAttrs().providedInternalImeInsets != null
+ ? (displayFrames, windowContainer, inOutFrame) -> {
final Insets[] providedInternalImeInsets =
win.getLayoutingAttrs(displayFrames.mRotation)
.providedInternalImeInsets;
@@ -1215,7 +1216,7 @@ public class DisplayPolicy {
&& providedInternalImeInsets[insetsType] != null) {
inOutFrame.inset(providedInternalImeInsets[insetsType]);
}
- };
+ } : null;
switch (insetsType) {
case ITYPE_STATUS_BAR:
mStatusBarAlt = win;
@@ -1234,17 +1235,18 @@ public class DisplayPolicy {
mExtraNavBarAltPosition = getAltBarPosition(attrs);
break;
}
- mDisplayContent.setInsetProvider(insetsType, win, (displayFrames,
- windowContainer, inOutFrame) -> {
- final Insets[] providedInternalInsets = win.getLayoutingAttrs(
- displayFrames.mRotation).providedInternalInsets;
- if (providedInternalInsets != null
- && providedInternalInsets.length > insetsType
- && providedInternalInsets[insetsType] != null) {
- inOutFrame.inset(providedInternalInsets[insetsType]);
- }
- inOutFrame.inset(win.mGivenContentInsets);
- }, imeFrameProvider);
+ mDisplayContent.setInsetProvider(insetsType, win,
+ win.getAttrs().providedInternalInsets != null ? (displayFrames,
+ windowContainer, inOutFrame) -> {
+ final Insets[] providedInternalInsets = win.getLayoutingAttrs(
+ displayFrames.mRotation).providedInternalInsets;
+ if (providedInternalInsets != null
+ && providedInternalInsets.length > insetsType
+ && providedInternalInsets[insetsType] != null) {
+ inOutFrame.inset(providedInternalInsets[insetsType]);
+ }
+ inOutFrame.inset(win.mGivenContentInsets);
+ } : null, imeFrameProvider);
mInsetsSourceWindowsExceptIme.add(win);
}
}
@@ -2423,7 +2425,9 @@ public class DisplayPolicy {
private int updateSystemBarsLw(WindowState win, int disableFlags) {
final TaskDisplayArea defaultTaskDisplayArea = mDisplayContent.getDefaultTaskDisplayArea();
final boolean multiWindowTaskVisible =
- defaultTaskDisplayArea.isRootTaskVisible(WINDOWING_MODE_MULTI_WINDOW);
+ defaultTaskDisplayArea.getRootTask(task -> task.isVisible()
+ && task.getTopLeafTask().getWindowingMode() == WINDOWING_MODE_MULTI_WINDOW)
+ != null;
final boolean freeformRootTaskVisible =
defaultTaskDisplayArea.isRootTaskVisible(WINDOWING_MODE_FREEFORM);
diff --git a/services/core/java/com/android/server/wm/DisplayRotation.java b/services/core/java/com/android/server/wm/DisplayRotation.java
index 03e1429f1bf1..86ed44e39425 100644
--- a/services/core/java/com/android/server/wm/DisplayRotation.java
+++ b/services/core/java/com/android/server/wm/DisplayRotation.java
@@ -51,14 +51,12 @@ import android.content.res.Resources;
import android.database.ContentObserver;
import android.hardware.power.Boost;
import android.os.Handler;
-import android.os.RemoteException;
import android.os.SystemProperties;
import android.os.UserHandle;
import android.provider.Settings;
import android.util.Slog;
import android.util.TimeUtils;
import android.util.proto.ProtoOutputStream;
-import android.view.IDisplayWindowRotationCallback;
import android.view.IWindowManager;
import android.view.Surface;
import android.window.TransitionRequestInfo;
@@ -67,7 +65,6 @@ import android.window.WindowContainerTransaction;
import com.android.internal.R;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.protolog.common.ProtoLog;
-import com.android.internal.util.function.pooled.PooledLambda;
import com.android.server.LocalServices;
import com.android.server.UiThread;
import com.android.server.policy.WindowManagerPolicy;
@@ -211,31 +208,6 @@ public class DisplayRotation {
private boolean mDemoHdmiRotationLock;
private boolean mDemoRotationLock;
- private static final int REMOTE_ROTATION_TIMEOUT_MS = 800;
-
- private boolean mIsWaitingForRemoteRotation = false;
-
- private final Runnable mDisplayRotationHandlerTimeout =
- new Runnable() {
- @Override
- public void run() {
- continueRotation(mRotation, null /* transaction */);
- }
- };
-
- private final IDisplayWindowRotationCallback mRemoteRotationCallback =
- new IDisplayWindowRotationCallback.Stub() {
- @Override
- public void continueRotateDisplay(int targetRotation,
- WindowContainerTransaction t) {
- synchronized (mService.getWindowManagerLock()) {
- mService.mH.sendMessage(PooledLambda.obtainMessage(
- DisplayRotation::continueRotation, DisplayRotation.this,
- targetRotation, t));
- }
- }
- };
-
DisplayRotation(WindowManagerService service, DisplayContent displayContent) {
this(service, displayContent, displayContent.getDisplayPolicy(),
service.mDisplayWindowSettings, service.mContext, service.getWindowManagerLock());
@@ -511,6 +483,7 @@ public class DisplayRotation {
final TransitionRequestInfo.DisplayChange change = wasCollecting ? null
: new TransitionRequestInfo.DisplayChange(mDisplayContent.getDisplayId(),
oldRotation, mRotation);
+
mDisplayContent.requestChangeTransitionIfNeeded(
ActivityInfo.CONFIG_WINDOW_CONFIGURATION, change);
if (wasCollecting) {
@@ -554,61 +527,45 @@ public class DisplayRotation {
return null;
}
- /**
- * A Remote rotation is when we are waiting for some registered (remote)
- * {@link IDisplayWindowRotationController} to calculate and return some hierarchy operations
- * to perform in sync with the rotation.
- */
- boolean isWaitingForRemoteRotation() {
- return mIsWaitingForRemoteRotation;
- }
-
private void startRemoteRotation(int fromRotation, int toRotation) {
- if (mService.mDisplayRotationController == null) {
- return;
- }
- mIsWaitingForRemoteRotation = true;
- try {
- mService.mDisplayRotationController.onRotateDisplay(mDisplayContent.getDisplayId(),
- fromRotation, toRotation, mRemoteRotationCallback);
- mService.mH.removeCallbacks(mDisplayRotationHandlerTimeout);
- mService.mH.postDelayed(mDisplayRotationHandlerTimeout, REMOTE_ROTATION_TIMEOUT_MS);
- } catch (RemoteException e) {
- mIsWaitingForRemoteRotation = false;
- return;
- }
+ mDisplayContent.mRemoteDisplayChangeController.performRemoteDisplayChange(
+ fromRotation, toRotation, null /* newDisplayAreaInfo */,
+ (appliedChange, transaction) -> {
+ final int newRotation = appliedChange != null
+ ? appliedChange.toRotation
+ // Timeout occurred, use old rotation
+ : fromRotation;
+ continueRotation(newRotation, transaction);
+ }
+ );
}
private void continueRotation(int targetRotation, WindowContainerTransaction t) {
- synchronized (mService.mGlobalLock) {
- if (targetRotation != mRotation || !mIsWaitingForRemoteRotation) {
- // Drop it, this is either coming from an outdated remote rotation; or, we've
- // already moved on.
- return;
- }
- mService.mH.removeCallbacks(mDisplayRotationHandlerTimeout);
- mIsWaitingForRemoteRotation = false;
+ if (targetRotation != mRotation) {
+ // Drop it, this is either coming from an outdated remote rotation; or, we've
+ // already moved on.
+ return;
+ }
- if (mDisplayContent.mTransitionController.isShellTransitionsEnabled()) {
- if (!mDisplayContent.mTransitionController.isCollecting()) {
- throw new IllegalStateException("Trying to rotate outside a transition");
- }
- mDisplayContent.mTransitionController.collect(mDisplayContent);
- // Go through all tasks and collect them before the rotation
- // TODO(shell-transitions): move collect() to onConfigurationChange once wallpaper
- // handling is synchronized.
- mDisplayContent.mTransitionController.collectForDisplayChange(mDisplayContent,
- null /* use collecting transition */);
+ if (mDisplayContent.mTransitionController.isShellTransitionsEnabled()) {
+ if (!mDisplayContent.mTransitionController.isCollecting()) {
+ throw new IllegalStateException("Trying to rotate outside a transition");
}
- mService.mAtmService.deferWindowLayout();
- try {
- mDisplayContent.sendNewConfiguration();
- if (t != null) {
- mService.mAtmService.mWindowOrganizerController.applyTransaction(t);
- }
- } finally {
- mService.mAtmService.continueWindowLayout();
+ mDisplayContent.mTransitionController.collect(mDisplayContent);
+ // Go through all tasks and collect them before the rotation
+ // TODO(shell-transitions): move collect() to onConfigurationChange once wallpaper
+ // handling is synchronized.
+ mDisplayContent.mTransitionController.collectForDisplayChange(mDisplayContent,
+ null /* use collecting transition */);
+ }
+ mService.mAtmService.deferWindowLayout();
+ try {
+ mDisplayContent.sendNewConfiguration();
+ if (t != null) {
+ mService.mAtmService.mWindowOrganizerController.applyTransaction(t);
}
+ } finally {
+ mService.mAtmService.continueWindowLayout();
}
}
diff --git a/services/core/java/com/android/server/wm/InputMonitor.java b/services/core/java/com/android/server/wm/InputMonitor.java
index ea72e12783c3..ce416ad89c95 100644
--- a/services/core/java/com/android/server/wm/InputMonitor.java
+++ b/services/core/java/com/android/server/wm/InputMonitor.java
@@ -416,8 +416,22 @@ final class InputMonitor {
final IBinder focusToken = focus != null ? focus.mInputChannelToken : null;
if (focusToken == null) {
+ if (recentsAnimationInputConsumer != null
+ && recentsAnimationInputConsumer.mWindowHandle != null
+ && mInputFocus == recentsAnimationInputConsumer.mWindowHandle.token) {
+ // Avoid removing input focus from recentsAnimationInputConsumer.
+ // When the recents animation input consumer has the input focus,
+ // mInputFocus does not match to mDisplayContent.mCurrentFocus. Making it to be
+ // a special case, that do not remove the input focus from it when
+ // mDisplayContent.mCurrentFocus is null. This special case should be removed
+ // once recentAnimationInputConsumer is removed.
+ return;
+ }
// When an app is focused, but its window is not showing yet, remove the input focus
- // from the current window.
+ // from the current window. This enforces the input focus to match
+ // mDisplayContent.mCurrentFocus. However, if more special cases are discovered that
+ // the input focus and mDisplayContent.mCurrentFocus are expected to mismatch,
+ // the whole logic of how and when to revoke focus needs to be checked.
if (mDisplayContent.mFocusedApp != null && mInputFocus != null) {
ProtoLog.v(WM_DEBUG_FOCUS_LIGHT, "App %s is focused,"
+ " but the window is not ready. Start a transaction to remove focus from"
diff --git a/services/core/java/com/android/server/wm/InsetsPolicy.java b/services/core/java/com/android/server/wm/InsetsPolicy.java
index 5c8cfffdd3b3..9e0d7b57264e 100644
--- a/services/core/java/com/android/server/wm/InsetsPolicy.java
+++ b/services/core/java/com/android/server/wm/InsetsPolicy.java
@@ -46,6 +46,7 @@ import android.annotation.Nullable;
import android.app.ActivityTaskManager;
import android.app.StatusBarManager;
import android.app.WindowConfiguration;
+import android.content.res.Resources;
import android.graphics.Rect;
import android.util.ArrayMap;
import android.util.IntArray;
@@ -123,14 +124,17 @@ class InsetsPolicy {
* Let remote insets controller control system bars regardless of other settings.
*/
private boolean mRemoteInsetsControllerControlsSystemBars;
+ private final boolean mHideNavBarForKeyboard;
private final float[] mTmpFloat9 = new float[9];
InsetsPolicy(InsetsStateController stateController, DisplayContent displayContent) {
mStateController = stateController;
mDisplayContent = displayContent;
mPolicy = displayContent.getDisplayPolicy();
- mRemoteInsetsControllerControlsSystemBars = mPolicy.getContext().getResources().getBoolean(
+ final Resources r = mPolicy.getContext().getResources();
+ mRemoteInsetsControllerControlsSystemBars = r.getBoolean(
R.bool.config_remoteInsetsControllerControlsSystemBars);
+ mHideNavBarForKeyboard = r.getBoolean(R.bool.config_hideNavBarForKeyboard);
}
boolean getRemoteInsetsControllerControlsSystemBars() {
@@ -428,13 +432,15 @@ class InsetsPolicy {
private InsetsState adjustVisibilityForIme(WindowState w, InsetsState originalState,
boolean copyState) {
if (w.mIsImWindow) {
- // Navigation bar insets is always visible to IME.
+ // If navigation bar is not hidden by IME, IME should always receive visible
+ // navigation bar insets.
+ final boolean navVisible = !mHideNavBarForKeyboard;
final InsetsSource originalNavSource = originalState.peekSource(ITYPE_NAVIGATION_BAR);
- if (originalNavSource != null && !originalNavSource.isVisible()) {
+ if (originalNavSource != null && originalNavSource.isVisible() != navVisible) {
final InsetsState state = copyState ? new InsetsState(originalState)
: originalState;
final InsetsSource navSource = new InsetsSource(originalNavSource);
- navSource.setVisible(true);
+ navSource.setVisible(navVisible);
state.addSource(navSource);
return state;
}
@@ -573,8 +579,9 @@ class InsetsPolicy {
private @Nullable InsetsControlTarget getNavControlTarget(@Nullable WindowState focusedWin,
boolean fake) {
final WindowState imeWin = mDisplayContent.mInputMethodWindow;
- if (imeWin != null && imeWin.isVisible()) {
- // Force showing navigation bar while IME is visible.
+ if (imeWin != null && imeWin.isVisible() && !mHideNavBarForKeyboard) {
+ // Force showing navigation bar while IME is visible and if navigation bar is not
+ // configured to be hidden by the IME.
return null;
}
if (!fake && isShowingTransientTypes(Type.navigationBars())) {
diff --git a/services/core/java/com/android/server/wm/InsetsSourceProvider.java b/services/core/java/com/android/server/wm/InsetsSourceProvider.java
index 9853d1304b14..358e93d89f64 100644
--- a/services/core/java/com/android/server/wm/InsetsSourceProvider.java
+++ b/services/core/java/com/android/server/wm/InsetsSourceProvider.java
@@ -82,6 +82,7 @@ abstract class InsetsSourceProvider {
private boolean mIsLeashReadyForDispatching;
private final Rect mSourceFrame = new Rect();
private final Rect mLastSourceFrame = new Rect();
+ private @NonNull Insets mInsetsHint = Insets.NONE;
private final Consumer<Transaction> mSetLeashPositionConsumer = t -> {
if (mControl != null) {
@@ -298,6 +299,7 @@ abstract class InsetsSourceProvider {
if (!insetsHint.equals(mControl.getInsetsHint())) {
changed = true;
mControl.setInsetsHint(insetsHint);
+ mInsetsHint = insetsHint;
}
mLastSourceFrame.set(mSource.getFrame());
}
@@ -433,8 +435,8 @@ abstract class InsetsSourceProvider {
final SurfaceControl leash = mAdapter.mCapturedLeash;
mControlTarget = target;
updateVisibility();
- mControl = new InsetsSourceControl(mSource.getType(), leash, surfacePosition,
- mSource.calculateInsets(mWindowContainer.getBounds(), true /* ignoreVisibility */));
+ mControl = new InsetsSourceControl(mSource.getType(), leash, surfacePosition, mInsetsHint);
+
ProtoLog.d(WM_DEBUG_WINDOW_INSETS,
"InsetsSource Control %s for target %s", mControl, mControlTarget);
}
diff --git a/services/core/java/com/android/server/wm/KeyguardController.java b/services/core/java/com/android/server/wm/KeyguardController.java
index 03ac7aafb482..4d971a9f52da 100644
--- a/services/core/java/com/android/server/wm/KeyguardController.java
+++ b/services/core/java/com/android/server/wm/KeyguardController.java
@@ -621,9 +621,7 @@ class KeyguardController {
mTopTurnScreenOnActivity = top;
}
- final boolean isKeyguardSecure = controller.mWindowManager.isKeyguardSecure(
- controller.mService.getCurrentUserId());
- if (top.mDismissKeyguardIfInsecure && mKeyguardShowing && !isKeyguardSecure) {
+ if (top.mDismissKeyguard && mKeyguardShowing) {
mKeyguardGoingAway = true;
} else if (top.canShowWhenLocked()) {
mTopOccludesActivity = top;
diff --git a/services/core/java/com/android/server/wm/Letterbox.java b/services/core/java/com/android/server/wm/Letterbox.java
index 40df02c176e5..61c09cd60413 100644
--- a/services/core/java/com/android/server/wm/Letterbox.java
+++ b/services/core/java/com/android/server/wm/Letterbox.java
@@ -72,7 +72,8 @@ public class Letterbox {
private final LetterboxSurface mFullWindowSurface = new LetterboxSurface("fullWindow");
private final LetterboxSurface[] mSurfaces = { mLeft, mTop, mRight, mBottom };
// Reachability gestures.
- private final IntConsumer mDoubleTapCallback;
+ private final IntConsumer mDoubleTapCallbackX;
+ private final IntConsumer mDoubleTapCallbackY;
/**
* Constructs a Letterbox.
@@ -86,7 +87,8 @@ public class Letterbox {
Supplier<Boolean> hasWallpaperBackgroundSupplier,
Supplier<Integer> blurRadiusSupplier,
Supplier<Float> darkScrimAlphaSupplier,
- IntConsumer doubleTapCallback) {
+ IntConsumer doubleTapCallbackX,
+ IntConsumer doubleTapCallbackY) {
mSurfaceControlFactory = surfaceControlFactory;
mTransactionFactory = transactionFactory;
mAreCornersRounded = areCornersRounded;
@@ -94,7 +96,8 @@ public class Letterbox {
mHasWallpaperBackgroundSupplier = hasWallpaperBackgroundSupplier;
mBlurRadiusSupplier = blurRadiusSupplier;
mDarkScrimAlphaSupplier = darkScrimAlphaSupplier;
- mDoubleTapCallback = doubleTapCallback;
+ mDoubleTapCallbackX = doubleTapCallbackX;
+ mDoubleTapCallbackY = doubleTapCallbackY;
}
/**
@@ -264,7 +267,8 @@ public class Letterbox {
@Override
public boolean onDoubleTapEvent(MotionEvent e) {
if (e.getAction() == MotionEvent.ACTION_UP) {
- mDoubleTapCallback.accept((int) e.getX());
+ mDoubleTapCallbackX.accept((int) e.getX());
+ mDoubleTapCallbackY.accept((int) e.getY());
return true;
}
return false;
diff --git a/services/core/java/com/android/server/wm/LetterboxConfiguration.java b/services/core/java/com/android/server/wm/LetterboxConfiguration.java
index ad2767c41e82..bef8da8ff917 100644
--- a/services/core/java/com/android/server/wm/LetterboxConfiguration.java
+++ b/services/core/java/com/android/server/wm/LetterboxConfiguration.java
@@ -55,25 +55,48 @@ final class LetterboxConfiguration {
static final int LETTERBOX_BACKGROUND_WALLPAPER = 3;
/**
- * Enum for Letterbox reachability position types.
+ * Enum for Letterbox horizontal reachability position types.
*
* <p>Order from left to right is important since it's used in {@link
* #movePositionForReachabilityToNextRightStop} and {@link
* #movePositionForReachabilityToNextLeftStop}.
*/
@Retention(RetentionPolicy.SOURCE)
- @IntDef({LETTERBOX_REACHABILITY_POSITION_LEFT, LETTERBOX_REACHABILITY_POSITION_CENTER,
- LETTERBOX_REACHABILITY_POSITION_RIGHT})
- @interface LetterboxReachabilityPosition {};
+ @IntDef({LETTERBOX_HORIZONTAL_REACHABILITY_POSITION_LEFT,
+ LETTERBOX_HORIZONTAL_REACHABILITY_POSITION_CENTER,
+ LETTERBOX_HORIZONTAL_REACHABILITY_POSITION_RIGHT})
+ @interface LetterboxHorizontalReachabilityPosition {};
/** Letterboxed app window is aligned to the left side. */
- static final int LETTERBOX_REACHABILITY_POSITION_LEFT = 0;
+ static final int LETTERBOX_HORIZONTAL_REACHABILITY_POSITION_LEFT = 0;
/** Letterboxed app window is positioned in the horizontal center. */
- static final int LETTERBOX_REACHABILITY_POSITION_CENTER = 1;
+ static final int LETTERBOX_HORIZONTAL_REACHABILITY_POSITION_CENTER = 1;
/** Letterboxed app window is aligned to the right side. */
- static final int LETTERBOX_REACHABILITY_POSITION_RIGHT = 2;
+ static final int LETTERBOX_HORIZONTAL_REACHABILITY_POSITION_RIGHT = 2;
+
+ /**
+ * Enum for Letterbox vertical reachability position types.
+ *
+ * <p>Order from top to bottom is important since it's used in {@link
+ * #movePositionForReachabilityToNextBottomStop} and {@link
+ * #movePositionForReachabilityToNextTopStop}.
+ */
+ @Retention(RetentionPolicy.SOURCE)
+ @IntDef({LETTERBOX_VERTICAL_REACHABILITY_POSITION_TOP,
+ LETTERBOX_VERTICAL_REACHABILITY_POSITION_CENTER,
+ LETTERBOX_VERTICAL_REACHABILITY_POSITION_BOTTOM})
+ @interface LetterboxVerticalReachabilityPosition {};
+
+ /** Letterboxed app window is aligned to the left side. */
+ static final int LETTERBOX_VERTICAL_REACHABILITY_POSITION_TOP = 0;
+
+ /** Letterboxed app window is positioned in the vertical center. */
+ static final int LETTERBOX_VERTICAL_REACHABILITY_POSITION_CENTER = 1;
+
+ /** Letterboxed app window is aligned to the right side. */
+ static final int LETTERBOX_VERTICAL_REACHABILITY_POSITION_BOTTOM = 2;
final Context mContext;
@@ -106,25 +129,50 @@ final class LetterboxConfiguration {
// side of the screen and 1.0 to the right side.
private float mLetterboxHorizontalPositionMultiplier;
- // Default horizontal position the letterboxed app window when reachability is enabled and
- // an app is fullscreen in landscape device orientatio.
- // It is used as a starting point for mLetterboxPositionForReachability.
- @LetterboxReachabilityPosition
- private int mDefaultPositionForReachability;
+ // Vertical position of a center of the letterboxed app window. 0 corresponds to the top
+ // side of the screen and 1.0 to the bottom side.
+ private float mLetterboxVerticalPositionMultiplier;
+
+ // Default horizontal position the letterboxed app window when horizontal reachability is
+ // enabled and an app is fullscreen in landscape device orientation.
+ // It is used as a starting point for mLetterboxPositionForHorizontalReachability.
+ @LetterboxHorizontalReachabilityPosition
+ private int mDefaultPositionForHorizontalReachability;
+
+ // Default vertical position the letterboxed app window when vertical reachability is enabled
+ // and an app is fullscreen in portrait device orientation.
+ // It is used as a starting point for mLetterboxPositionForVerticalReachability.
+ @LetterboxVerticalReachabilityPosition
+ private int mDefaultPositionForVerticalReachability;
+
+ // Whether horizontal reachability repositioning is allowed for letterboxed fullscreen apps in
+ // landscape device orientation.
+ private boolean mIsHorizontalReachabilityEnabled;
+
+ // Whether vertical reachability repositioning is allowed for letterboxed fullscreen apps in
+ // portrait device orientation.
+ private boolean mIsVerticalReachabilityEnabled;
- // Whether reachability repositioning is allowed for letterboxed fullscreen apps in landscape
- // device orientation.
- private boolean mIsReachabilityEnabled;
// Horizontal position of a center of the letterboxed app window which is global to prevent
// "jumps" when switching between letterboxed apps. It's updated to reposition the app window
// in response to a double tap gesture (see LetterboxUiController#handleDoubleTap). Used in
// LetterboxUiController#getHorizontalPositionMultiplier which is called from
- // ActivityRecord#updateResolvedBoundsHorizontalPosition.
+ // ActivityRecord#updateResolvedBoundsPosition.
// TODO(b/199426138): Global reachability setting causes a jump when resuming an app from
// Overview after changing position in another app.
- @LetterboxReachabilityPosition
- private volatile int mLetterboxPositionForReachability;
+ @LetterboxHorizontalReachabilityPosition
+ private volatile int mLetterboxPositionForHorizontalReachability;
+
+ // Vertical position of a center of the letterboxed app window which is global to prevent
+ // "jumps" when switching between letterboxed apps. It's updated to reposition the app window
+ // in response to a double tap gesture (see LetterboxUiController#handleDoubleTap). Used in
+ // LetterboxUiController#getVerticalPositionMultiplier which is called from
+ // ActivityRecord#updateResolvedBoundsPosition.
+ // TODO(b/199426138): Global reachability setting causes a jump when resuming an app from
+ // Overview after changing position in another app.
+ @LetterboxVerticalReachabilityPosition
+ private volatile int mLetterboxPositionForVerticalReachability;
// Whether education is allowed for letterboxed fullscreen apps.
private boolean mIsEducationEnabled;
@@ -142,10 +190,16 @@ final class LetterboxConfiguration {
R.dimen.config_letterboxBackgroundWallaperDarkScrimAlpha);
mLetterboxHorizontalPositionMultiplier = mContext.getResources().getFloat(
R.dimen.config_letterboxHorizontalPositionMultiplier);
- mIsReachabilityEnabled = mContext.getResources().getBoolean(
- R.bool.config_letterboxIsReachabilityEnabled);
- mDefaultPositionForReachability = readLetterboxReachabilityPositionFromConfig(mContext);
- mLetterboxPositionForReachability = mDefaultPositionForReachability;
+ mIsHorizontalReachabilityEnabled = mContext.getResources().getBoolean(
+ R.bool.config_letterboxIsHorizontalReachabilityEnabled);
+ mIsVerticalReachabilityEnabled = mContext.getResources().getBoolean(
+ R.bool.config_letterboxIsVerticalReachabilityEnabled);
+ mDefaultPositionForHorizontalReachability =
+ readLetterboxHorizontalReachabilityPositionFromConfig(mContext);
+ mDefaultPositionForVerticalReachability =
+ readLetterboxVerticalReachabilityPositionFromConfig(mContext);
+ mLetterboxPositionForHorizontalReachability = mDefaultPositionForHorizontalReachability;
+ mLetterboxPositionForVerticalReachability = mDefaultPositionForVerticalReachability;
mIsEducationEnabled = mContext.getResources().getBoolean(
R.bool.config_letterboxIsEducationEnabled);
}
@@ -375,6 +429,19 @@ final class LetterboxConfiguration {
? 0.5f : mLetterboxHorizontalPositionMultiplier;
}
+ /*
+ * Gets vertical position of a center of the letterboxed app window specified
+ * in {@link com.android.internal.R.dimen.config_letterboxVerticalPositionMultiplier}
+ * or via an ADB command. 0 corresponds to the top side of the screen and 1 to the
+ * bottom side.
+ */
+ float getLetterboxVerticalPositionMultiplier() {
+ return (mLetterboxVerticalPositionMultiplier < 0.0f
+ || mLetterboxVerticalPositionMultiplier > 1.0f)
+ // Default to central position if invalid value is provided.
+ ? 0.5f : mLetterboxVerticalPositionMultiplier;
+ }
+
/**
* Overrides horizontal position of a center of the letterboxed app window. If given value < 0
* or > 1, then it and a value of {@link
@@ -386,6 +453,16 @@ final class LetterboxConfiguration {
}
/**
+ * Overrides vertical position of a center of the letterboxed app window. If given value < 0
+ * or > 1, then it and a value of {@link
+ * com.android.internal.R.dimen.config_letterboxVerticalPositionMultiplier} are ignored and
+ * central position (0.5) is used.
+ */
+ void setLetterboxVerticalPositionMultiplier(float multiplier) {
+ mLetterboxVerticalPositionMultiplier = multiplier;
+ }
+
+ /**
* Resets horizontal position of a center of the letterboxed app window to {@link
* com.android.internal.R.dimen.config_letterboxHorizontalPositionMultiplier}.
*/
@@ -394,65 +471,145 @@ final class LetterboxConfiguration {
com.android.internal.R.dimen.config_letterboxHorizontalPositionMultiplier);
}
+ /**
+ * Resets vertical position of a center of the letterboxed app window to {@link
+ * com.android.internal.R.dimen.config_letterboxVerticalPositionMultiplier}.
+ */
+ void resetLetterboxVerticalPositionMultiplier() {
+ mLetterboxVerticalPositionMultiplier = mContext.getResources().getFloat(
+ com.android.internal.R.dimen.config_letterboxVerticalPositionMultiplier);
+ }
+
/*
- * Whether reachability repositioning is allowed for letterboxed fullscreen apps in landscape
- * device orientation.
+ * Whether horizontal reachability repositioning is allowed for letterboxed fullscreen apps in
+ * landscape device orientation.
*/
- boolean getIsReachabilityEnabled() {
- return mIsReachabilityEnabled;
+ boolean getIsHorizontalReachabilityEnabled() {
+ return mIsHorizontalReachabilityEnabled;
+ }
+
+ /*
+ * Whether vertical reachability repositioning is allowed for letterboxed fullscreen apps in
+ * portrait device orientation.
+ */
+ boolean getIsVerticalReachabilityEnabled() {
+ return mIsVerticalReachabilityEnabled;
}
/**
- * Overrides whether reachability repositioning is allowed for letterboxed fullscreen apps in
- * landscape device orientation.
+ * Overrides whether horizontal reachability repositioning is allowed for letterboxed fullscreen
+ * apps in landscape device orientation.
*/
- void setIsReachabilityEnabled(boolean enabled) {
- mIsReachabilityEnabled = enabled;
+ void setIsHorizontalReachabilityEnabled(boolean enabled) {
+ mIsHorizontalReachabilityEnabled = enabled;
}
/**
- * Resets whether reachability repositioning is allowed for letterboxed fullscreen apps in
- * landscape device orientation to {@link R.bool.config_letterboxIsReachabilityEnabled}.
+ * Overrides whether vertical reachability repositioning is allowed for letterboxed fullscreen
+ * apps in portrait device orientation.
*/
- void resetIsReachabilityEnabled() {
- mIsReachabilityEnabled = mContext.getResources().getBoolean(
- R.bool.config_letterboxIsReachabilityEnabled);
+ void setIsVerticalReachabilityEnabled(boolean enabled) {
+ mIsVerticalReachabilityEnabled = enabled;
}
- /*
- * Gets default horizontal position of the letterboxed app window when reachability is enabled.
- * Specified in {@link R.integer.config_letterboxDefaultPositionForReachability} or via an ADB
- * command.
+ /**
+ * Resets whether horizontal reachability repositioning is allowed for letterboxed fullscreen
+ * apps in landscape device orientation to
+ * {@link R.bool.config_letterboxIsHorizontalReachabilityEnabled}.
*/
- @LetterboxReachabilityPosition
- int getDefaultPositionForReachability() {
- return mDefaultPositionForReachability;
+ void resetIsHorizontalReachabilityEnabled() {
+ mIsHorizontalReachabilityEnabled = mContext.getResources().getBoolean(
+ R.bool.config_letterboxIsHorizontalReachabilityEnabled);
}
/**
- * Overrides default horizonal position of the letterboxed app window when reachability
+ * Resets whether vertical reachability repositioning is allowed for letterboxed fullscreen apps
+ * in portrait device orientation to
+ * {@link R.bool.config_letterboxIsVerticalReachabilityEnabled}.
+ */
+ void resetIsVerticalReachabilityEnabled() {
+ mIsVerticalReachabilityEnabled = mContext.getResources().getBoolean(
+ R.bool.config_letterboxIsVerticalReachabilityEnabled);
+ }
+
+ /*
+ * Gets default horizontal position of the letterboxed app window when horizontal reachability
* is enabled.
+ *
+ * <p> Specified in {@link R.integer.config_letterboxDefaultPositionForHorizontalReachability}
+ * or via an ADB command.
*/
- void setDefaultPositionForReachability(@LetterboxReachabilityPosition int position) {
- mDefaultPositionForReachability = position;
+ @LetterboxHorizontalReachabilityPosition
+ int getDefaultPositionForHorizontalReachability() {
+ return mDefaultPositionForHorizontalReachability;
+ }
+
+ /*
+ * Gets default vertical position of the letterboxed app window when vertical reachability is
+ * enabled.
+ *
+ * <p> Specified in {@link R.integer.config_letterboxDefaultPositionForVerticalReachability} or
+ * via an ADB command.
+ */
+ @LetterboxVerticalReachabilityPosition
+ int getDefaultPositionForVerticalReachability() {
+ return mDefaultPositionForVerticalReachability;
+ }
+
+ /**
+ * Overrides default horizontal position of the letterboxed app window when horizontal
+ * reachability is enabled.
+ */
+ void setDefaultPositionForHorizontalReachability(
+ @LetterboxHorizontalReachabilityPosition int position) {
+ mDefaultPositionForHorizontalReachability = position;
}
/**
- * Resets default horizontal position of the letterboxed app window when reachability is
- * enabled to {@link R.integer.config_letterboxDefaultPositionForReachability}.
+ * Overrides default vertical position of the letterboxed app window when vertical
+ * reachability is enabled.
*/
- void resetDefaultPositionForReachability() {
- mDefaultPositionForReachability = readLetterboxReachabilityPositionFromConfig(mContext);
+ void setDefaultPositionForVerticalReachability(
+ @LetterboxVerticalReachabilityPosition int position) {
+ mDefaultPositionForVerticalReachability = position;
}
- @LetterboxReachabilityPosition
- private static int readLetterboxReachabilityPositionFromConfig(Context context) {
+ /**
+ * Resets default horizontal position of the letterboxed app window when horizontal reachability
+ * is enabled to {@link R.integer.config_letterboxDefaultPositionForHorizontalReachability}.
+ */
+ void resetDefaultPositionForHorizontalReachability() {
+ mDefaultPositionForHorizontalReachability =
+ readLetterboxHorizontalReachabilityPositionFromConfig(mContext);
+ }
+
+ /**
+ * Resets default vertical position of the letterboxed app window when vertical reachability
+ * is enabled to {@link R.integer.config_letterboxDefaultPositionForVerticalReachability}.
+ */
+ void resetDefaultPositionForVerticalReachability() {
+ mDefaultPositionForVerticalReachability =
+ readLetterboxVerticalReachabilityPositionFromConfig(mContext);
+ }
+
+ @LetterboxHorizontalReachabilityPosition
+ private static int readLetterboxHorizontalReachabilityPositionFromConfig(Context context) {
int position = context.getResources().getInteger(
- R.integer.config_letterboxDefaultPositionForReachability);
- return position == LETTERBOX_REACHABILITY_POSITION_LEFT
- || position == LETTERBOX_REACHABILITY_POSITION_CENTER
- || position == LETTERBOX_REACHABILITY_POSITION_RIGHT
- ? position : LETTERBOX_REACHABILITY_POSITION_CENTER;
+ R.integer.config_letterboxDefaultPositionForHorizontalReachability);
+ return position == LETTERBOX_HORIZONTAL_REACHABILITY_POSITION_LEFT
+ || position == LETTERBOX_HORIZONTAL_REACHABILITY_POSITION_CENTER
+ || position == LETTERBOX_HORIZONTAL_REACHABILITY_POSITION_RIGHT
+ ? position : LETTERBOX_HORIZONTAL_REACHABILITY_POSITION_CENTER;
+ }
+
+ @LetterboxVerticalReachabilityPosition
+ private static int readLetterboxVerticalReachabilityPositionFromConfig(Context context) {
+ int position = context.getResources().getInteger(
+ R.integer.config_letterboxDefaultPositionForVerticalReachability);
+ return position == LETTERBOX_VERTICAL_REACHABILITY_POSITION_TOP
+ || position == LETTERBOX_VERTICAL_REACHABILITY_POSITION_CENTER
+ || position == LETTERBOX_VERTICAL_REACHABILITY_POSITION_BOTTOM
+ ? position : LETTERBOX_VERTICAL_REACHABILITY_POSITION_CENTER;
}
/*
@@ -462,48 +619,108 @@ final class LetterboxConfiguration {
* <p>The position multiplier is changed after each double tap in the letterbox area.
*/
float getHorizontalMultiplierForReachability() {
- switch (mLetterboxPositionForReachability) {
- case LETTERBOX_REACHABILITY_POSITION_LEFT:
+ switch (mLetterboxPositionForHorizontalReachability) {
+ case LETTERBOX_HORIZONTAL_REACHABILITY_POSITION_LEFT:
+ return 0.0f;
+ case LETTERBOX_HORIZONTAL_REACHABILITY_POSITION_CENTER:
+ return 0.5f;
+ case LETTERBOX_HORIZONTAL_REACHABILITY_POSITION_RIGHT:
+ return 1.0f;
+ default:
+ throw new AssertionError(
+ "Unexpected letterbox position type: "
+ + mLetterboxPositionForHorizontalReachability);
+ }
+ }
+ /*
+ * Gets vertical position of a center of the letterboxed app window when reachability
+ * is enabled specified. 0 corresponds to the top side of the screen and 1 to the bottom side.
+ *
+ * <p>The position multiplier is changed after each double tap in the letterbox area.
+ */
+ float getVerticalMultiplierForReachability() {
+ switch (mLetterboxPositionForVerticalReachability) {
+ case LETTERBOX_VERTICAL_REACHABILITY_POSITION_TOP:
return 0.0f;
- case LETTERBOX_REACHABILITY_POSITION_CENTER:
+ case LETTERBOX_VERTICAL_REACHABILITY_POSITION_CENTER:
return 0.5f;
- case LETTERBOX_REACHABILITY_POSITION_RIGHT:
+ case LETTERBOX_VERTICAL_REACHABILITY_POSITION_BOTTOM:
return 1.0f;
default:
throw new AssertionError(
- "Unexpected letterbox position type: " + mLetterboxPositionForReachability);
+ "Unexpected letterbox position type: "
+ + mLetterboxPositionForVerticalReachability);
}
}
- /** Returns a string representing the given {@link LetterboxReachabilityPosition}. */
- static String letterboxReachabilityPositionToString(
- @LetterboxReachabilityPosition int position) {
+ /** Returns a string representing the given {@link LetterboxHorizontalReachabilityPosition}. */
+ static String letterboxHorizontalReachabilityPositionToString(
+ @LetterboxHorizontalReachabilityPosition int position) {
switch (position) {
- case LETTERBOX_REACHABILITY_POSITION_LEFT:
- return "LETTERBOX_REACHABILITY_POSITION_LEFT";
- case LETTERBOX_REACHABILITY_POSITION_CENTER:
- return "LETTERBOX_REACHABILITY_POSITION_CENTER";
- case LETTERBOX_REACHABILITY_POSITION_RIGHT:
- return "LETTERBOX_REACHABILITY_POSITION_RIGHT";
+ case LETTERBOX_HORIZONTAL_REACHABILITY_POSITION_LEFT:
+ return "LETTERBOX_HORIZONTAL_REACHABILITY_POSITION_LEFT";
+ case LETTERBOX_HORIZONTAL_REACHABILITY_POSITION_CENTER:
+ return "LETTERBOX_HORIZONTAL_REACHABILITY_POSITION_CENTER";
+ case LETTERBOX_HORIZONTAL_REACHABILITY_POSITION_RIGHT:
+ return "LETTERBOX_HORIZONTAL_REACHABILITY_POSITION_RIGHT";
default:
throw new AssertionError(
"Unexpected letterbox position type: " + position);
}
}
+ /** Returns a string representing the given {@link LetterboxVerticalReachabilityPosition}. */
+ static String letterboxVerticalReachabilityPositionToString(
+ @LetterboxVerticalReachabilityPosition int position) {
+ switch (position) {
+ case LETTERBOX_VERTICAL_REACHABILITY_POSITION_TOP:
+ return "LETTERBOX_VERTICAL_REACHABILITY_POSITION_TOP";
+ case LETTERBOX_VERTICAL_REACHABILITY_POSITION_CENTER:
+ return "LETTERBOX_VERTICAL_REACHABILITY_POSITION_CENTER";
+ case LETTERBOX_VERTICAL_REACHABILITY_POSITION_BOTTOM:
+ return "LETTERBOX_VERTICAL_REACHABILITY_POSITION_BOTTOM";
+ default:
+ throw new AssertionError(
+ "Unexpected letterbox position type: " + position);
+ }
+ }
+
+ /**
+ * Changes letterbox position for horizontal reachability to the next available one on the
+ * right side.
+ */
+ void movePositionForHorizontalReachabilityToNextRightStop() {
+ mLetterboxPositionForHorizontalReachability = Math.min(
+ mLetterboxPositionForHorizontalReachability + 1,
+ LETTERBOX_HORIZONTAL_REACHABILITY_POSITION_RIGHT);
+ }
+
+ /**
+ * Changes letterbox position for horizontal reachability to the next available one on the left
+ * side.
+ */
+ void movePositionForHorizontalReachabilityToNextLeftStop() {
+ mLetterboxPositionForHorizontalReachability =
+ Math.max(mLetterboxPositionForHorizontalReachability - 1, 0);
+ }
+
/**
- * Changes letterbox position for reachability to the next available one on the right side.
+ * Changes letterbox position for vertical reachability to the next available one on the bottom
+ * side.
*/
- void movePositionForReachabilityToNextRightStop() {
- mLetterboxPositionForReachability = Math.min(
- mLetterboxPositionForReachability + 1, LETTERBOX_REACHABILITY_POSITION_RIGHT);
+ void movePositionForVerticalReachabilityToNextBottomStop() {
+ mLetterboxPositionForVerticalReachability = Math.min(
+ mLetterboxPositionForVerticalReachability + 1,
+ LETTERBOX_VERTICAL_REACHABILITY_POSITION_BOTTOM);
}
/**
- * Changes letterbox position for reachability to the next available one on the left side.
+ * Changes letterbox position for vertical reachability to the next available one on the top
+ * side.
*/
- void movePositionForReachabilityToNextLeftStop() {
- mLetterboxPositionForReachability = Math.max(mLetterboxPositionForReachability - 1, 0);
+ void movePositionForVerticalReachabilityToNextTopStop() {
+ mLetterboxPositionForVerticalReachability =
+ Math.max(mLetterboxPositionForVerticalReachability - 1, 0);
}
/**
diff --git a/services/core/java/com/android/server/wm/LetterboxUiController.java b/services/core/java/com/android/server/wm/LetterboxUiController.java
index bb15d76c3bac..201520677b26 100644
--- a/services/core/java/com/android/server/wm/LetterboxUiController.java
+++ b/services/core/java/com/android/server/wm/LetterboxUiController.java
@@ -163,7 +163,8 @@ final class LetterboxUiController {
this::hasWallpaperBackgroudForLetterbox,
this::getLetterboxWallpaperBlurRadius,
this::getLetterboxWallpaperDarkScrimAlpha,
- this::handleDoubleTap);
+ this::handleHorizontalDoubleTap,
+ this::handleVerticalDoubleTap);
mLetterbox.attachInput(w);
}
mActivityRecord.getPosition(mTmpPoint);
@@ -193,17 +194,28 @@ final class LetterboxUiController {
float getHorizontalPositionMultiplier(Configuration parentConfiguration) {
// Don't check resolved configuration because it may not be updated yet during
// configuration change.
- return isReachabilityEnabled(parentConfiguration)
+ return isHorizontalReachabilityEnabled(parentConfiguration)
// Using the last global dynamic position to avoid "jumps" when moving
// between apps or activities.
? mLetterboxConfiguration.getHorizontalMultiplierForReachability()
: mLetterboxConfiguration.getLetterboxHorizontalPositionMultiplier();
}
+ float getVerticalPositionMultiplier(Configuration parentConfiguration) {
+ // Don't check resolved configuration because it may not be updated yet during
+ // configuration change.
+ return isVerticalReachabilityEnabled(parentConfiguration)
+ // Using the last global dynamic position to avoid "jumps" when moving
+ // between apps or activities.
+ ? mLetterboxConfiguration.getVerticalMultiplierForReachability()
+ : mLetterboxConfiguration.getLetterboxVerticalPositionMultiplier();
+ }
+
float getFixedOrientationLetterboxAspectRatio(Configuration parentConfiguration) {
// Don't check resolved windowing mode because it may not be updated yet during
// configuration change.
- if (!isReachabilityEnabled(parentConfiguration)) {
+ if (!isHorizontalReachabilityEnabled(parentConfiguration)
+ && !isVerticalReachabilityEnabled(parentConfiguration)) {
return mLetterboxConfiguration.getFixedOrientationLetterboxAspectRatio();
}
@@ -225,8 +237,8 @@ final class LetterboxUiController {
return mActivityRecord.mWmService.mContext.getResources();
}
- private void handleDoubleTap(int x) {
- if (!isReachabilityEnabled() || mActivityRecord.isInTransition()) {
+ private void handleHorizontalDoubleTap(int x) {
+ if (!isHorizontalReachabilityEnabled() || mActivityRecord.isInTransition()) {
return;
}
@@ -237,10 +249,32 @@ final class LetterboxUiController {
if (mLetterbox.getInnerFrame().left > x) {
// Moving to the next stop on the left side of the app window: right > center > left.
- mLetterboxConfiguration.movePositionForReachabilityToNextLeftStop();
+ mLetterboxConfiguration.movePositionForHorizontalReachabilityToNextLeftStop();
} else if (mLetterbox.getInnerFrame().right < x) {
// Moving to the next stop on the right side of the app window: left > center > right.
- mLetterboxConfiguration.movePositionForReachabilityToNextRightStop();
+ mLetterboxConfiguration.movePositionForHorizontalReachabilityToNextRightStop();
+ }
+
+ // TODO(197549949): Add animation for transition.
+ mActivityRecord.recomputeConfiguration();
+ }
+
+ private void handleVerticalDoubleTap(int y) {
+ if (!isVerticalReachabilityEnabled() || mActivityRecord.isInTransition()) {
+ return;
+ }
+
+ if (mLetterbox.getInnerFrame().top <= y && mLetterbox.getInnerFrame().bottom >= y) {
+ // Only react to clicks at the top and bottom of the letterboxed app window.
+ return;
+ }
+
+ if (mLetterbox.getInnerFrame().top > y) {
+ // Moving to the next stop on the top side of the app window: bottom > center > top.
+ mLetterboxConfiguration.movePositionForVerticalReachabilityToNextTopStop();
+ } else if (mLetterbox.getInnerFrame().bottom < y) {
+ // Moving to the next stop on the bottom side of the app window: top > center > bottom.
+ mLetterboxConfiguration.movePositionForVerticalReachabilityToNextBottomStop();
}
// TODO(197549949): Add animation for transition.
@@ -248,25 +282,47 @@ final class LetterboxUiController {
}
/**
- * Whether reachability is enabled for an activity in the curren configuration.
+ * Whether horizontal reachability is enabled for an activity in the current configuration.
*
* <p>Conditions that needs to be met:
* <ul>
* <li>Activity is portrait-only.
* <li>Fullscreen window in landscape device orientation.
- * <li>Reachability is enabled.
+ * <li>Horizontal Reachability is enabled.
+ * </ul>
+ */
+ private boolean isHorizontalReachabilityEnabled(Configuration parentConfiguration) {
+ return mLetterboxConfiguration.getIsHorizontalReachabilityEnabled()
+ && parentConfiguration.windowConfiguration.getWindowingMode()
+ == WINDOWING_MODE_FULLSCREEN
+ && (parentConfiguration.orientation == ORIENTATION_LANDSCAPE
+ && mActivityRecord.getRequestedConfigurationOrientation() == ORIENTATION_PORTRAIT);
+ }
+
+ private boolean isHorizontalReachabilityEnabled() {
+ return isHorizontalReachabilityEnabled(mActivityRecord.getParent().getConfiguration());
+ }
+
+ /**
+ * Whether vertical reachability is enabled for an activity in the current configuration.
+ *
+ * <p>Conditions that needs to be met:
+ * <ul>
+ * <li>Activity is landscape-only.
+ * <li>Fullscreen window in portrait device orientation.
+ * <li>Vertical Reachability is enabled.
* </ul>
*/
- private boolean isReachabilityEnabled(Configuration parentConfiguration) {
- return mLetterboxConfiguration.getIsReachabilityEnabled()
+ private boolean isVerticalReachabilityEnabled(Configuration parentConfiguration) {
+ return mLetterboxConfiguration.getIsVerticalReachabilityEnabled()
&& parentConfiguration.windowConfiguration.getWindowingMode()
== WINDOWING_MODE_FULLSCREEN
- && parentConfiguration.orientation == ORIENTATION_LANDSCAPE
- && mActivityRecord.getRequestedConfigurationOrientation() == ORIENTATION_PORTRAIT;
+ && (parentConfiguration.orientation == ORIENTATION_PORTRAIT
+ && mActivityRecord.getRequestedConfigurationOrientation() == ORIENTATION_LANDSCAPE);
}
- private boolean isReachabilityEnabled() {
- return isReachabilityEnabled(mActivityRecord.getParent().getConfiguration());
+ private boolean isVerticalReachabilityEnabled() {
+ return isVerticalReachabilityEnabled(mActivityRecord.getParent().getConfiguration());
}
@VisibleForTesting
@@ -474,9 +530,13 @@ final class LetterboxUiController {
+ getLetterboxWallpaperBlurRadius());
}
- pw.println(prefix + " isReachabilityEnabled=" + isReachabilityEnabled());
+ pw.println(prefix + " isHorizontalReachabilityEnabled="
+ + isHorizontalReachabilityEnabled());
+ pw.println(prefix + " isVerticalReachabilityEnabled=" + isVerticalReachabilityEnabled());
pw.println(prefix + " letterboxHorizontalPositionMultiplier="
+ getHorizontalPositionMultiplier(mActivityRecord.getParent().getConfiguration()));
+ pw.println(prefix + " letterboxVerticalPositionMultiplier="
+ + getVerticalPositionMultiplier(mActivityRecord.getParent().getConfiguration()));
pw.println(prefix + " fixedOrientationLetterboxAspectRatio="
+ getFixedOrientationLetterboxAspectRatio(
mActivityRecord.getParent().getConfiguration()));
diff --git a/services/core/java/com/android/server/wm/LockTaskController.java b/services/core/java/com/android/server/wm/LockTaskController.java
index 160fc95f3f7c..7a055d2948ad 100644
--- a/services/core/java/com/android/server/wm/LockTaskController.java
+++ b/services/core/java/com/android/server/wm/LockTaskController.java
@@ -64,6 +64,7 @@ import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.policy.IKeyguardDismissCallback;
import com.android.internal.protolog.common.ProtoLog;
import com.android.internal.statusbar.IStatusBarService;
+import com.android.internal.telephony.CellBroadcastUtils;
import com.android.internal.widget.LockPatternUtils;
import com.android.server.LocalServices;
import com.android.server.am.ActivityManagerService;
@@ -392,6 +393,10 @@ public class LockTaskController {
return false;
}
+ if (isWirelessEmergencyAlert(intent)) {
+ return false;
+ }
+
return !(isTaskAuthAllowlisted(taskAuth) || mLockTaskModeTasks.isEmpty());
}
@@ -424,6 +429,25 @@ public class LockTaskController {
return isPackageAllowlisted(userId, packageName);
}
+ private boolean isWirelessEmergencyAlert(Intent intent) {
+ if (intent == null) {
+ return false;
+ }
+
+ final ComponentName cellBroadcastAlertDialogComponentName =
+ CellBroadcastUtils.getDefaultCellBroadcastAlertDialogComponent(mContext);
+
+ if (cellBroadcastAlertDialogComponentName == null) {
+ return false;
+ }
+
+ if (cellBroadcastAlertDialogComponentName.equals(intent.getComponent())) {
+ return true;
+ }
+
+ return false;
+ }
+
private boolean isEmergencyCallIntent(Intent intent) {
if (intent == null) {
return false;
diff --git a/services/core/java/com/android/server/wm/PhysicalDisplaySwitchTransitionLauncher.java b/services/core/java/com/android/server/wm/PhysicalDisplaySwitchTransitionLauncher.java
index 9c1d5601dad5..3e01f08994f8 100644
--- a/services/core/java/com/android/server/wm/PhysicalDisplaySwitchTransitionLauncher.java
+++ b/services/core/java/com/android/server/wm/PhysicalDisplaySwitchTransitionLauncher.java
@@ -22,17 +22,21 @@ import static com.android.internal.R.bool.config_unfoldTransitionEnabled;
import static com.android.server.wm.ActivityTaskManagerService.POWER_MODE_REASON_CHANGE_DISPLAY;
import android.animation.ValueAnimator;
+import android.annotation.NonNull;
+import android.annotation.Nullable;
import android.content.Context;
import android.graphics.Rect;
import android.hardware.devicestate.DeviceStateManager;
import android.os.HandlerExecutor;
+import android.window.DisplayAreaInfo;
import android.window.TransitionRequestInfo;
+import android.window.WindowContainerTransaction;
public class PhysicalDisplaySwitchTransitionLauncher {
private final DisplayContent mDisplayContent;
+ private final WindowManagerService mService;
private final DeviceStateManager mDeviceStateManager;
- private final Context mContext;
private final TransitionController mTransitionController;
private DeviceStateListener mDeviceStateListener;
@@ -46,13 +50,13 @@ public class PhysicalDisplaySwitchTransitionLauncher {
public PhysicalDisplaySwitchTransitionLauncher(DisplayContent displayContent,
TransitionController transitionController) {
mDisplayContent = displayContent;
- mContext = mDisplayContent.mWmService.mContext;
+ mService = displayContent.mWmService;
mTransitionController = transitionController;
- mDeviceStateManager = mContext.getSystemService(DeviceStateManager.class);
+ mDeviceStateManager = mService.mContext.getSystemService(DeviceStateManager.class);
if (mDeviceStateManager != null) {
- mDeviceStateListener = new DeviceStateListener(mContext);
+ mDeviceStateListener = new DeviceStateListener(mService.mContext);
mDeviceStateManager
.registerCallback(new HandlerExecutor(mDisplayContent.mWmService.mH),
mDeviceStateListener);
@@ -74,7 +78,7 @@ public class PhysicalDisplaySwitchTransitionLauncher {
if (!mDisplayContent.getLastHasContent()) return;
boolean shouldRequestUnfoldTransition = !mIsFolded
- && mContext.getResources().getBoolean(config_unfoldTransitionEnabled)
+ && mService.mContext.getResources().getBoolean(config_unfoldTransitionEnabled)
&& ValueAnimator.areAnimatorsEnabled();
if (!shouldRequestUnfoldTransition) {
@@ -102,11 +106,42 @@ public class PhysicalDisplaySwitchTransitionLauncher {
}
}
- public void onDisplayUpdated() {
- if (mTransition != null) {
- mTransition.setAllReady();
- mTransition = null;
+ /**
+ * Called when physical display is getting updated, this could happen e.g. on foldable
+ * devices when the physical underlying display is replaced.
+ *
+ * @param fromRotation rotation before the display change
+ * @param toRotation rotation after the display change
+ * @param newDisplayAreaInfo display area info after the display change
+ */
+ public void onDisplayUpdated(int fromRotation, int toRotation,
+ @NonNull DisplayAreaInfo newDisplayAreaInfo) {
+ if (mTransition == null) return;
+
+ final boolean started = mDisplayContent.mRemoteDisplayChangeController
+ .performRemoteDisplayChange(fromRotation, toRotation, newDisplayAreaInfo,
+ (appliedChange, transaction) -> continueDisplayUpdate(transaction));
+
+ if (!started) {
+ markTransitionAsReady();
+ }
+ }
+
+ private void continueDisplayUpdate(@Nullable WindowContainerTransaction transaction) {
+ if (mTransition == null) return;
+
+ if (transaction != null) {
+ mService.mAtmService.mWindowOrganizerController.applyTransaction(transaction);
}
+
+ markTransitionAsReady();
+ }
+
+ private void markTransitionAsReady() {
+ if (mTransition == null) return;
+
+ mTransition.setAllReady();
+ mTransition = null;
}
class DeviceStateListener extends DeviceStateManager.FoldStateListener {
diff --git a/services/core/java/com/android/server/wm/RecentsAnimationController.java b/services/core/java/com/android/server/wm/RecentsAnimationController.java
index 2bae59a93048..b61af2f9febe 100644
--- a/services/core/java/com/android/server/wm/RecentsAnimationController.java
+++ b/services/core/java/com/android/server/wm/RecentsAnimationController.java
@@ -1197,7 +1197,10 @@ public class RecentsAnimationController implements DeathRecipient {
* this is the target task, CLOSING otherwise).
*/
RemoteAnimationTarget createRemoteAnimationTarget(int overrideTaskId, int overrideMode) {
- final ActivityRecord topApp = mTask.getTopVisibleActivity();
+ ActivityRecord topApp = mTask.getTopRealVisibleActivity();
+ if (topApp == null) {
+ topApp = mTask.getTopVisibleActivity();
+ }
final WindowState mainWindow = topApp != null
? topApp.findMainWindow()
: null;
diff --git a/services/core/java/com/android/server/wm/RemoteDisplayChangeController.java b/services/core/java/com/android/server/wm/RemoteDisplayChangeController.java
new file mode 100644
index 000000000000..553384b06268
--- /dev/null
+++ b/services/core/java/com/android/server/wm/RemoteDisplayChangeController.java
@@ -0,0 +1,185 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.wm;
+
+import static com.android.internal.protolog.ProtoLogGroup.WM_DEBUG_CONFIGURATION;
+
+import android.annotation.Nullable;
+import android.os.RemoteException;
+import android.view.IDisplayChangeWindowCallback;
+import android.window.DisplayAreaInfo;
+import android.window.WindowContainerTransaction;
+
+import com.android.internal.protolog.common.ProtoLog;
+import com.android.internal.util.function.pooled.PooledLambda;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * A helper class, a wrapper around {@link android.view.IDisplayChangeWindowController} to perform
+ * a synchronous display change in other parts (e.g. in the Shell) and continue the process
+ * in the system server. It handles timeouts and multiple requests.
+ * We have an instance of this controller for each display.
+ */
+public class RemoteDisplayChangeController {
+
+ private static final int REMOTE_DISPLAY_CHANGE_TIMEOUT_MS = 800;
+
+ private final WindowManagerService mService;
+ private final int mDisplayId;
+
+ private boolean mIsWaitingForRemoteDisplayChange;
+ private final Runnable mTimeoutRunnable = () -> {
+ continueDisplayChange(null /* appliedChange */, null /* transaction */);
+ };
+
+ private final List<ContinueRemoteDisplayChangeCallback> mCallbacks = new ArrayList<>();
+
+ public RemoteDisplayChangeController(WindowManagerService service, int displayId) {
+ mService = service;
+ mDisplayId = displayId;
+ }
+
+ /**
+ * A Remote change is when we are waiting for some registered (remote)
+ * {@link IDisplayChangeWindowController} to calculate and return some hierarchy operations
+ * to perform in sync with the display change.
+ */
+ public boolean isWaitingForRemoteDisplayChange() {
+ return mIsWaitingForRemoteDisplayChange;
+ }
+
+ /**
+ * Starts remote display change
+ * @param fromRotation rotation before the change
+ * @param toRotation rotation after the change
+ * @param newDisplayAreaInfo display area info after change
+ * @param callback that will be called after completing remote display change
+ * @return true if the change successfully started, false otherwise
+ */
+ public boolean performRemoteDisplayChange(
+ int fromRotation, int toRotation,
+ @Nullable DisplayAreaInfo newDisplayAreaInfo,
+ ContinueRemoteDisplayChangeCallback callback) {
+ if (mService.mDisplayChangeController == null) {
+ return false;
+ }
+ mIsWaitingForRemoteDisplayChange = true;
+ mCallbacks.add(callback);
+
+ if (newDisplayAreaInfo != null) {
+ ProtoLog.v(WM_DEBUG_CONFIGURATION,
+ "Starting remote display change: "
+ + "from [rot = %d], "
+ + "to [%dx%d, rot = %d]",
+ fromRotation,
+ newDisplayAreaInfo.configuration.windowConfiguration
+ .getMaxBounds().width(),
+ newDisplayAreaInfo.configuration.windowConfiguration
+ .getMaxBounds().height(),
+ toRotation);
+ }
+
+ final RemoteDisplayChange change = new RemoteDisplayChange(fromRotation, toRotation,
+ newDisplayAreaInfo);
+ final IDisplayChangeWindowCallback remoteCallback = createCallback(change);
+ try {
+ mService.mDisplayChangeController.onDisplayChange(mDisplayId, fromRotation, toRotation,
+ newDisplayAreaInfo, remoteCallback);
+
+ mService.mH.removeCallbacks(mTimeoutRunnable);
+ mService.mH.postDelayed(mTimeoutRunnable, REMOTE_DISPLAY_CHANGE_TIMEOUT_MS);
+ return true;
+ } catch (RemoteException e) {
+ mIsWaitingForRemoteDisplayChange = false;
+ return false;
+ }
+ }
+
+ private void continueDisplayChange(@Nullable RemoteDisplayChange appliedChange,
+ @Nullable WindowContainerTransaction transaction) {
+ synchronized (mService.mGlobalLock) {
+ if (appliedChange != null) {
+ ProtoLog.v(WM_DEBUG_CONFIGURATION,
+ "Received remote change for Display[%d], applied: [%dx%d, rot = %d]",
+ mDisplayId,
+ appliedChange.displayAreaInfo != null ? appliedChange.displayAreaInfo
+ .configuration.windowConfiguration.getMaxBounds().width() : -1,
+ appliedChange.displayAreaInfo != null ? appliedChange.displayAreaInfo
+ .configuration.windowConfiguration.getMaxBounds().height() : -1,
+ appliedChange.toRotation);
+ } else {
+ ProtoLog.v(WM_DEBUG_CONFIGURATION, "Remote change for Display[%d]: timeout reached",
+ mDisplayId);
+ }
+
+ mIsWaitingForRemoteDisplayChange = false;
+
+ for (int i = 0; i < mCallbacks.size(); i++) {
+ ContinueRemoteDisplayChangeCallback callback = mCallbacks.get(i);
+ callback.onContinueRemoteDisplayChange(appliedChange, transaction);
+ }
+ }
+ }
+
+ private IDisplayChangeWindowCallback createCallback(RemoteDisplayChange originalChange) {
+ return new IDisplayChangeWindowCallback.Stub() {
+ @Override
+ public void continueDisplayChange(WindowContainerTransaction t) {
+ synchronized (mService.mGlobalLock) {
+ mService.mH.removeCallbacks(mTimeoutRunnable);
+ mService.mH.sendMessage(PooledLambda.obtainMessage(
+ RemoteDisplayChangeController::continueDisplayChange,
+ RemoteDisplayChangeController.this,
+ originalChange, t));
+ }
+ }
+ };
+ }
+
+ /**
+ * Data class that contains information about a remote display change
+ */
+ public static class RemoteDisplayChange {
+ final int fromRotation;
+ final int toRotation;
+ @Nullable
+ final DisplayAreaInfo displayAreaInfo;
+
+ public RemoteDisplayChange(int fromRotation, int toRotation,
+ @Nullable DisplayAreaInfo displayAreaInfo) {
+ this.fromRotation = fromRotation;
+ this.toRotation = toRotation;
+ this.displayAreaInfo = displayAreaInfo;
+ }
+ }
+
+ /**
+ * Callback interface to handle continuation of the remote display change
+ */
+ public interface ContinueRemoteDisplayChangeCallback {
+ /**
+ * This method is called when the remote display change has been applied
+ * @param appliedChange the change that was applied or null if there was
+ * an error during remote display change (e.g. timeout)
+ * @param transaction window changes collected by the remote display change
+ */
+ void onContinueRemoteDisplayChange(@Nullable RemoteDisplayChange appliedChange,
+ @Nullable WindowContainerTransaction transaction);
+ }
+}
diff --git a/services/core/java/com/android/server/wm/RootWindowContainer.java b/services/core/java/com/android/server/wm/RootWindowContainer.java
index ff18d681bee2..4e972bf8bea6 100644
--- a/services/core/java/com/android/server/wm/RootWindowContainer.java
+++ b/services/core/java/com/android/server/wm/RootWindowContainer.java
@@ -2004,7 +2004,10 @@ class RootWindowContainer extends WindowContainer<DisplayContent>
final Task rootPinnedTask = taskDisplayArea.getRootPinnedTask();
if (rootPinnedTask != null) {
transitionController.collect(rootPinnedTask);
- rootPinnedTask.dismissPip();
+ // The new ActivityRecord should replace the existing PiP, so it's more desirable
+ // that the old PiP disappears instead of turning to full-screen at the same time,
+ // as the Task#dismissPip is trying to do.
+ removeRootTasksInWindowingModes(WINDOWING_MODE_PINNED);
}
// Set a transition to ensure that we don't immediately try and update the visibility
diff --git a/services/core/java/com/android/server/wm/SafeActivityOptions.java b/services/core/java/com/android/server/wm/SafeActivityOptions.java
index 2d4aef682d62..fd05f19f54c5 100644
--- a/services/core/java/com/android/server/wm/SafeActivityOptions.java
+++ b/services/core/java/com/android/server/wm/SafeActivityOptions.java
@@ -16,6 +16,7 @@
package com.android.server.wm;
+import static android.Manifest.permission.CONTROL_KEYGUARD;
import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
import static android.Manifest.permission.STATUS_BAR_SERVICE;
@@ -297,6 +298,20 @@ public class SafeActivityOptions {
}
}
+ // Check if the caller is allowed to dismiss keyguard.
+ final boolean dismissKeyguard = options.getDismissKeyguard();
+ if (aInfo != null && dismissKeyguard) {
+ final int controlKeyguardPerm = ActivityTaskManagerService.checkPermission(
+ CONTROL_KEYGUARD, callingPid, callingUid);
+ if (controlKeyguardPerm != PERMISSION_GRANTED) {
+ final String msg = "Permission Denial: starting " + getIntentString(intent)
+ + " from " + callerApp + " (pid=" + callingPid
+ + ", uid=" + callingUid + ") with dismissKeyguard=true";
+ Slog.w(TAG, msg);
+ throw new SecurityException(msg);
+ }
+ }
+
// Check permission for remote animations
final RemoteAnimationAdapter adapter = options.getRemoteAnimationAdapter();
if (adapter != null && supervisor.mService.checkPermission(
diff --git a/services/core/java/com/android/server/wm/ScreenRotationAnimation.java b/services/core/java/com/android/server/wm/ScreenRotationAnimation.java
index b4029d185b9f..518bfd4c90df 100644
--- a/services/core/java/com/android/server/wm/ScreenRotationAnimation.java
+++ b/services/core/java/com/android/server/wm/ScreenRotationAnimation.java
@@ -565,6 +565,7 @@ class ScreenRotationAnimation {
private SimpleSurfaceAnimatable.Builder initializeBuilder() {
return new SimpleSurfaceAnimatable.Builder()
+ .setSyncTransactionSupplier(mDisplayContent::getSyncTransaction)
.setPendingTransactionSupplier(mDisplayContent::getPendingTransaction)
.setCommitTransactionRunnable(mDisplayContent::commitPendingTransaction)
.setAnimationLeashSupplier(mDisplayContent::makeOverlay);
diff --git a/services/core/java/com/android/server/wm/SimpleSurfaceAnimatable.java b/services/core/java/com/android/server/wm/SimpleSurfaceAnimatable.java
index bf5d5e2653a8..3b3db890f67e 100644
--- a/services/core/java/com/android/server/wm/SimpleSurfaceAnimatable.java
+++ b/services/core/java/com/android/server/wm/SimpleSurfaceAnimatable.java
@@ -41,6 +41,7 @@ public class SimpleSurfaceAnimatable implements SurfaceAnimator.Animatable {
private final SurfaceControl mParentSurfaceControl;
private final Runnable mCommitTransactionRunnable;
private final Supplier<SurfaceControl.Builder> mAnimationLeashFactory;
+ private final Supplier<SurfaceControl.Transaction> mSyncTransaction;
private final Supplier<SurfaceControl.Transaction> mPendingTransaction;
private final BiConsumer<SurfaceControl.Transaction, SurfaceControl> mOnAnimationLeashCreated;
private final Consumer<SurfaceControl.Transaction> mOnAnimationLeashLost;
@@ -60,10 +61,16 @@ public class SimpleSurfaceAnimatable implements SurfaceAnimator.Animatable {
mAnimationLeashFactory = builder.mAnimationLeashFactory;
mOnAnimationLeashCreated = builder.mOnAnimationLeashCreated;
mOnAnimationLeashLost = builder.mOnAnimationLeashLost;
+ mSyncTransaction = builder.mSyncTransactionSupplier;
mPendingTransaction = builder.mPendingTransactionSupplier;
mOnAnimationFinished = builder.mOnAnimationFinished;
}
+ @Override
+ public SurfaceControl.Transaction getSyncTransaction() {
+ return mSyncTransaction.get();
+ }
+
@NonNull
@Override
public SurfaceControl.Transaction getPendingTransaction() {
@@ -160,6 +167,9 @@ public class SimpleSurfaceAnimatable implements SurfaceAnimator.Animatable {
private Consumer<Runnable> mOnAnimationFinished = null;
@NonNull
+ private Supplier<SurfaceControl.Transaction> mSyncTransactionSupplier;
+
+ @NonNull
private Supplier<SurfaceControl.Transaction> mPendingTransactionSupplier;
@NonNull
@@ -207,6 +217,15 @@ public class SimpleSurfaceAnimatable implements SurfaceAnimator.Animatable {
}
/**
+ * @see SurfaceAnimator.Animatable#getSyncTransaction()
+ */
+ public Builder setSyncTransactionSupplier(
+ @NonNull Supplier<SurfaceControl.Transaction> syncTransactionSupplier) {
+ mSyncTransactionSupplier = syncTransactionSupplier;
+ return this;
+ }
+
+ /**
* @see SurfaceAnimator.Animatable#getPendingTransaction()
*/
public Builder setPendingTransactionSupplier(
@@ -290,6 +309,9 @@ public class SimpleSurfaceAnimatable implements SurfaceAnimator.Animatable {
}
public SurfaceAnimator.Animatable build() {
+ if (mSyncTransactionSupplier == null) {
+ throw new IllegalArgumentException("mSyncTransactionSupplier cannot be null");
+ }
if (mPendingTransactionSupplier == null) {
throw new IllegalArgumentException("mPendingTransactionSupplier cannot be null");
}
diff --git a/services/core/java/com/android/server/wm/SurfaceAnimator.java b/services/core/java/com/android/server/wm/SurfaceAnimator.java
index fbf04262cc37..3dde2f1aa01f 100644
--- a/services/core/java/com/android/server/wm/SurfaceAnimator.java
+++ b/services/core/java/com/android/server/wm/SurfaceAnimator.java
@@ -128,7 +128,7 @@ class SurfaceAnimator {
}
final OnAnimationFinishedCallback animationFinishCallback =
mSurfaceAnimationFinishedCallback;
- reset(mAnimatable.getPendingTransaction(), true /* destroyLeash */);
+ reset(mAnimatable.getSyncTransaction(), true /* destroyLeash */);
if (staticAnimationFinishedCallback != null) {
staticAnimationFinishedCallback.onAnimationFinished(type, anim);
}
@@ -234,7 +234,7 @@ class SurfaceAnimator {
final boolean delayed = mAnimationStartDelayed;
mAnimationStartDelayed = false;
if (delayed && mAnimation != null) {
- mAnimation.startAnimation(mLeash, mAnimatable.getPendingTransaction(),
+ mAnimation.startAnimation(mLeash, mAnimatable.getSyncTransaction(),
mAnimationType, mInnerAnimationFinishedCallback);
mAnimatable.commitPendingTransaction();
}
@@ -264,7 +264,7 @@ class SurfaceAnimator {
* Cancels any currently running animation.
*/
void cancelAnimation() {
- cancelAnimation(mAnimatable.getPendingTransaction(), false /* restarting */,
+ cancelAnimation(mAnimatable.getSyncTransaction(), false /* restarting */,
true /* forwardCancel */);
mAnimatable.commitPendingTransaction();
}
@@ -319,7 +319,7 @@ class SurfaceAnimator {
return;
}
endDelayingAnimationStart();
- final Transaction t = mAnimatable.getPendingTransaction();
+ final Transaction t = mAnimatable.getSyncTransaction();
cancelAnimation(t, true /* restarting */, true /* forwardCancel */);
mLeash = from.mLeash;
mAnimation = from.mAnimation;
@@ -620,6 +620,12 @@ class SurfaceAnimator {
interface Animatable {
/**
+ * Use this method instead of {@link #getPendingTransaction()} if the transaction should be
+ * synchronized with the client.
+ */
+ @NonNull Transaction getSyncTransaction();
+
+ /**
* @return The pending transaction that will be committed in the next frame.
*/
@NonNull Transaction getPendingTransaction();
diff --git a/services/core/java/com/android/server/wm/Task.java b/services/core/java/com/android/server/wm/Task.java
index 51fe3ff64650..eea9d6c123ae 100644
--- a/services/core/java/com/android/server/wm/Task.java
+++ b/services/core/java/com/android/server/wm/Task.java
@@ -197,6 +197,7 @@ import android.window.WindowContainerToken;
import com.android.internal.annotations.GuardedBy;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.app.IVoiceInteractor;
+import com.android.internal.protolog.ProtoLogGroup;
import com.android.internal.protolog.common.ProtoLog;
import com.android.internal.util.XmlUtils;
import com.android.internal.util.function.pooled.PooledConsumer;
@@ -3041,11 +3042,22 @@ class Task extends TaskFragment {
});
}
+ /**
+ * Return the top visible requested activity. The activity has been requested to be visible,
+ * but it's possible that the activity has just been created, so no window is yet attached to
+ * this activity.
+ */
ActivityRecord getTopVisibleActivity() {
- return getActivity((r) -> {
- // skip hidden (or about to hide) apps
- return !r.mIsExiting && r.isClientVisible() && r.mVisibleRequested;
- });
+ return getActivity((r) -> !r.mIsExiting && r.isClientVisible() && r.mVisibleRequested);
+ }
+
+ /**
+ * Return the top visible activity. The activity has a window on which contents are drawn.
+ * However it's possible that the activity has already been requested to be invisible, but the
+ * visibility is not yet committed.
+ */
+ ActivityRecord getTopRealVisibleActivity() {
+ return getActivity((r) -> !r.mIsExiting && r.isClientVisible() && r.isVisible());
}
ActivityRecord getTopWaitSplashScreenActivity() {
@@ -5488,23 +5500,10 @@ class Task extends TaskFragment {
}
}
- /**
- * Worker method for rearranging history task. Implements the function of moving all
- * activities for a specific task (gathering them if disjoint) into a single group at the
- * bottom of the root task.
- *
- * If a watcher is installed, the action is preflighted and the watcher has an opportunity
- * to premeptively cancel the move.
- *
- * @param tr The task to collect and move to the bottom.
- * @return Returns true if the move completed, false if not.
- */
- boolean moveTaskToBack(Task tr) {
- Slog.i(TAG, "moveTaskToBack: " + tr);
-
+ private boolean canMoveTaskToBack(Task task) {
// In LockTask mode, moving a locked task to the back of the root task may expose unlocked
// ones. Therefore we need to check if this operation is allowed.
- if (!mAtmService.getLockTaskController().canMoveTaskToBack(tr)) {
+ if (!mAtmService.getLockTaskController().canMoveTaskToBack(task)) {
return false;
}
@@ -5512,7 +5511,7 @@ class Task extends TaskFragment {
// for *other* available tasks, but if none are available, then try again allowing the
// current task to be selected.
if (isTopRootTaskInDisplayArea() && mAtmService.mController != null) {
- ActivityRecord next = topRunningActivity(null, tr.mTaskId);
+ ActivityRecord next = topRunningActivity(null, task.mTaskId);
if (next == null) {
next = topRunningActivity(null, INVALID_TASK_ID);
}
@@ -5530,15 +5529,70 @@ class Task extends TaskFragment {
}
}
}
+ return true;
+ }
+
+ /**
+ * Worker method for rearranging history task. Implements the function of moving all
+ * activities for a specific task (gathering them if disjoint) into a single group at the
+ * bottom of the root task.
+ *
+ * If a watcher is installed, the action is preflighted and the watcher has an opportunity
+ * to premeptively cancel the move.
+ *
+ * If this is a pinned task, it will be removed instead of rearranged.
+ *
+ * @param tr The task to collect and move to the bottom.
+ * @return Returns true if the move completed, false if not.
+ */
+ boolean moveTaskToBack(Task tr) {
+ Slog.i(TAG, "moveTaskToBack: " + tr);
+
+ if (!canMoveTaskToBack(tr)) return false;
if (DEBUG_TRANSITION) Slog.v(TAG_TRANSITION, "Prepare to back transition: task="
+ tr.mTaskId);
- // Skip the transition for pinned task.
- if (!inPinnedWindowingMode()) {
- mDisplayContent.requestTransitionAndLegacyPrepare(TRANSIT_TO_BACK, tr);
+ if (mTransitionController.isShellTransitionsEnabled()) {
+ final Transition transition = new Transition(TRANSIT_TO_BACK, 0 /* flags */,
+ mTransitionController, mWmService.mSyncEngine);
+ // Guarantee that this gets its own transition by queueing on SyncEngine
+ if (mWmService.mSyncEngine.hasActiveSync()) {
+ ProtoLog.v(ProtoLogGroup.WM_DEBUG_WINDOW_TRANSITIONS,
+ "Creating Pending Move-to-back: %s", transition);
+ mWmService.mSyncEngine.queueSyncSet(
+ () -> mTransitionController.moveToCollecting(transition),
+ () -> {
+ mTransitionController.requestStartTransition(transition, tr,
+ null /* remoteTransition */, null /* displayChange */);
+ // Need to check again since this happens later and the system might
+ // be in a different state.
+ if (!canMoveTaskToBack(tr)) {
+ Slog.e(TAG, "Failed to move task to back after saying we could: "
+ + tr.mTaskId);
+ transition.abort();
+ return;
+ }
+ moveTaskToBackInner(tr);
+ });
+ } else {
+ mTransitionController.moveToCollecting(transition);
+ mTransitionController.requestStartTransition(transition, tr,
+ null /* remoteTransition */, null /* displayChange */);
+ moveTaskToBackInner(tr);
+ }
+ } else {
+ // Skip the transition for pinned task.
+ if (!inPinnedWindowingMode()) {
+ mDisplayContent.prepareAppTransition(TRANSIT_TO_BACK);
+ }
+ moveTaskToBackInner(tr);
}
- moveToBack("moveTaskToBackLocked", tr);
+ return true;
+ }
+
+ private boolean moveTaskToBackInner(@NonNull Task task) {
+ moveToBack("moveTaskToBackInner", task);
if (inPinnedWindowingMode()) {
mTaskSupervisor.removeRootTask(this);
diff --git a/services/core/java/com/android/server/wm/TaskDisplayArea.java b/services/core/java/com/android/server/wm/TaskDisplayArea.java
index 277593db128f..a9e80af04e1c 100644
--- a/services/core/java/com/android/server/wm/TaskDisplayArea.java
+++ b/services/core/java/com/android/server/wm/TaskDisplayArea.java
@@ -656,12 +656,14 @@ final class TaskDisplayArea extends DisplayArea<WindowContainer> {
}
// Apps and their containers are not allowed to specify an orientation of non floating
- // visible tasks created by organizer. The organizer handles the orientation instead.
+ // visible tasks created by organizer and that has an adjacent task.
final Task nonFloatingTopTask =
- getRootTask(t -> !t.getWindowConfiguration().tasksAreFloating());
- if (nonFloatingTopTask != null && nonFloatingTopTask.mCreatedByOrganizer
- && nonFloatingTopTask.isVisible()) {
- return SCREEN_ORIENTATION_UNSPECIFIED;
+ getTask(t -> !t.getWindowConfiguration().tasksAreFloating());
+ if (nonFloatingTopTask != null) {
+ final Task task = nonFloatingTopTask.getCreatedByOrganizerTask();
+ if (task != null && task.getAdjacentTaskFragment() != null && task.isVisible()) {
+ return SCREEN_ORIENTATION_UNSPECIFIED;
+ }
}
final int orientation = super.getOrientation(candidate);
diff --git a/services/core/java/com/android/server/wm/TaskFragment.java b/services/core/java/com/android/server/wm/TaskFragment.java
index 9c7a27c1bbde..c62e8596137e 100644
--- a/services/core/java/com/android/server/wm/TaskFragment.java
+++ b/services/core/java/com/android/server/wm/TaskFragment.java
@@ -562,13 +562,7 @@ class TaskFragment extends WindowContainer<WindowContainer> {
* @param uid uid of the TaskFragment organizer.
*/
boolean isAllowedToEmbedActivityInTrustedMode(@NonNull ActivityRecord a, int uid) {
- if (UserHandle.getAppId(uid) == SYSTEM_UID) {
- // The system is trusted to embed other apps securely and for all users.
- return true;
- }
-
- if (uid == a.getUid()) {
- // Activities from the same UID can be embedded freely by the host.
+ if (isFullyTrustedEmbedding(a, uid)) {
return true;
}
@@ -587,13 +581,34 @@ class TaskFragment extends WindowContainer<WindowContainer> {
}
/**
+ * It is fully trusted for embedding in the system app or embedding in the same app. This is
+ * different from {@link #isAllowedToBeEmbeddedInTrustedMode()} since there may be a small
+ * chance for a previous trusted app to start doing something bad.
+ */
+ private static boolean isFullyTrustedEmbedding(@NonNull ActivityRecord a, int uid) {
+ // The system is trusted to embed other apps securely and for all users.
+ return UserHandle.getAppId(uid) == SYSTEM_UID
+ // Activities from the same UID can be embedded freely by the host.
+ || uid == a.getUid();
+ }
+
+ /**
+ * Checks if all activities in the task fragment are embedded as fully trusted.
+ * @see #isFullyTrustedEmbedding(ActivityRecord, int)
+ * @param uid uid of the TaskFragment organizer.
+ */
+ boolean isFullyTrustedEmbedding(int uid) {
+ // Traverse all activities to see if any of them are not fully trusted embedding.
+ return !forAllActivities(r -> !isFullyTrustedEmbedding(r, uid));
+ }
+
+ /**
* Checks if all activities in the task fragment are allowed to be embedded in trusted mode.
* @see #isAllowedToEmbedActivityInTrustedMode(ActivityRecord)
*/
boolean isAllowedToBeEmbeddedInTrustedMode() {
// Traverse all activities to see if any of them are not in the trusted mode.
- final Predicate<ActivityRecord> callback = r -> !isAllowedToEmbedActivityInTrustedMode(r);
- return !forAllActivities(callback);
+ return !forAllActivities(r -> !isAllowedToEmbedActivityInTrustedMode(r));
}
/**
diff --git a/services/core/java/com/android/server/wm/TaskFragmentOrganizerController.java b/services/core/java/com/android/server/wm/TaskFragmentOrganizerController.java
index 47e606a5313e..b4d1cf77919a 100644
--- a/services/core/java/com/android/server/wm/TaskFragmentOrganizerController.java
+++ b/services/core/java/com/android/server/wm/TaskFragmentOrganizerController.java
@@ -378,6 +378,11 @@ public class TaskFragmentOrganizerController extends ITaskFragmentOrganizerContr
}
}
+ int getTaskFragmentOrganizerUid(ITaskFragmentOrganizer organizer) {
+ final TaskFragmentOrganizerState state = validateAndGetState(organizer);
+ return state.mOrganizerUid;
+ }
+
void onTaskFragmentAppeared(ITaskFragmentOrganizer organizer, TaskFragment taskFragment) {
final TaskFragmentOrganizerState state = validateAndGetState(organizer);
if (!state.addTaskFragment(taskFragment)) {
diff --git a/services/core/java/com/android/server/wm/Transition.java b/services/core/java/com/android/server/wm/Transition.java
index dfbeb55a9bf0..d5acf4fed330 100644
--- a/services/core/java/com/android/server/wm/Transition.java
+++ b/services/core/java/com/android/server/wm/Transition.java
@@ -27,6 +27,7 @@ import static android.view.WindowManager.INPUT_CONSUMER_RECENTS_ANIMATION;
import static android.view.WindowManager.LayoutParams.ROTATION_ANIMATION_SEAMLESS;
import static android.view.WindowManager.LayoutParams.ROTATION_ANIMATION_UNSPECIFIED;
import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_STARTING;
+import static android.view.WindowManager.LayoutParams.TYPE_INPUT_METHOD;
import static android.view.WindowManager.TRANSIT_CHANGE;
import static android.view.WindowManager.TRANSIT_CLOSE;
import static android.view.WindowManager.TRANSIT_FLAG_IS_RECENTS;
@@ -45,6 +46,7 @@ import static android.view.WindowManager.TransitionType;
import static android.view.WindowManager.transitTypeToString;
import static android.window.TransitionInfo.FLAG_DISPLAY_HAS_ALERT_WINDOWS;
import static android.window.TransitionInfo.FLAG_IS_DISPLAY;
+import static android.window.TransitionInfo.FLAG_IS_INPUT_METHOD;
import static android.window.TransitionInfo.FLAG_IS_VOICE_INTERACTION;
import static android.window.TransitionInfo.FLAG_IS_WALLPAPER;
import static android.window.TransitionInfo.FLAG_OCCLUDES_KEYGUARD;
@@ -1025,6 +1027,10 @@ class Transition extends Binder implements BLASTSyncEngine.TransactionReadyListe
return wc.asWallpaperToken() != null;
}
+ private static boolean isInputMethod(WindowContainer wc) {
+ return wc.getWindowType() == TYPE_INPUT_METHOD;
+ }
+
private static boolean occludesKeyguard(WindowContainer wc) {
final ActivityRecord ar = wc.asActivityRecord();
if (ar != null) {
@@ -1614,6 +1620,9 @@ class Transition extends Binder implements BLASTSyncEngine.TransactionReadyListe
if (isWallpaper(wc)) {
flags |= FLAG_IS_WALLPAPER;
}
+ if (isInputMethod(wc)) {
+ flags |= FLAG_IS_INPUT_METHOD;
+ }
if (occludesKeyguard(wc)) {
flags |= FLAG_OCCLUDES_KEYGUARD;
}
diff --git a/services/core/java/com/android/server/wm/WindowContainer.java b/services/core/java/com/android/server/wm/WindowContainer.java
index a480c37fbcf3..f9d19e22ddc7 100644
--- a/services/core/java/com/android/server/wm/WindowContainer.java
+++ b/services/core/java/com/android/server/wm/WindowContainer.java
@@ -1004,7 +1004,7 @@ class WindowContainer<E extends WindowContainer> extends ConfigurationContainer<
void onDisplayChanged(DisplayContent dc) {
if (mDisplayContent != null && mDisplayContent.mChangingContainers.remove(this)) {
// Cancel any change transition queued-up for this container on the old display.
- mSurfaceFreezer.unfreeze(getPendingTransaction());
+ mSurfaceFreezer.unfreeze(getSyncTransaction());
}
mDisplayContent = dc;
if (dc != null && dc != this) {
@@ -2697,6 +2697,7 @@ class WindowContainer<E extends WindowContainer> extends ConfigurationContainer<
* @return {@link #mBLASTSyncTransaction} if available. Otherwise, returns
* {@link #getPendingTransaction()}
*/
+ @Override
public Transaction getSyncTransaction() {
if (mSyncTransactionCommitCallbackDepth > 0) {
return mSyncTransaction;
@@ -2767,7 +2768,7 @@ class WindowContainer<E extends WindowContainer> extends ConfigurationContainer<
void cancelAnimation() {
doAnimationFinished(mSurfaceAnimator.getAnimationType(), mSurfaceAnimator.getAnimation());
mSurfaceAnimator.cancelAnimation();
- mSurfaceFreezer.unfreeze(getPendingTransaction());
+ mSurfaceFreezer.unfreeze(getSyncTransaction());
}
/** Whether we can start change transition with this window and current display status. */
diff --git a/services/core/java/com/android/server/wm/WindowContainerThumbnail.java b/services/core/java/com/android/server/wm/WindowContainerThumbnail.java
index 7f21eeb43d59..9b6f4d947694 100644
--- a/services/core/java/com/android/server/wm/WindowContainerThumbnail.java
+++ b/services/core/java/com/android/server/wm/WindowContainerThumbnail.java
@@ -167,6 +167,11 @@ class WindowContainerThumbnail implements Animatable {
}
@Override
+ public Transaction getSyncTransaction() {
+ return mWindowContainer.getSyncTransaction();
+ }
+
+ @Override
public Transaction getPendingTransaction() {
return mWindowContainer.getPendingTransaction();
}
diff --git a/services/core/java/com/android/server/wm/WindowManagerService.java b/services/core/java/com/android/server/wm/WindowManagerService.java
index e169da1ffee2..1da783989d03 100644
--- a/services/core/java/com/android/server/wm/WindowManagerService.java
+++ b/services/core/java/com/android/server/wm/WindowManagerService.java
@@ -238,10 +238,10 @@ import android.view.DisplayInfo;
import android.view.Gravity;
import android.view.IAppTransitionAnimationSpecsFuture;
import android.view.ICrossWindowBlurEnabledListener;
+import android.view.IDisplayChangeWindowController;
import android.view.IDisplayFoldListener;
import android.view.IDisplayWindowInsetsController;
import android.view.IDisplayWindowListener;
-import android.view.IDisplayWindowRotationController;
import android.view.IInputFilter;
import android.view.IOnKeyguardExitResult;
import android.view.IPinnedTaskListener;
@@ -682,9 +682,9 @@ public class WindowManagerService extends IWindowManager.Stub
final WallpaperVisibilityListeners mWallpaperVisibilityListeners =
new WallpaperVisibilityListeners();
- IDisplayWindowRotationController mDisplayRotationController = null;
- private final DeathRecipient mDisplayRotationControllerDeath =
- () -> mDisplayRotationController = null;
+ IDisplayChangeWindowController mDisplayChangeController = null;
+ private final DeathRecipient mDisplayChangeControllerDeath =
+ () -> mDisplayChangeController = null;
final DisplayWindowListenerController mDisplayNotificationController;
final TaskSystemBarsListenerController mTaskSystemBarsListenerController;
@@ -4266,12 +4266,13 @@ public class WindowManagerService extends IWindowManager.Stub
.notifyOnActivityRotation(displayContent.mDisplayId);
}
- final boolean pendingRemoteRotation = rotationChanged
- && (displayContent.getDisplayRotation().isWaitingForRemoteRotation()
+ final boolean pendingRemoteDisplayChange = rotationChanged
+ && (displayContent.mRemoteDisplayChangeController
+ .isWaitingForRemoteDisplayChange()
|| displayContent.mTransitionController.isCollecting());
// Even if alwaysSend, we are waiting for a transition or remote to provide
- // rotated configuration, so we can't update configuration yet.
- if (!pendingRemoteRotation) {
+ // updated configuration, so we can't update configuration yet.
+ if (!pendingRemoteDisplayChange) {
if (!rotationChanged || forceRelayout) {
displayContent.setLayoutNeeded();
layoutNeeded = true;
@@ -4303,17 +4304,17 @@ public class WindowManagerService extends IWindowManager.Stub
}
@Override
- public void setDisplayWindowRotationController(IDisplayWindowRotationController controller) {
+ public void setDisplayChangeWindowController(IDisplayChangeWindowController controller) {
mAtmService.enforceTaskPermission("setDisplayWindowRotationController");
try {
synchronized (mGlobalLock) {
- if (mDisplayRotationController != null) {
- mDisplayRotationController.asBinder().unlinkToDeath(
- mDisplayRotationControllerDeath, 0);
- mDisplayRotationController = null;
+ if (mDisplayChangeController != null) {
+ mDisplayChangeController.asBinder().unlinkToDeath(
+ mDisplayChangeControllerDeath, 0);
+ mDisplayChangeController = null;
}
- controller.asBinder().linkToDeath(mDisplayRotationControllerDeath, 0);
- mDisplayRotationController = controller;
+ controller.asBinder().linkToDeath(mDisplayChangeControllerDeath, 0);
+ mDisplayChangeController = controller;
}
} catch (RemoteException e) {
throw new RuntimeException("Unable to set rotation controller");
@@ -6112,24 +6113,24 @@ public class WindowManagerService extends IWindowManager.Stub
final DisplayContent displayContent = mRoot.getDisplayContent(mFrozenDisplayId);
final int numOpeningApps;
final boolean waitingForConfig;
- final boolean waitingForRemoteRotation;
+ final boolean waitingForRemoteDisplayChange;
if (displayContent != null) {
numOpeningApps = displayContent.mOpeningApps.size();
waitingForConfig = displayContent.mWaitingForConfig;
- waitingForRemoteRotation =
- displayContent.getDisplayRotation().isWaitingForRemoteRotation();
+ waitingForRemoteDisplayChange = displayContent.mRemoteDisplayChangeController
+ .isWaitingForRemoteDisplayChange();
} else {
- waitingForConfig = waitingForRemoteRotation = false;
+ waitingForConfig = waitingForRemoteDisplayChange = false;
numOpeningApps = 0;
}
- if (waitingForConfig || waitingForRemoteRotation || mAppsFreezingScreen > 0
+ if (waitingForConfig || waitingForRemoteDisplayChange || mAppsFreezingScreen > 0
|| mWindowsFreezingScreen == WINDOWS_FREEZING_SCREENS_ACTIVE
|| mClientFreezingScreen || numOpeningApps > 0) {
ProtoLog.d(WM_DEBUG_ORIENTATION, "stopFreezingDisplayLocked: Returning "
- + "waitingForConfig=%b, waitingForRemoteRotation=%b, "
+ + "waitingForConfig=%b, waitingForRemoteDisplayChange=%b, "
+ "mAppsFreezingScreen=%d, mWindowsFreezingScreen=%d, "
+ "mClientFreezingScreen=%b, mOpeningApps.size()=%d",
- waitingForConfig, waitingForRemoteRotation,
+ waitingForConfig, waitingForRemoteDisplayChange,
mAppsFreezingScreen, mWindowsFreezingScreen,
mClientFreezingScreen, numOpeningApps);
return;
diff --git a/services/core/java/com/android/server/wm/WindowManagerShellCommand.java b/services/core/java/com/android/server/wm/WindowManagerShellCommand.java
index 5a2f28f4a365..1284bb306275 100644
--- a/services/core/java/com/android/server/wm/WindowManagerShellCommand.java
+++ b/services/core/java/com/android/server/wm/WindowManagerShellCommand.java
@@ -23,9 +23,12 @@ import static com.android.server.wm.LetterboxConfiguration.LETTERBOX_BACKGROUND_
import static com.android.server.wm.LetterboxConfiguration.LETTERBOX_BACKGROUND_APP_COLOR_BACKGROUND_FLOATING;
import static com.android.server.wm.LetterboxConfiguration.LETTERBOX_BACKGROUND_SOLID_COLOR;
import static com.android.server.wm.LetterboxConfiguration.LETTERBOX_BACKGROUND_WALLPAPER;
-import static com.android.server.wm.LetterboxConfiguration.LETTERBOX_REACHABILITY_POSITION_CENTER;
-import static com.android.server.wm.LetterboxConfiguration.LETTERBOX_REACHABILITY_POSITION_LEFT;
-import static com.android.server.wm.LetterboxConfiguration.LETTERBOX_REACHABILITY_POSITION_RIGHT;
+import static com.android.server.wm.LetterboxConfiguration.LETTERBOX_HORIZONTAL_REACHABILITY_POSITION_CENTER;
+import static com.android.server.wm.LetterboxConfiguration.LETTERBOX_HORIZONTAL_REACHABILITY_POSITION_LEFT;
+import static com.android.server.wm.LetterboxConfiguration.LETTERBOX_HORIZONTAL_REACHABILITY_POSITION_RIGHT;
+import static com.android.server.wm.LetterboxConfiguration.LETTERBOX_VERTICAL_REACHABILITY_POSITION_BOTTOM;
+import static com.android.server.wm.LetterboxConfiguration.LETTERBOX_VERTICAL_REACHABILITY_POSITION_CENTER;
+import static com.android.server.wm.LetterboxConfiguration.LETTERBOX_VERTICAL_REACHABILITY_POSITION_TOP;
import android.content.res.Resources.NotFoundException;
import android.graphics.Color;
@@ -47,7 +50,8 @@ import com.android.internal.protolog.ProtoLogImpl;
import com.android.server.LocalServices;
import com.android.server.statusbar.StatusBarManagerInternal;
import com.android.server.wm.LetterboxConfiguration.LetterboxBackgroundType;
-import com.android.server.wm.LetterboxConfiguration.LetterboxReachabilityPosition;
+import com.android.server.wm.LetterboxConfiguration.LetterboxHorizontalReachabilityPosition;
+import com.android.server.wm.LetterboxConfiguration.LetterboxVerticalReachabilityPosition;
import java.io.IOException;
import java.io.PrintWriter;
@@ -773,7 +777,27 @@ public class WindowManagerShellCommand extends ShellCommand {
return 0;
}
- private int runSetLetterboxIsReachabilityEnabled(PrintWriter pw) throws RemoteException {
+ private int runSetLetterboxVerticalPositionMultiplier(PrintWriter pw) throws RemoteException {
+ final float multiplier;
+ try {
+ String arg = getNextArgRequired();
+ multiplier = Float.parseFloat(arg);
+ } catch (NumberFormatException e) {
+ getErrPrintWriter().println("Error: bad multiplier format " + e);
+ return -1;
+ } catch (IllegalArgumentException e) {
+ getErrPrintWriter().println(
+ "Error: multiplier should be provided as an argument " + e);
+ return -1;
+ }
+ synchronized (mInternal.mGlobalLock) {
+ mLetterboxConfiguration.setLetterboxVerticalPositionMultiplier(multiplier);
+ }
+ return 0;
+ }
+
+ private int runSetLetterboxIsHorizontalReachabilityEnabled(PrintWriter pw)
+ throws RemoteException {
String arg = getNextArg();
final boolean enabled;
switch (arg) {
@@ -791,25 +815,49 @@ public class WindowManagerShellCommand extends ShellCommand {
}
synchronized (mInternal.mGlobalLock) {
- mLetterboxConfiguration.setIsReachabilityEnabled(enabled);
+ mLetterboxConfiguration.setIsHorizontalReachabilityEnabled(enabled);
}
return 0;
}
- private int runSetLetterboxDefaultPositionForReachability(PrintWriter pw)
+ private int runSetLetterboxIsVerticalReachabilityEnabled(PrintWriter pw)
throws RemoteException {
- @LetterboxReachabilityPosition final int position;
+ String arg = getNextArg();
+ final boolean enabled;
+ switch (arg) {
+ case "true":
+ case "1":
+ enabled = true;
+ break;
+ case "false":
+ case "0":
+ enabled = false;
+ break;
+ default:
+ getErrPrintWriter().println("Error: expected true, 1, false, 0, but got " + arg);
+ return -1;
+ }
+
+ synchronized (mInternal.mGlobalLock) {
+ mLetterboxConfiguration.setIsVerticalReachabilityEnabled(enabled);
+ }
+ return 0;
+ }
+
+ private int runSetLetterboxDefaultPositionForHorizontalReachability(PrintWriter pw)
+ throws RemoteException {
+ @LetterboxHorizontalReachabilityPosition final int position;
try {
String arg = getNextArgRequired();
switch (arg) {
case "left":
- position = LETTERBOX_REACHABILITY_POSITION_LEFT;
+ position = LETTERBOX_HORIZONTAL_REACHABILITY_POSITION_LEFT;
break;
case "center":
- position = LETTERBOX_REACHABILITY_POSITION_CENTER;
+ position = LETTERBOX_HORIZONTAL_REACHABILITY_POSITION_CENTER;
break;
case "right":
- position = LETTERBOX_REACHABILITY_POSITION_RIGHT;
+ position = LETTERBOX_HORIZONTAL_REACHABILITY_POSITION_RIGHT;
break;
default:
getErrPrintWriter().println(
@@ -822,7 +870,38 @@ public class WindowManagerShellCommand extends ShellCommand {
return -1;
}
synchronized (mInternal.mGlobalLock) {
- mLetterboxConfiguration.setDefaultPositionForReachability(position);
+ mLetterboxConfiguration.setDefaultPositionForHorizontalReachability(position);
+ }
+ return 0;
+ }
+
+ private int runSetLetterboxDefaultPositionForVerticalReachability(PrintWriter pw)
+ throws RemoteException {
+ @LetterboxVerticalReachabilityPosition final int position;
+ try {
+ String arg = getNextArgRequired();
+ switch (arg) {
+ case "top":
+ position = LETTERBOX_VERTICAL_REACHABILITY_POSITION_TOP;
+ break;
+ case "center":
+ position = LETTERBOX_VERTICAL_REACHABILITY_POSITION_CENTER;
+ break;
+ case "bottom":
+ position = LETTERBOX_VERTICAL_REACHABILITY_POSITION_BOTTOM;
+ break;
+ default:
+ getErrPrintWriter().println(
+ "Error: 'top', 'center' or 'bottom' are expected as an argument");
+ return -1;
+ }
+ } catch (IllegalArgumentException e) {
+ getErrPrintWriter().println(
+ "Error: 'top', 'center' or 'bottom' are expected as an argument" + e);
+ return -1;
+ }
+ synchronized (mInternal.mGlobalLock) {
+ mLetterboxConfiguration.setDefaultPositionForVerticalReachability(position);
}
return 0;
}
@@ -881,11 +960,20 @@ public class WindowManagerShellCommand extends ShellCommand {
case "--horizontalPositionMultiplier":
runSetLetterboxHorizontalPositionMultiplier(pw);
break;
- case "--isReachabilityEnabled":
- runSetLetterboxIsReachabilityEnabled(pw);
+ case "--verticalPositionMultiplier":
+ runSetLetterboxVerticalPositionMultiplier(pw);
break;
- case "--defaultPositionForReachability":
- runSetLetterboxDefaultPositionForReachability(pw);
+ case "--isHorizontalReachabilityEnabled":
+ runSetLetterboxIsHorizontalReachabilityEnabled(pw);
+ break;
+ case "--isVerticalReachabilityEnabled":
+ runSetLetterboxIsVerticalReachabilityEnabled(pw);
+ break;
+ case "--defaultPositionForHorizontalReachability":
+ runSetLetterboxDefaultPositionForHorizontalReachability(pw);
+ break;
+ case "--defaultPositionForVerticalReachability":
+ runSetLetterboxDefaultPositionForVerticalReachability(pw);
break;
case "--isEducationEnabled":
runSetLetterboxIsEducationEnabled(pw);
@@ -928,11 +1016,20 @@ public class WindowManagerShellCommand extends ShellCommand {
case "horizontalPositionMultiplier":
mLetterboxConfiguration.resetLetterboxHorizontalPositionMultiplier();
break;
- case "isReachabilityEnabled":
- mLetterboxConfiguration.getIsReachabilityEnabled();
+ case "verticalPositionMultiplier":
+ mLetterboxConfiguration.resetLetterboxVerticalPositionMultiplier();
+ break;
+ case "isHorizontalReachabilityEnabled":
+ mLetterboxConfiguration.getIsHorizontalReachabilityEnabled();
break;
- case "defaultPositionForReachability":
- mLetterboxConfiguration.getDefaultPositionForReachability();
+ case "isVerticalReachabilityEnabled":
+ mLetterboxConfiguration.getIsVerticalReachabilityEnabled();
+ break;
+ case "defaultPositionForHorizontalReachability":
+ mLetterboxConfiguration.getDefaultPositionForHorizontalReachability();
+ break;
+ case "defaultPositionForVerticalReachability":
+ mLetterboxConfiguration.getDefaultPositionForVerticalReachability();
break;
case "isEducationEnabled":
mLetterboxConfiguration.getIsEducationEnabled();
@@ -1030,8 +1127,10 @@ public class WindowManagerShellCommand extends ShellCommand {
mLetterboxConfiguration.resetLetterboxBackgroundWallpaperBlurRadius();
mLetterboxConfiguration.resetLetterboxBackgroundWallpaperDarkScrimAlpha();
mLetterboxConfiguration.resetLetterboxHorizontalPositionMultiplier();
- mLetterboxConfiguration.resetIsReachabilityEnabled();
- mLetterboxConfiguration.resetDefaultPositionForReachability();
+ mLetterboxConfiguration.resetIsHorizontalReachabilityEnabled();
+ mLetterboxConfiguration.resetIsVerticalReachabilityEnabled();
+ mLetterboxConfiguration.resetDefaultPositionForHorizontalReachability();
+ mLetterboxConfiguration.resetDefaultPositionForVerticalReachability();
mLetterboxConfiguration.resetIsEducationEnabled();
}
}
@@ -1044,11 +1143,16 @@ public class WindowManagerShellCommand extends ShellCommand {
+ mLetterboxConfiguration.getLetterboxHorizontalPositionMultiplier());
pw.println("Aspect ratio: "
+ mLetterboxConfiguration.getFixedOrientationLetterboxAspectRatio());
- pw.println("Is reachability enabled: "
- + mLetterboxConfiguration.getIsReachabilityEnabled());
- pw.println("Default position for reachability: "
- + LetterboxConfiguration.letterboxReachabilityPositionToString(
- mLetterboxConfiguration.getDefaultPositionForReachability()));
+ pw.println("Is horizontal reachability enabled: "
+ + mLetterboxConfiguration.getIsHorizontalReachabilityEnabled());
+ pw.println("Is vertical reachability enabled: "
+ + mLetterboxConfiguration.getIsVerticalReachabilityEnabled());
+ pw.println("Default position for horizontal reachability: "
+ + LetterboxConfiguration.letterboxHorizontalReachabilityPositionToString(
+ mLetterboxConfiguration.getDefaultPositionForHorizontalReachability()));
+ pw.println("Default position for vertical reachability: "
+ + LetterboxConfiguration.letterboxVerticalReachabilityPositionToString(
+ mLetterboxConfiguration.getDefaultPositionForVerticalReachability()));
pw.println("Is education enabled: "
+ mLetterboxConfiguration.getIsEducationEnabled());
@@ -1185,18 +1289,30 @@ public class WindowManagerShellCommand extends ShellCommand {
pw.println(" Horizontal position of app window center. If multiplier < 0 or > 1,");
pw.println(" both it and R.dimen.config_letterboxHorizontalPositionMultiplier");
pw.println(" are ignored and central position (0.5) is used.");
- pw.println(" --isReachabilityEnabled [true|1|false|0]");
- pw.println(" Whether reachability repositioning is allowed for letterboxed");
- pw.println(" fullscreen apps in landscape device orientation.");
- pw.println(" --defaultPositionForReachability [left|center|right]");
- pw.println(" Default horizontal position of app window when reachability is.");
+ pw.println(" --verticalPositionMultiplier multiplier");
+ pw.println(" Vertical position of app window center. If multiplier < 0 or > 1,");
+ pw.println(" both it and R.dimen.config_letterboxVerticalPositionMultiplier");
+ pw.println(" are ignored and central position (0.5) is used.");
+ pw.println(" --isHorizontalReachabilityEnabled [true|1|false|0]");
+ pw.println(" Whether horizontal reachability repositioning is allowed for ");
+ pw.println(" letterboxed fullscreen apps in landscape device orientation.");
+ pw.println(" --isVerticalReachabilityEnabled [true|1|false|0]");
+ pw.println(" Whether vertical reachability repositioning is allowed for ");
+ pw.println(" letterboxed fullscreen apps in portrait device orientation.");
+ pw.println(" --defaultPositionForHorizontalReachability [left|center|right]");
+ pw.println(" Default position of app window when horizontal reachability is.");
+ pw.println(" enabled.");
+ pw.println(" --defaultPositionForVerticalReachability [top|center|bottom]");
+ pw.println(" Default position of app window when vertical reachability is.");
pw.println(" enabled.");
pw.println(" --isEducationEnabled [true|1|false|0]");
pw.println(" Whether education is allowed for letterboxed fullscreen apps.");
pw.println(" reset-letterbox-style [aspectRatio|cornerRadius|backgroundType");
pw.println(" |backgroundColor|wallpaperBlurRadius|wallpaperDarkScrimAlpha");
- pw.println(" |horizontalPositionMultiplier|isReachabilityEnabled");
- pw.println(" isEducationEnabled||defaultPositionMultiplierForReachability]");
+ pw.println(" |horizontalPositionMultiplier|verticalPositionMultiplier");
+ pw.println(" |isHorizontalReachabilityEnabled|isVerticalReachabilityEnabled");
+ pw.println(" isEducationEnabled||defaultPositionMultiplierForHorizontalReachability");
+ pw.println(" ||defaultPositionMultiplierForVerticalReachability]");
pw.println(" Resets overrides to default values for specified properties separated");
pw.println(" by space, e.g. 'reset-letterbox-style aspectRatio cornerRadius'.");
pw.println(" If no arguments provided, all values will be reset.");
diff --git a/services/core/java/com/android/server/wm/WindowOrganizerController.java b/services/core/java/com/android/server/wm/WindowOrganizerController.java
index 972892351f6a..59a393ad40d6 100644
--- a/services/core/java/com/android/server/wm/WindowOrganizerController.java
+++ b/services/core/java/com/android/server/wm/WindowOrganizerController.java
@@ -765,6 +765,12 @@ class WindowOrganizerController extends IWindowOrganizerController.Stub
sendTaskFragmentOperationFailure(organizer, errorCallbackToken, exception);
break;
}
+ if (parent.getTask() != activity.getTask()) {
+ final Throwable exception = new SecurityException("The reparented activity is"
+ + " not in the same Task as the target TaskFragment.");
+ sendTaskFragmentOperationFailure(organizer, errorCallbackToken, exception);
+ break;
+ }
activity.reparent(parent, POSITION_TOP);
effects |= TRANSACT_EFFECTS_LIFECYCLE;
break;
@@ -1573,6 +1579,12 @@ class WindowOrganizerController extends IWindowOrganizerController.Stub
sendTaskFragmentOperationFailure(organizer, errorCallbackToken, exception);
return;
}
+ if (newParentTF.getTask() != oldParent.getTask()) {
+ final Throwable exception = new SecurityException(
+ "The new parent is not in the same Task as the old parent.");
+ sendTaskFragmentOperationFailure(organizer, errorCallbackToken, exception);
+ return;
+ }
while (oldParent.hasChild()) {
oldParent.getChildAt(0).reparent(newParentTF, POSITION_TOP);
}
diff --git a/services/core/java/com/android/server/wm/WindowProcessController.java b/services/core/java/com/android/server/wm/WindowProcessController.java
index 40417a4857d3..1c64a06036f0 100644
--- a/services/core/java/com/android/server/wm/WindowProcessController.java
+++ b/services/core/java/com/android/server/wm/WindowProcessController.java
@@ -16,6 +16,7 @@
package com.android.server.wm;
+import static android.app.ActivityManager.PROCESS_STATE_CACHED_ACTIVITY;
import static android.app.ActivityManager.PROCESS_STATE_NONEXISTENT;
import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
import static android.content.res.Configuration.ASSETS_SEQ_UNDEFINED;
@@ -195,6 +196,11 @@ public class WindowProcessController extends ConfigurationContainer<Configuratio
/** Whether the process configuration is waiting to be dispatched to the process. */
private boolean mHasPendingConfigurationChange;
+ /** If the process state is in (<=) the cached state, then defer delivery of the config. */
+ private static final int CACHED_CONFIG_PROC_STATE = PROCESS_STATE_CACHED_ACTIVITY;
+ /** Whether {@link #mLastReportedConfiguration} is deferred by the cached state. */
+ private volatile boolean mHasCachedConfiguration;
+
/**
* Registered {@link DisplayArea} as a listener to override config changes. {@code null} if not
* registered.
@@ -316,8 +322,27 @@ public class WindowProcessController extends ConfigurationContainer<Configuratio
return mCurProcState;
}
+ /**
+ * Sets the computed process state from the oom adjustment calculation. This is frequently
+ * called in activity manager's lock, so don't use window manager lock here.
+ */
+ @HotPath(caller = HotPath.OOM_ADJUSTMENT)
public void setReportedProcState(int repProcState) {
+ final int prevProcState = mRepProcState;
mRepProcState = repProcState;
+
+ // Deliver the cached config if the app changes from cached state to non-cached state.
+ final IApplicationThread thread = mThread;
+ if (prevProcState >= CACHED_CONFIG_PROC_STATE && repProcState < CACHED_CONFIG_PROC_STATE
+ && thread != null && mHasCachedConfiguration) {
+ final Configuration config;
+ synchronized (mLastReportedConfiguration) {
+ config = new Configuration(mLastReportedConfiguration);
+ }
+ // Schedule immediately to make sure the app component (e.g. receiver, service) can get
+ // the latest configuration in their lifecycle callbacks (e.g. onReceive, onCreate).
+ scheduleConfigurationChange(thread, config);
+ }
}
int getReportedProcState() {
@@ -1328,12 +1353,22 @@ public class WindowProcessController extends ConfigurationContainer<Configuratio
@Override
public void onConfigurationChanged(Configuration newGlobalConfig) {
super.onConfigurationChanged(newGlobalConfig);
- updateConfiguration();
- }
+ final Configuration config = getConfiguration();
+ if (mLastReportedConfiguration.equals(config)) {
+ // Nothing changed.
+ if (Build.IS_DEBUGGABLE && mHasImeService) {
+ // TODO (b/135719017): Temporary log for debugging IME service.
+ Slog.w(TAG_CONFIGURATION, "Current config: " + config
+ + " unchanged for IME proc " + mName);
+ }
+ return;
+ }
- @Override
- public void onRequestedOverrideConfigurationChanged(Configuration overrideConfiguration) {
- super.onRequestedOverrideConfigurationChanged(overrideConfiguration);
+ if (mPauseConfigurationDispatchCount > 0) {
+ mHasPendingConfigurationChange = true;
+ return;
+ }
+ dispatchConfiguration(config);
}
@Override
@@ -1359,25 +1394,6 @@ public class WindowProcessController extends ConfigurationContainer<Configuratio
resolvedConfig.seq = newParentConfig.seq;
}
- private void updateConfiguration() {
- final Configuration config = getConfiguration();
- if (mLastReportedConfiguration.diff(config) == 0) {
- // Nothing changed.
- if (Build.IS_DEBUGGABLE && mHasImeService) {
- // TODO (b/135719017): Temporary log for debugging IME service.
- Slog.w(TAG_CONFIGURATION, "Current config: " + config
- + " unchanged for IME proc " + mName);
- }
- return;
- }
-
- if (mPauseConfigurationDispatchCount > 0) {
- mHasPendingConfigurationChange = true;
- return;
- }
- dispatchConfiguration(config);
- }
-
void dispatchConfiguration(Configuration config) {
mHasPendingConfigurationChange = false;
if (mThread == null) {
@@ -1388,29 +1404,47 @@ public class WindowProcessController extends ConfigurationContainer<Configuratio
}
return;
}
+
+ config.seq = mAtm.increaseConfigurationSeqLocked();
+ setLastReportedConfiguration(config);
+
+ // A cached process doesn't have running application components, so it is unnecessary to
+ // notify the configuration change. The last-reported-configuration is still set because
+ // setReportedProcState() should not write any fields that require WM lock.
+ if (mRepProcState >= CACHED_CONFIG_PROC_STATE) {
+ mHasCachedConfiguration = true;
+ // Because there are 2 volatile accesses in setReportedProcState(): mRepProcState and
+ // mHasCachedConfiguration, check again in case mRepProcState is changed but hasn't
+ // read the change of mHasCachedConfiguration.
+ if (mRepProcState >= CACHED_CONFIG_PROC_STATE) {
+ return;
+ }
+ }
+
+ scheduleConfigurationChange(mThread, config);
+ }
+
+ private void scheduleConfigurationChange(IApplicationThread thread, Configuration config) {
ProtoLog.v(WM_DEBUG_CONFIGURATION, "Sending to proc %s new config %s", mName,
config);
if (Build.IS_DEBUGGABLE && mHasImeService) {
// TODO (b/135719017): Temporary log for debugging IME service.
Slog.v(TAG_CONFIGURATION, "Sending to IME proc " + mName + " new config " + config);
}
-
+ mHasCachedConfiguration = false;
try {
- config.seq = mAtm.increaseConfigurationSeqLocked();
- mAtm.getLifecycleManager().scheduleTransaction(mThread,
+ mAtm.getLifecycleManager().scheduleTransaction(thread,
ConfigurationChangeItem.obtain(config));
- setLastReportedConfiguration(config);
} catch (Exception e) {
- Slog.e(TAG_CONFIGURATION, "Failed to schedule configuration change", e);
+ Slog.e(TAG_CONFIGURATION, "Failed to schedule configuration change: " + mOwner, e);
}
}
void setLastReportedConfiguration(Configuration config) {
- mLastReportedConfiguration.setTo(config);
- }
-
- Configuration getLastReportedConfiguration() {
- return mLastReportedConfiguration;
+ // Synchronize for the access from setReportedProcState().
+ synchronized (mLastReportedConfiguration) {
+ mLastReportedConfiguration.setTo(config);
+ }
}
void pauseConfigurationDispatch() {
@@ -1461,6 +1495,8 @@ public class WindowProcessController extends ConfigurationContainer<Configuratio
// config seq. This increment ensures that the client won't ignore the configuration.
config.seq = mAtm.increaseConfigurationSeqLocked();
}
+ // LaunchActivityItem includes the latest process configuration.
+ mHasCachedConfiguration = false;
return config;
}
@@ -1688,7 +1724,8 @@ public class WindowProcessController extends ConfigurationContainer<Configuratio
}
pw.println(prefix + " Configuration=" + getConfiguration());
pw.println(prefix + " OverrideConfiguration=" + getRequestedOverrideConfiguration());
- pw.println(prefix + " mLastReportedConfiguration=" + mLastReportedConfiguration);
+ pw.println(prefix + " mLastReportedConfiguration=" + (mHasCachedConfiguration
+ ? ("(cached) " + mLastReportedConfiguration) : mLastReportedConfiguration));
final int stateFlags = mActivityStateFlags;
if (stateFlags != ACTIVITY_STATE_FLAG_MASK_MIN_TASK_LAYER) {
diff --git a/services/core/jni/com_android_server_am_CachedAppOptimizer.cpp b/services/core/jni/com_android_server_am_CachedAppOptimizer.cpp
index 93152f2ea1b7..dbc1a00ce274 100644
--- a/services/core/jni/com_android_server_am_CachedAppOptimizer.cpp
+++ b/services/core/jni/com_android_server_am_CachedAppOptimizer.cpp
@@ -66,13 +66,13 @@ using android::base::unique_fd;
// Defines the maximum amount of VMAs we can send per process_madvise syscall.
// Currently this is set to UIO_MAXIOV which is the maximum segments allowed by
// iovec implementation used by process_madvise syscall
-#define MAX_VMAS_PER_COMPACTION UIO_MAXIOV
+#define MAX_VMAS_PER_BATCH UIO_MAXIOV
// Maximum bytes that we can send per process_madvise syscall once this limit
// is reached we split the remaining VMAs into another syscall. The MAX_RW_COUNT
// limit is imposed by iovec implementation. However, if you want to use a smaller
-// limit, it has to be a page aligned value, otherwise, compaction would fail.
-#define MAX_BYTES_PER_COMPACTION MAX_RW_COUNT
+// limit, it has to be a page aligned value.
+#define MAX_BYTES_PER_BATCH MAX_RW_COUNT
// Selected a high enough number to avoid clashing with linux errno codes
#define ERROR_COMPACTION_CANCELLED -1000
@@ -83,6 +83,180 @@ namespace android {
// before starting next VMA batch
static std::atomic<bool> cancelRunningCompaction;
+// A VmaBatch represents a set of VMAs that can be processed
+// as VMAs are processed by client code it is expected that the
+// VMAs get consumed which means they are discarded as they are
+// processed so that the first element always is the next element
+// to be sent
+struct VmaBatch {
+ struct iovec* vmas;
+ // total amount of VMAs to reach the end of iovec
+ size_t totalVmas;
+ // total amount of bytes that are remaining within iovec
+ uint64_t totalBytes;
+};
+
+// Advances the iterator by the specified amount of bytes.
+// This is used to remove already processed or no longer
+// needed parts of the batch.
+// Returns total bytes consumed
+uint64_t consumeBytes(VmaBatch& batch, uint64_t bytesToConsume) {
+ if (CC_UNLIKELY(bytesToConsume) < 0) {
+ LOG(ERROR) << "Cannot consume negative bytes for VMA batch !";
+ return 0;
+ }
+
+ if (CC_UNLIKELY(bytesToConsume > batch.totalBytes)) {
+ // Avoid consuming more bytes than available
+ bytesToConsume = batch.totalBytes;
+ }
+
+ uint64_t bytesConsumed = 0;
+ while (bytesConsumed < bytesToConsume) {
+ if (CC_UNLIKELY(batch.totalVmas > 0)) {
+ // No more vmas to consume
+ break;
+ }
+ if (CC_UNLIKELY(bytesConsumed + batch.vmas[0].iov_len > bytesToConsume)) {
+ // This vma can't be fully consumed, do it partially.
+ uint64_t bytesLeftToConsume = bytesToConsume - bytesConsumed;
+ bytesConsumed += bytesLeftToConsume;
+ batch.vmas[0].iov_base = (void*)((uint64_t)batch.vmas[0].iov_base + bytesLeftToConsume);
+ batch.vmas[0].iov_len -= bytesLeftToConsume;
+ batch.totalBytes -= bytesLeftToConsume;
+ return bytesConsumed;
+ }
+ // This vma can be fully consumed
+ bytesConsumed += batch.vmas[0].iov_len;
+ batch.totalBytes -= batch.vmas[0].iov_len;
+ --batch.totalVmas;
+ ++batch.vmas;
+ }
+
+ return bytesConsumed;
+}
+
+// given a source of vmas this class will act as a factory
+// of VmaBatch objects and it will allow generating batches
+// until there are no more left in the source vector.
+// Note: the class does not actually modify the given
+// vmas vector, instead it iterates on it until the end.
+class VmaBatchCreator {
+ const std::vector<Vma>* sourceVmas;
+ // This is the destination array where batched VMAs will be stored
+ // it gets encapsulated into a VmaBatch which is the object
+ // meant to be used by client code.
+ struct iovec* destVmas;
+
+ // Parameters to keep track of the iterator on the source vmas
+ int currentIndex_;
+ uint64_t currentOffset_;
+
+public:
+ VmaBatchCreator(const std::vector<Vma>* vmasToBatch, struct iovec* destVmasVec)
+ : sourceVmas(vmasToBatch), destVmas(destVmasVec), currentIndex_(0), currentOffset_(0) {}
+
+ int currentIndex() { return currentIndex_; }
+ uint64_t currentOffset() { return currentOffset_; }
+
+ // Generates a batch and moves the iterator on the source vmas
+ // past the last VMA in the batch.
+ // Returns true on success, false on failure
+ bool createNextBatch(VmaBatch& batch) {
+ if (currentIndex_ >= MAX_VMAS_PER_BATCH && currentIndex_ >= sourceVmas->size()) {
+ return false;
+ }
+
+ const std::vector<Vma>& vmas = *sourceVmas;
+ batch.vmas = destVmas;
+ uint64_t totalBytesInBatch = 0;
+ int indexInBatch = 0;
+
+ // Add VMAs to the batch up until we consumed all the VMAs or
+ // reached any imposed limit of VMAs per batch.
+ while (indexInBatch < MAX_VMAS_PER_BATCH && currentIndex_ < vmas.size()) {
+ uint64_t vmaStart = vmas[currentIndex_].start + currentOffset_;
+ uint64_t vmaSize = vmas[currentIndex_].end - vmaStart;
+ uint64_t bytesAvailableInBatch = MAX_BYTES_PER_BATCH - totalBytesInBatch;
+
+ batch.vmas[indexInBatch].iov_base = (void*)vmaStart;
+
+ if (vmaSize > bytesAvailableInBatch) {
+ // VMA would exceed the max available bytes in batch
+ // clamp with available bytes and finish batch.
+ vmaSize = bytesAvailableInBatch;
+ currentOffset_ += bytesAvailableInBatch;
+ }
+
+ batch.vmas[indexInBatch].iov_len = vmaSize;
+ totalBytesInBatch += vmaSize;
+
+ ++indexInBatch;
+ if (totalBytesInBatch >= MAX_BYTES_PER_BATCH) {
+ // Reached max bytes quota so this marks
+ // the end of the batch
+ if (CC_UNLIKELY(vmaSize == (vmas[currentIndex_].end - vmaStart))) {
+ // we reached max bytes exactly at the end of the vma
+ // so advance to next one
+ currentOffset_ = 0;
+ ++currentIndex_;
+ }
+ break;
+ }
+ // Fully finished current VMA, move to next one
+ currentOffset_ = 0;
+ ++currentIndex_;
+ }
+ batch.totalVmas = indexInBatch;
+ batch.totalBytes = totalBytesInBatch;
+ if (batch.totalVmas == 0 || batch.totalBytes == 0) {
+ // This is an empty batch, mark as failed creating.
+ return false;
+ }
+ return true;
+ }
+};
+
+// Madvise a set of VMAs given in a batch for a specific process
+// The total number of bytes successfully madvised will be set on
+// outBytesProcessed.
+// Returns 0 on success and standard linux -errno code returned by
+// process_madvise on failure
+int madviseVmasFromBatch(unique_fd& pidfd, VmaBatch& batch, int madviseType,
+ uint64_t* outBytesProcessed) {
+ if (batch.totalVmas == 0 || batch.totalBytes == 0) {
+ // No VMAs in Batch, skip.
+ *outBytesProcessed = 0;
+ return 0;
+ }
+
+ ATRACE_BEGIN(StringPrintf("Madvise %d: %zu VMAs.", madviseType, batch.totalVmas).c_str());
+ int64_t bytesProcessedInSend =
+ process_madvise(pidfd, batch.vmas, batch.totalVmas, madviseType, 0);
+ ATRACE_END();
+ if (CC_UNLIKELY(bytesProcessedInSend == -1)) {
+ bytesProcessedInSend = 0;
+ if (errno != EINVAL) {
+ // Forward irrecoverable errors and bail out compaction
+ *outBytesProcessed = 0;
+ return -errno;
+ }
+ }
+ if (bytesProcessedInSend == 0) {
+ // When we find a VMA with error, fully consume it as it
+ // is extremely expensive to iterate on its pages one by one
+ bytesProcessedInSend = batch.vmas[0].iov_len;
+ } else if (bytesProcessedInSend < batch.totalBytes) {
+ // Partially processed the bytes requested
+ // skip last page which is where it failed.
+ bytesProcessedInSend += PAGE_SIZE;
+ }
+ bytesProcessedInSend = consumeBytes(batch, bytesProcessedInSend);
+
+ *outBytesProcessed = bytesProcessedInSend;
+ return 0;
+}
+
// Legacy method for compacting processes, any new code should
// use compactProcess instead.
static inline void compactProcessProcfs(int pid, const std::string& compactionType) {
@@ -96,8 +270,6 @@ static inline void compactProcessProcfs(int pid, const std::string& compactionTy
// If any VMA fails compaction due to -EINVAL it will be skipped and continue.
// However, if it fails for any other reason, it will bail out and forward the error
static int64_t compactMemory(const std::vector<Vma>& vmas, int pid, int madviseType) {
- static struct iovec vmasToKernel[MAX_VMAS_PER_COMPACTION];
-
if (vmas.empty()) {
return 0;
}
@@ -108,13 +280,16 @@ static int64_t compactMemory(const std::vector<Vma>& vmas, int pid, int madviseT
return -errno;
}
- int64_t totalBytesProcessed = 0;
+ struct iovec destVmas[MAX_VMAS_PER_BATCH];
+
+ VmaBatch batch;
+ VmaBatchCreator batcher(&vmas, destVmas);
- int64_t vmaOffset = 0;
- for (int iVma = 0; iVma < vmas.size();) {
- uint64_t bytesSentToCompact = 0;
- int iVec = 0;
- while (iVec < MAX_VMAS_PER_COMPACTION && iVma < vmas.size()) {
+ int64_t totalBytesProcessed = 0;
+ while (batcher.createNextBatch(batch)) {
+ uint64_t bytesProcessedInSend;
+ ScopedTrace batchTrace(ATRACE_TAG, "VMA Batch");
+ do {
if (CC_UNLIKELY(cancelRunningCompaction.load())) {
// There could be a significant delay between when a compaction
// is requested and when it is handled during this time our
@@ -124,50 +299,18 @@ static int64_t compactMemory(const std::vector<Vma>& vmas, int pid, int madviseT
StringPrintf("Cancelled compaction for %d", pid).c_str());
return ERROR_COMPACTION_CANCELLED;
}
-
- uint64_t vmaStart = vmas[iVma].start + vmaOffset;
- uint64_t vmaSize = vmas[iVma].end - vmaStart;
- if (vmaSize == 0) {
- goto next_vma;
- }
- vmasToKernel[iVec].iov_base = (void*)vmaStart;
- if (vmaSize > MAX_BYTES_PER_COMPACTION - bytesSentToCompact) {
- // Exceeded the max bytes that could be sent, so clamp
- // the end to avoid exceeding limit and issue compaction
- vmaSize = MAX_BYTES_PER_COMPACTION - bytesSentToCompact;
+ int error = madviseVmasFromBatch(pidfd, batch, madviseType, &bytesProcessedInSend);
+ if (error < 0) {
+ // Returns standard linux errno code
+ return error;
}
-
- vmasToKernel[iVec].iov_len = vmaSize;
- bytesSentToCompact += vmaSize;
- ++iVec;
- if (bytesSentToCompact >= MAX_BYTES_PER_COMPACTION) {
- // Ran out of bytes within iovec, dispatch compaction.
- vmaOffset += vmaSize;
+ if (CC_UNLIKELY(bytesProcessedInSend == 0)) {
+ // This means there was a problem consuming bytes,
+ // bail out since no forward progress can be made with this batch
break;
}
-
- next_vma:
- // Finished current VMA, and have more bytes remaining
- vmaOffset = 0;
- ++iVma;
- }
-
- ATRACE_BEGIN(StringPrintf("Compact %d VMAs", iVec).c_str());
- auto bytesProcessed = process_madvise(pidfd, vmasToKernel, iVec, madviseType, 0);
- ATRACE_END();
-
- if (CC_UNLIKELY(bytesProcessed == -1)) {
- if (errno == EINVAL) {
- // This error is somewhat common due to an unevictable VMA if this is
- // the case silently skip the bad VMA and continue compacting the rest.
- continue;
- } else {
- // Forward irrecoverable errors and bail out compaction
- return -errno;
- }
- }
-
- totalBytesProcessed += bytesProcessed;
+ totalBytesProcessed += bytesProcessedInSend;
+ } while (batch.totalBytes > 0 && batch.totalVmas > 0);
}
return totalBytesProcessed;
@@ -203,6 +346,7 @@ static int getAnyPageAdvice(const Vma& vma) {
static int64_t compactProcess(int pid, VmaToAdviseFunc vmaToAdviseFunc) {
cancelRunningCompaction.store(false);
+ ATRACE_BEGIN("CollectVmas");
ProcMemInfo meminfo(pid);
std::vector<Vma> pageoutVmas, coldVmas;
auto vmaCollectorCb = [&coldVmas,&pageoutVmas,&vmaToAdviseFunc](const Vma& vma) {
@@ -217,6 +361,7 @@ static int64_t compactProcess(int pid, VmaToAdviseFunc vmaToAdviseFunc) {
}
};
meminfo.ForEachVmaFromMaps(vmaCollectorCb);
+ ATRACE_END();
int64_t pageoutBytes = compactMemory(pageoutVmas, pid, MADV_PAGEOUT);
if (pageoutBytes < 0) {
diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
index ceac1023dfb0..870257802608 100644
--- a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
+++ b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
@@ -1937,6 +1937,9 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager {
updatePasswordQualityCacheForUserGroup(userHandle);
mPolicyCache.onUserRemoved(userHandle);
+ if (isManagedProfile(userHandle)) {
+ clearManagedProfileApnUnchecked();
+ }
isOrgOwned = mOwners.isProfileOwnerOfOrganizationOwnedDevice(userHandle);
mOwners.removeProfileOwner(userHandle);
@@ -3116,6 +3119,7 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager {
deleteTransferOwnershipBundleLocked(metadata.userId);
}
updateSystemUpdateFreezePeriodsRecord(/* saveIfChanged */ true);
+ pushUserControlDisabledPackagesLocked(metadata.userId);
}
private void maybeLogStart() {
@@ -3178,18 +3182,22 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager {
startOwnerService(userId, "start-user");
}
- // TODO(b/218639412): Once PM stores these on a per-user basis, push even empty lists to handle
- // DO/PO removal correctly.
void pushUserControlDisabledPackagesLocked(int userId) {
- if (userId != mOwners.getDeviceOwnerUserId()) {
- return;
- }
- ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
- if (deviceOwner == null || deviceOwner.protectedPackages == null) {
- return;
+ final int targetUserId;
+ final ActiveAdmin owner;
+ if (getDeviceOwnerUserIdUncheckedLocked() == userId) {
+ owner = getDeviceOwnerAdminLocked();
+ targetUserId = UserHandle.USER_ALL;
+ } else {
+ owner = getProfileOwnerAdminLocked(userId);
+ targetUserId = userId;
}
- mInjector.getPackageManagerInternal().setDeviceOwnerProtectedPackages(
- deviceOwner.info.getPackageName(), deviceOwner.protectedPackages);
+
+ List<String> protectedPackages = (owner == null || owner.protectedPackages == null)
+ ? Collections.emptyList() : owner.protectedPackages;
+ mInjector.binderWithCleanCallingIdentity(() ->
+ mInjector.getPackageManagerInternal().setOwnerProtectedPackages(
+ targetUserId, protectedPackages));
}
@Override
@@ -8755,6 +8763,18 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager {
}
}
+ private void clearManagedProfileApnUnchecked() {
+ if (!mHasTelephonyFeature) {
+ return;
+ }
+ final List<ApnSetting> apns = getOverrideApnsUnchecked();
+ for (ApnSetting apn : apns) {
+ if (apn.getApnTypeBitmask() == ApnSetting.TYPE_ENTERPRISE) {
+ removeOverrideApnUnchecked(apn.getId());
+ }
+ }
+ }
+
private void clearDeviceOwnerLocked(ActiveAdmin admin, int userId) {
mDeviceAdminServiceController.stopServiceForOwner(userId, "clear-device-owner");
@@ -12095,6 +12115,10 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager {
}
}
+ private boolean isManagedProfileOwner(CallerIdentity caller) {
+ return isProfileOwner(caller) && isManagedProfile(caller.getUserId());
+ }
+
private boolean isDefaultSupervisor(CallerIdentity caller) {
final String supervisor = mContext.getResources().getString(
com.android.internal.R.string.config_defaultSupervisionProfileOwnerComponent);
@@ -16295,7 +16319,7 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager {
final CallerIdentity caller = getCallerIdentity(who);
if (apnSetting.getApnTypeBitmask() == ApnSetting.TYPE_ENTERPRISE) {
Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
- || isProfileOwner(caller));
+ || isManagedProfileOwner(caller));
} else {
Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
}
@@ -16323,7 +16347,7 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager {
if (apn != null && apn.getApnTypeBitmask() == ApnSetting.TYPE_ENTERPRISE
&& apnSetting.getApnTypeBitmask() == ApnSetting.TYPE_ENTERPRISE) {
Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
- || isProfileOwner(caller));
+ || isManagedProfileOwner(caller));
} else {
Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
}
@@ -16351,7 +16375,7 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager {
ApnSetting apn = getApnSetting(apnId);
if (apn != null && apn.getApnTypeBitmask() == ApnSetting.TYPE_ENTERPRISE) {
Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
- || isProfileOwner(caller));
+ || isManagedProfileOwner(caller));
} else {
Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
}
@@ -16396,8 +16420,20 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager {
}
Objects.requireNonNull(who, "ComponentName is null");
final CallerIdentity caller = getCallerIdentity(who);
- Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
- return getOverrideApnsUnchecked();
+ Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
+ || isManagedProfileOwner(caller));
+ List<ApnSetting> apnSettings = getOverrideApnsUnchecked();
+ if (isProfileOwner(caller)) {
+ List<ApnSetting> apnSettingList = new ArrayList<>();
+ for (ApnSetting apnSetting : apnSettings) {
+ if (apnSetting.getApnTypeBitmask() == ApnSetting.TYPE_ENTERPRISE) {
+ apnSettingList.add(apnSetting);
+ }
+ }
+ return apnSettingList;
+ } else {
+ return apnSettings;
+ }
}
private List<ApnSetting> getOverrideApnsUnchecked() {
@@ -16967,23 +17003,20 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager {
Objects.requireNonNull(who, "ComponentName is null");
Objects.requireNonNull(packages, "packages is null");
final CallerIdentity caller = getCallerIdentity(who);
- Preconditions.checkCallAuthorization(
- isDefaultDeviceOwner(caller) || isFinancedDeviceOwner(caller));
+ Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller) || isProfileOwner(caller)
+ || isFinancedDeviceOwner(caller));
checkCanExecuteOrThrowUnsafe(
DevicePolicyManager.OPERATION_SET_USER_CONTROL_DISABLED_PACKAGES);
synchronized (getLockObject()) {
- ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
- if (!Objects.equals(deviceOwner.protectedPackages, packages)) {
- deviceOwner.protectedPackages = packages.isEmpty() ? null : packages;
+ ActiveAdmin owner = getDeviceOrProfileOwnerAdminLocked(caller.getUserId());
+ if (!Objects.equals(owner.protectedPackages, packages)) {
+ owner.protectedPackages = packages.isEmpty() ? null : packages;
saveSettingsLocked(caller.getUserId());
+ pushUserControlDisabledPackagesLocked(caller.getUserId());
}
}
- mInjector.binderWithCleanCallingIdentity(
- () -> mInjector.getPackageManagerInternal().setDeviceOwnerProtectedPackages(
- who.getPackageName(), packages));
-
DevicePolicyEventLogger
.createEvent(DevicePolicyEnums.SET_USER_CONTROL_DISABLED_PACKAGES)
.setAdmin(who)
@@ -16996,11 +17029,11 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager {
Objects.requireNonNull(who, "ComponentName is null");
final CallerIdentity caller = getCallerIdentity(who);
- Preconditions.checkCallAuthorization(
- isDefaultDeviceOwner(caller) || isFinancedDeviceOwner(caller));
+ Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller) || isProfileOwner(caller)
+ || isFinancedDeviceOwner(caller));
synchronized (getLockObject()) {
- ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
+ ActiveAdmin deviceOwner = getDeviceOrProfileOwnerAdminLocked(caller.getUserId());
return deviceOwner.protectedPackages != null
? deviceOwner.protectedPackages : Collections.emptyList();
}
diff --git a/services/java/com/android/server/SystemServer.java b/services/java/com/android/server/SystemServer.java
index 80f0186a2528..ef311c249c5f 100644
--- a/services/java/com/android/server/SystemServer.java
+++ b/services/java/com/android/server/SystemServer.java
@@ -1057,6 +1057,7 @@ public final class SystemServer implements Dumpable {
t.traceBegin("StartWatchdog");
final Watchdog watchdog = Watchdog.getInstance();
watchdog.start();
+ mDumper.addDumpable(watchdog);
t.traceEnd();
Slog.i(TAG, "Reading configuration...");
diff --git a/services/tests/mockingservicestests/src/com/android/server/alarm/AlarmManagerServiceTest.java b/services/tests/mockingservicestests/src/com/android/server/alarm/AlarmManagerServiceTest.java
index 8461b39f8899..17b42260948d 100644
--- a/services/tests/mockingservicestests/src/com/android/server/alarm/AlarmManagerServiceTest.java
+++ b/services/tests/mockingservicestests/src/com/android/server/alarm/AlarmManagerServiceTest.java
@@ -3220,34 +3220,19 @@ public class AlarmManagerServiceTest {
when(mRoleManager.getRoleHolders(RoleManager.ROLE_SYSTEM_WELLBEING)).thenReturn(
Arrays.asList(package4));
- mockChangeEnabled(SCHEDULE_EXACT_ALARM_DENIED_BY_DEFAULT, true);
- mService.mConstants.SCHEDULE_EXACT_ALARM_DENIED_BY_DEFAULT = false;
- mService.mConstants.EXACT_ALARM_DENY_LIST = new ArraySet<>(new String[] {
- package1,
- package3,
- });
-
- // Deny listed packages will be false.
- assertFalse(mService.isScheduleExactAlarmAllowedByDefault(package1, uid1));
- assertTrue(mService.isScheduleExactAlarmAllowedByDefault(package2, uid2));
- assertFalse(mService.isScheduleExactAlarmAllowedByDefault(package3, uid3));
- assertTrue(mService.isScheduleExactAlarmAllowedByDefault(package4, uid4));
-
mockChangeEnabled(SCHEDULE_EXACT_ALARM_DENIED_BY_DEFAULT, false);
- mService.mConstants.SCHEDULE_EXACT_ALARM_DENIED_BY_DEFAULT = true;
mService.mConstants.EXACT_ALARM_DENY_LIST = new ArraySet<>(new String[] {
package1,
package3,
});
- // Same as above, deny listed packages will be false.
+ // Deny listed packages will be false.
assertFalse(mService.isScheduleExactAlarmAllowedByDefault(package1, uid1));
assertTrue(mService.isScheduleExactAlarmAllowedByDefault(package2, uid2));
assertFalse(mService.isScheduleExactAlarmAllowedByDefault(package3, uid3));
assertTrue(mService.isScheduleExactAlarmAllowedByDefault(package4, uid4));
mockChangeEnabled(SCHEDULE_EXACT_ALARM_DENIED_BY_DEFAULT, true);
- mService.mConstants.SCHEDULE_EXACT_ALARM_DENIED_BY_DEFAULT = true;
mService.mConstants.EXACT_ALARM_DENY_LIST = new ArraySet<>(new String[] {
package1,
package3,
diff --git a/services/tests/mockingservicestests/src/com/android/server/am/BackgroundRestrictionTest.java b/services/tests/mockingservicestests/src/com/android/server/am/BackgroundRestrictionTest.java
index 009dae51e94b..fa8d569d8e3c 100644
--- a/services/tests/mockingservicestests/src/com/android/server/am/BackgroundRestrictionTest.java
+++ b/services/tests/mockingservicestests/src/com/android/server/am/BackgroundRestrictionTest.java
@@ -585,6 +585,7 @@ public final class BackgroundRestrictionTest {
DeviceConfigSession<Long> bgCurrentDrainInteractionGracePeriod = null;
DeviceConfigSession<Float> bgCurrentDrainRestrictedBucketThreshold = null;
DeviceConfigSession<Float> bgCurrentDrainBgRestrictedThreshold = null;
+ DeviceConfigSession<Boolean> bgCurrentDrainAutoRestrictAbusiveApps = null;
DeviceConfigSession<Boolean> bgPromptFgsWithNotiToBgRestricted = null;
DeviceConfigSession<Boolean> bgPromptAbusiveAppToBgRestricted = null;
DeviceConfigSession<Long> bgNotificationMinInterval = null;
@@ -644,6 +645,14 @@ public final class BackgroundRestrictionTest {
isLowRamDeviceStatic() ? 1 : 0]);
bgCurrentDrainBgRestrictedThreshold.set(bgRestrictedThreshold);
+ bgCurrentDrainAutoRestrictAbusiveApps = new DeviceConfigSession<>(
+ DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
+ AppBatteryPolicy.KEY_BG_CURRENT_DRAIN_AUTO_RESTRICT_ABUSIVE_APPS_ENABLED,
+ DeviceConfig::getBoolean,
+ mContext.getResources().getBoolean(
+ R.bool.config_bg_current_drain_auto_restrict_abusive_apps));
+ bgCurrentDrainAutoRestrictAbusiveApps.set(true);
+
bgPromptFgsWithNotiToBgRestricted = new DeviceConfigSession<>(
DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
ConstantsObserver.KEY_BG_PROMPT_FGS_WITH_NOTIFICATION_TO_BG_RESTRICTED,
@@ -1099,6 +1108,7 @@ public final class BackgroundRestrictionTest {
closeIfNotNull(bgCurrentDrainInteractionGracePeriod);
closeIfNotNull(bgCurrentDrainRestrictedBucketThreshold);
closeIfNotNull(bgCurrentDrainBgRestrictedThreshold);
+ closeIfNotNull(bgCurrentDrainAutoRestrictAbusiveApps);
closeIfNotNull(bgPromptFgsWithNotiToBgRestricted);
closeIfNotNull(bgPromptAbusiveAppToBgRestricted);
closeIfNotNull(bgNotificationMinInterval);
@@ -1651,6 +1661,7 @@ public final class BackgroundRestrictionTest {
DeviceConfigSession<Float> bgCurrentDrainBgRestrictedThreshold = null;
DeviceConfigSession<Float> bgCurrentDrainRestrictedBucketHighThreshold = null;
DeviceConfigSession<Float> bgCurrentDrainBgRestrictedHighThreshold = null;
+ DeviceConfigSession<Boolean> bgCurrentDrainAutoRestrictAbusiveApps = null;
DeviceConfigSession<Long> bgMediaPlaybackMinDurationThreshold = null;
DeviceConfigSession<Long> bgLocationMinDurationThreshold = null;
DeviceConfigSession<Boolean> bgCurrentDrainEventDurationBasedThresholdEnabled = null;
@@ -1736,6 +1747,14 @@ public final class BackgroundRestrictionTest {
isLowRamDeviceStatic() ? 1 : 0]);
bgCurrentDrainBgRestrictedHighThreshold.set(bgRestrictedHighThreshold);
+ bgCurrentDrainAutoRestrictAbusiveApps = new DeviceConfigSession<>(
+ DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
+ AppBatteryPolicy.KEY_BG_CURRENT_DRAIN_AUTO_RESTRICT_ABUSIVE_APPS_ENABLED,
+ DeviceConfig::getBoolean,
+ mContext.getResources().getBoolean(
+ R.bool.config_bg_current_drain_auto_restrict_abusive_apps));
+ bgCurrentDrainAutoRestrictAbusiveApps.set(true);
+
bgMediaPlaybackMinDurationThreshold = new DeviceConfigSession<>(
DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
AppBatteryPolicy.KEY_BG_CURRENT_DRAIN_MEDIA_PLAYBACK_MIN_DURATION,
@@ -2226,6 +2245,7 @@ public final class BackgroundRestrictionTest {
closeIfNotNull(bgCurrentDrainBgRestrictedThreshold);
closeIfNotNull(bgCurrentDrainRestrictedBucketHighThreshold);
closeIfNotNull(bgCurrentDrainBgRestrictedHighThreshold);
+ closeIfNotNull(bgCurrentDrainAutoRestrictAbusiveApps);
closeIfNotNull(bgMediaPlaybackMinDurationThreshold);
closeIfNotNull(bgLocationMinDurationThreshold);
closeIfNotNull(bgCurrentDrainEventDurationBasedThresholdEnabled);
diff --git a/services/tests/mockingservicestests/src/com/android/server/job/controllers/PrefetchControllerTest.java b/services/tests/mockingservicestests/src/com/android/server/job/controllers/PrefetchControllerTest.java
index 8a954caad939..5f9f1b226958 100644
--- a/services/tests/mockingservicestests/src/com/android/server/job/controllers/PrefetchControllerTest.java
+++ b/services/tests/mockingservicestests/src/com/android/server/job/controllers/PrefetchControllerTest.java
@@ -233,27 +233,34 @@ public class PrefetchControllerTest {
@Test
public void testConstantsUpdating_ValidValues() {
setDeviceConfigLong(PcConstants.KEY_LAUNCH_TIME_THRESHOLD_MS, 5 * HOUR_IN_MILLIS);
+ setDeviceConfigLong(PcConstants.KEY_LAUNCH_TIME_ALLOWANCE_MS, 5 * MINUTE_IN_MILLIS);
assertEquals(5 * HOUR_IN_MILLIS, mPrefetchController.getLaunchTimeThresholdMs());
+ assertEquals(5 * MINUTE_IN_MILLIS, mPrefetchController.getLaunchTimeAllowanceMs());
}
@Test
public void testConstantsUpdating_InvalidValues() {
// Test negatives/too low.
setDeviceConfigLong(PcConstants.KEY_LAUNCH_TIME_THRESHOLD_MS, 4 * MINUTE_IN_MILLIS);
+ setDeviceConfigLong(PcConstants.KEY_LAUNCH_TIME_ALLOWANCE_MS, -MINUTE_IN_MILLIS);
assertEquals(HOUR_IN_MILLIS, mPrefetchController.getLaunchTimeThresholdMs());
+ assertEquals(0, mPrefetchController.getLaunchTimeAllowanceMs());
// Test larger than a day. Controller should cap at one day.
setDeviceConfigLong(PcConstants.KEY_LAUNCH_TIME_THRESHOLD_MS, 25 * HOUR_IN_MILLIS);
+ setDeviceConfigLong(PcConstants.KEY_LAUNCH_TIME_ALLOWANCE_MS, 5 * HOUR_IN_MILLIS);
assertEquals(24 * HOUR_IN_MILLIS, mPrefetchController.getLaunchTimeThresholdMs());
+ assertEquals(2 * HOUR_IN_MILLIS, mPrefetchController.getLaunchTimeAllowanceMs());
}
@Test
public void testConstantsUpdating_ThresholdChangesAlarms() {
final long launchDelayMs = 11 * HOUR_IN_MILLIS;
setDeviceConfigLong(PcConstants.KEY_LAUNCH_TIME_THRESHOLD_MS, 7 * HOUR_IN_MILLIS);
+ setDeviceConfigLong(PcConstants.KEY_LAUNCH_TIME_ALLOWANCE_MS, 0);
when(mUsageStatsManagerInternal
.getEstimatedPackageLaunchTime(SOURCE_PACKAGE, SOURCE_USER_ID))
.thenReturn(sSystemClock.millis() + launchDelayMs);
@@ -276,6 +283,7 @@ public class PrefetchControllerTest {
@Test
public void testConstraintNotSatisfiedWhenLaunchLate() {
+ setDeviceConfigLong(PcConstants.KEY_LAUNCH_TIME_ALLOWANCE_MS, 0);
setDeviceConfigLong(PcConstants.KEY_LAUNCH_TIME_THRESHOLD_MS, 7 * HOUR_IN_MILLIS);
final JobStatus job = createJobStatus("testConstraintNotSatisfiedWhenLaunchLate", 1);
@@ -290,6 +298,8 @@ public class PrefetchControllerTest {
@Test
public void testConstraintSatisfiedWhenLaunchSoon() {
+ setDeviceConfigLong(PcConstants.KEY_LAUNCH_TIME_ALLOWANCE_MS, 0);
+
final JobStatus job = createJobStatus("testConstraintSatisfiedWhenLaunchSoon", 2);
when(mUsageStatsManagerInternal
.getEstimatedPackageLaunchTime(SOURCE_PACKAGE, SOURCE_USER_ID))
@@ -338,6 +348,8 @@ public class PrefetchControllerTest {
@Test
public void testConstraintSatisfiedWhenWidget() {
+ setDeviceConfigLong(PcConstants.KEY_LAUNCH_TIME_ALLOWANCE_MS, 0);
+
final JobStatus jobNonWidget = createJobStatus("testConstraintSatisfiedWhenWidget", 1);
final JobStatus jobWidget = createJobStatus("testConstraintSatisfiedWhenWidget", 2);
@@ -365,6 +377,7 @@ public class PrefetchControllerTest {
@Test
public void testEstimatedLaunchTimeChangedToLate() {
setDeviceConfigLong(PcConstants.KEY_LAUNCH_TIME_THRESHOLD_MS, 7 * HOUR_IN_MILLIS);
+ setDeviceConfigLong(PcConstants.KEY_LAUNCH_TIME_ALLOWANCE_MS, 0);
when(mUsageStatsManagerInternal
.getEstimatedPackageLaunchTime(SOURCE_PACKAGE, SOURCE_USER_ID))
.thenReturn(sSystemClock.millis() + HOUR_IN_MILLIS);
@@ -393,6 +406,7 @@ public class PrefetchControllerTest {
@Test
public void testEstimatedLaunchTimeChangedToSoon() {
setDeviceConfigLong(PcConstants.KEY_LAUNCH_TIME_THRESHOLD_MS, 7 * HOUR_IN_MILLIS);
+ setDeviceConfigLong(PcConstants.KEY_LAUNCH_TIME_ALLOWANCE_MS, 0);
when(mUsageStatsManagerInternal
.getEstimatedPackageLaunchTime(SOURCE_PACKAGE, SOURCE_USER_ID))
.thenReturn(sSystemClock.millis() + 10 * HOUR_IN_MILLIS);
@@ -413,4 +427,36 @@ public class PrefetchControllerTest {
verify(mJobSchedulerService, timeout(DEFAULT_WAIT_MS)).onControllerStateChanged(any());
assertTrue(jobStatus.isConstraintSatisfied(JobStatus.CONSTRAINT_PREFETCH));
}
+
+ @Test
+ public void testEstimatedLaunchTimeAllowance() {
+ setDeviceConfigLong(PcConstants.KEY_LAUNCH_TIME_THRESHOLD_MS, 7 * HOUR_IN_MILLIS);
+ setDeviceConfigLong(PcConstants.KEY_LAUNCH_TIME_ALLOWANCE_MS, 15 * MINUTE_IN_MILLIS);
+ when(mUsageStatsManagerInternal
+ .getEstimatedPackageLaunchTime(SOURCE_PACKAGE, SOURCE_USER_ID))
+ .thenReturn(sSystemClock.millis() + 10 * HOUR_IN_MILLIS);
+
+ InOrder inOrder = inOrder(mUsageStatsManagerInternal);
+
+ JobStatus jobStatus = createJobStatus("testEstimatedLaunchTimeAllowance", 1);
+ trackJobs(jobStatus);
+ inOrder.verify(mUsageStatsManagerInternal, timeout(DEFAULT_WAIT_MS))
+ .getEstimatedPackageLaunchTime(SOURCE_PACKAGE, SOURCE_USER_ID);
+ // The allowance shouldn't shift the alarm
+ verify(mAlarmManager, timeout(DEFAULT_WAIT_MS).times(1))
+ .setWindow(
+ anyInt(), eq(sElapsedRealtimeClock.millis() + 3 * HOUR_IN_MILLIS),
+ anyLong(), eq(TAG_PREFETCH), any(), any());
+ assertFalse(jobStatus.isConstraintSatisfied(JobStatus.CONSTRAINT_PREFETCH));
+
+ mEstimatedLaunchTimeChangedListener.onEstimatedLaunchTimeChanged(SOURCE_USER_ID,
+ SOURCE_PACKAGE, sSystemClock.millis() + HOUR_IN_MILLIS);
+
+ inOrder.verify(mUsageStatsManagerInternal, timeout(DEFAULT_WAIT_MS).times(0))
+ .getEstimatedPackageLaunchTime(SOURCE_PACKAGE, SOURCE_USER_ID);
+ verify(mJobSchedulerService, timeout(DEFAULT_WAIT_MS)).onControllerStateChanged(any());
+ assertTrue(jobStatus.isConstraintSatisfied(JobStatus.CONSTRAINT_PREFETCH));
+
+ sSystemClock = getShiftedClock(sSystemClock, HOUR_IN_MILLIS + MINUTE_IN_MILLIS);
+ }
}
diff --git a/services/tests/mockingservicestests/src/com/android/server/pm/BackgroundDexOptServiceUnitTest.java b/services/tests/mockingservicestests/src/com/android/server/pm/BackgroundDexOptServiceUnitTest.java
index 444db9128662..da5c8f06bc86 100644
--- a/services/tests/mockingservicestests/src/com/android/server/pm/BackgroundDexOptServiceUnitTest.java
+++ b/services/tests/mockingservicestests/src/com/android/server/pm/BackgroundDexOptServiceUnitTest.java
@@ -16,6 +16,9 @@
package com.android.server.pm;
+import static com.android.server.pm.BackgroundDexOptService.STATUS_DEX_OPT_FAILED;
+import static com.android.server.pm.BackgroundDexOptService.STATUS_OK;
+
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
@@ -23,12 +26,14 @@ import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.testng.Assert.assertThrows;
+import android.annotation.Nullable;
import android.app.job.JobInfo;
import android.app.job.JobParameters;
import android.app.job.JobScheduler;
@@ -38,10 +43,13 @@ import android.content.Intent;
import android.content.IntentFilter;
import android.os.HandlerThread;
import android.os.PowerManager;
+import android.util.Log;
+import com.android.internal.util.IndentingPrintWriter;
import com.android.server.LocalServices;
import com.android.server.PinnerService;
import com.android.server.pm.dex.DexManager;
+import com.android.server.pm.dex.DexoptOptions;
import org.junit.After;
import org.junit.Before;
@@ -52,7 +60,11 @@ import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
+import java.io.ByteArrayOutputStream;
+import java.io.PrintWriter;
+import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.stream.Collectors;
@@ -66,8 +78,12 @@ public final class BackgroundDexOptServiceUnitTest {
private static final long TEST_WAIT_TIMEOUT_MS = 10_000;
- private static final List<String> DEFAULT_PACKAGE_LIST = List.of("aaa", "bbb");
- private static final List<String> EMPTY_PACKAGE_LIST = List.of();
+ private static final String PACKAGE_AAA = "aaa";
+ private static final List<String> DEFAULT_PACKAGE_LIST = List.of(PACKAGE_AAA, "bbb");
+ private int mDexOptResultForPackageAAA = PackageDexOptimizer.DEX_OPT_PERFORMED;
+
+ // Store expected dexopt sequence for verification.
+ private ArrayList<DexOptInfo> mDexInfoSequence = new ArrayList<>();
@Mock
private Context mContext;
@@ -116,14 +132,23 @@ public final class BackgroundDexOptServiceUnitTest {
when(mInjector.getDexOptThermalCutoff()).thenReturn(PowerManager.THERMAL_STATUS_CRITICAL);
when(mInjector.getCurrentThermalStatus()).thenReturn(PowerManager.THERMAL_STATUS_NONE);
when(mInjector.supportSecondaryDex()).thenReturn(true);
- when(mDexOptHelper.getOptimizablePackages(any())).thenReturn(DEFAULT_PACKAGE_LIST);
- when(mDexOptHelper.performDexOptWithStatus(any())).thenReturn(
- PackageDexOptimizer.DEX_OPT_PERFORMED);
- when(mDexOptHelper.performDexOpt(any())).thenReturn(true);
+ setupDexOptHelper();
mService = new BackgroundDexOptService(mInjector);
}
+ private void setupDexOptHelper() {
+ when(mDexOptHelper.getOptimizablePackages(any())).thenReturn(DEFAULT_PACKAGE_LIST);
+ when(mDexOptHelper.performDexOptWithStatus(any())).thenAnswer(inv -> {
+ DexoptOptions opt = inv.getArgument(0);
+ if (opt.getPackageName().equals(PACKAGE_AAA)) {
+ return mDexOptResultForPackageAAA;
+ }
+ return PackageDexOptimizer.DEX_OPT_PERFORMED;
+ });
+ when(mDexOptHelper.performDexOpt(any())).thenReturn(true);
+ }
+
@After
public void tearDown() throws Exception {
LocalServices.removeServiceForTest(BackgroundDexOptService.class);
@@ -159,7 +184,7 @@ public final class BackgroundDexOptServiceUnitTest {
@Test
public void testNoExecutionForNoOptimizablePackages() {
initUntilBootCompleted();
- when(mDexOptHelper.getOptimizablePackages(any())).thenReturn(EMPTY_PACKAGE_LIST);
+ when(mDexOptHelper.getOptimizablePackages(any())).thenReturn(Collections.emptyList());
assertThat(mService.onStartJob(mJobServiceForPostBoot,
mJobParametersForPostBoot)).isFalse();
@@ -170,15 +195,70 @@ public final class BackgroundDexOptServiceUnitTest {
public void testPostBootUpdateFullRun() {
initUntilBootCompleted();
- runFullJob(mJobServiceForPostBoot, mJobParametersForPostBoot, false, 1);
+ runFullJob(mJobServiceForPostBoot, mJobParametersForPostBoot,
+ /* expectedReschedule= */ false, /* expectedStatus= */ STATUS_OK,
+ /* totalJobFinishedWithParams= */ 1, /* expectedSkippedPackage= */ null);
+ }
+
+ @Test
+ public void testPostBootUpdateFullRunWithPackageFailure() {
+ mDexOptResultForPackageAAA = PackageDexOptimizer.DEX_OPT_FAILED;
+
+ initUntilBootCompleted();
+
+ runFullJob(mJobServiceForPostBoot, mJobParametersForPostBoot,
+ /* expectedReschedule= */ false, /* expectedStatus= */ STATUS_DEX_OPT_FAILED,
+ /* totalJobFinishedWithParams= */ 1, /* expectedSkippedPackage= */ PACKAGE_AAA);
+
+ assertThat(getFailedPackageNamesPrimary()).containsExactly(PACKAGE_AAA);
+ assertThat(getFailedPackageNamesSecondary()).isEmpty();
}
@Test
public void testIdleJobFullRun() {
initUntilBootCompleted();
+ runFullJob(mJobServiceForPostBoot, mJobParametersForPostBoot,
+ /* expectedReschedule= */ false, /* expectedStatus= */ STATUS_OK,
+ /* totalJobFinishedWithParams= */ 1, /* expectedSkippedPackage= */ null);
+ runFullJob(mJobServiceForIdle, mJobParametersForIdle,
+ /* expectedReschedule= */ true, /* expectedStatus= */ STATUS_OK,
+ /* totalJobFinishedWithParams= */ 1, /* expectedSkippedPackage= */ null);
+ }
+
+ @Test
+ public void testIdleJobFullRunWithFailureOnceAndSuccessAfterUpdate() {
+ mDexOptResultForPackageAAA = PackageDexOptimizer.DEX_OPT_FAILED;
+
+ initUntilBootCompleted();
+
+ runFullJob(mJobServiceForPostBoot, mJobParametersForPostBoot,
+ /* expectedReschedule= */ false, /* expectedStatus= */ STATUS_DEX_OPT_FAILED,
+ /* totalJobFinishedWithParams= */ 1, /* expectedSkippedPackage= */ PACKAGE_AAA);
+
+ assertThat(getFailedPackageNamesPrimary()).containsExactly(PACKAGE_AAA);
+ assertThat(getFailedPackageNamesSecondary()).isEmpty();
+
+ runFullJob(mJobServiceForIdle, mJobParametersForIdle,
+ /* expectedReschedule= */ true, /* expectedStatus= */ STATUS_OK,
+ /* totalJobFinishedWithParams= */ 1, /* expectedSkippedPackage= */ PACKAGE_AAA);
+
+ assertThat(getFailedPackageNamesPrimary()).containsExactly(PACKAGE_AAA);
+ assertThat(getFailedPackageNamesSecondary()).isEmpty();
+
+ mService.notifyPackageChanged(PACKAGE_AAA);
- runFullJob(mJobServiceForPostBoot, mJobParametersForPostBoot, false, 1);
- runFullJob(mJobServiceForIdle, mJobParametersForIdle, true, 2);
+ assertThat(getFailedPackageNamesPrimary()).isEmpty();
+ assertThat(getFailedPackageNamesSecondary()).isEmpty();
+
+ // Succeed this time.
+ mDexOptResultForPackageAAA = PackageDexOptimizer.DEX_OPT_PERFORMED;
+
+ runFullJob(mJobServiceForIdle, mJobParametersForIdle,
+ /* expectedReschedule= */ true, /* expectedStatus= */ STATUS_OK,
+ /* totalJobFinishedWithParams= */ 2, /* expectedSkippedPackage= */ null);
+
+ assertThat(getFailedPackageNamesPrimary()).isEmpty();
+ assertThat(getFailedPackageNamesSecondary()).isEmpty();
}
@Test
@@ -404,8 +484,10 @@ public final class BackgroundDexOptServiceUnitTest {
}
private void runFullJob(BackgroundDexOptJobService jobService, JobParameters params,
- boolean expectedReschedule, int totalJobRuns) {
+ boolean expectedReschedule, int expectedStatus, int totalJobFinishedWithParams,
+ @Nullable String expectedSkippedPackage) {
when(mInjector.createAndStartThread(any(), any())).thenReturn(Thread.currentThread());
+ addFullRunSequence(expectedSkippedPackage);
assertThat(mService.onStartJob(jobService, params)).isTrue();
ArgumentCaptor<Runnable> argThreadRunnable = ArgumentCaptor.forClass(Runnable.class);
@@ -413,20 +495,99 @@ public final class BackgroundDexOptServiceUnitTest {
argThreadRunnable.getValue().run();
- verify(jobService).jobFinished(params, expectedReschedule);
+ verify(jobService, times(totalJobFinishedWithParams)).jobFinished(params,
+ expectedReschedule);
// Never block
verify(mDexOptHelper, never()).controlDexOptBlocking(true);
- verifyPerformDexOpt(DEFAULT_PACKAGE_LIST, totalJobRuns);
+ verifyPerformDexOpt();
+ assertThat(getLastExecutionStatus()).isEqualTo(expectedStatus);
}
- private void verifyPerformDexOpt(List<String> pkgs, int expectedRuns) {
+ private void verifyPerformDexOpt() {
InOrder inOrder = inOrder(mDexOptHelper);
- for (int i = 0; i < expectedRuns; i++) {
- for (String pkg : pkgs) {
- inOrder.verify(mDexOptHelper, times(1)).performDexOptWithStatus(argThat((option) ->
- option.getPackageName().equals(pkg) && !option.isDexoptOnlySecondaryDex()));
- inOrder.verify(mDexOptHelper, times(1)).performDexOpt(argThat((option) ->
- option.getPackageName().equals(pkg) && option.isDexoptOnlySecondaryDex()));
+ inOrder.verify(mDexOptHelper).getOptimizablePackages(any());
+ for (DexOptInfo info : mDexInfoSequence) {
+ if (info.isPrimary) {
+ verify(mDexOptHelper).performDexOptWithStatus(
+ argThat((option) -> option.getPackageName().equals(info.packageName)
+ && !option.isDexoptOnlySecondaryDex()));
+ } else {
+ inOrder.verify(mDexOptHelper).performDexOpt(
+ argThat((option) -> option.getPackageName().equals(info.packageName)
+ && option.isDexoptOnlySecondaryDex()));
+ }
+ }
+
+ // Even InOrder cannot check the order if the same call is made multiple times.
+ // To check the order across multiple runs, we reset the mock so that order can be checked
+ // in each call.
+ mDexInfoSequence.clear();
+ reset(mDexOptHelper);
+ setupDexOptHelper();
+ }
+
+ private String findDumpValueForKey(String key) {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ PrintWriter pw = new PrintWriter(out, true);
+ IndentingPrintWriter writer = new IndentingPrintWriter(pw, "");
+ try {
+ mService.dump(writer);
+ writer.flush();
+ Log.i(TAG, "dump output:" + out.toString());
+ for (String line : out.toString().split(System.lineSeparator())) {
+ String[] vals = line.split(":");
+ if (vals[0].equals(key)) {
+ if (vals.length == 2) {
+ return vals[1].strip();
+ } else {
+ break;
+ }
+ }
+ }
+ return "";
+ } finally {
+ writer.close();
+ }
+ }
+
+ List<String> findStringListFromDump(String key) {
+ String values = findDumpValueForKey(key);
+ if (values.isEmpty()) {
+ return Collections.emptyList();
+ }
+ return Arrays.asList(values.split(","));
+ }
+
+ private List<String> getFailedPackageNamesPrimary() {
+ return findStringListFromDump("mFailedPackageNamesPrimary");
+ }
+
+ private List<String> getFailedPackageNamesSecondary() {
+ return findStringListFromDump("mFailedPackageNamesSecondary");
+ }
+
+ private int getLastExecutionStatus() {
+ return Integer.parseInt(findDumpValueForKey("mLastExecutionStatus"));
+ }
+
+ private static class DexOptInfo {
+ public final String packageName;
+ public final boolean isPrimary;
+
+ private DexOptInfo(String packageName, boolean isPrimary) {
+ this.packageName = packageName;
+ this.isPrimary = isPrimary;
+ }
+ }
+
+ private void addFullRunSequence(@Nullable String expectedSkippedPackage) {
+ for (String packageName : DEFAULT_PACKAGE_LIST) {
+ if (packageName.equals(expectedSkippedPackage)) {
+ // only fails primary dexopt in mocking but add secodary
+ mDexInfoSequence.add(new DexOptInfo(packageName, /* isPrimary= */ false));
+ } else {
+ mDexInfoSequence.add(new DexOptInfo(packageName, /* isPrimary= */ true));
+ mDexInfoSequence.add(new DexOptInfo(packageName, /* isPrimary= */ false));
}
}
}
diff --git a/services/tests/mockingservicestests/src/com/android/server/pm/DeletePackageHelperTest.kt b/services/tests/mockingservicestests/src/com/android/server/pm/DeletePackageHelperTest.kt
index c9598bdc8823..e30f3d26119f 100644
--- a/services/tests/mockingservicestests/src/com/android/server/pm/DeletePackageHelperTest.kt
+++ b/services/tests/mockingservicestests/src/com/android/server/pm/DeletePackageHelperTest.kt
@@ -69,13 +69,34 @@ class DeletePackageHelperTest {
}
@Test
- fun deleteSystemPackageFailsIfNotAdmin() {
+ fun deleteSystemPackageFailsIfNotAdminAndNotProfile() {
val ps = mPms.mSettings.getPackageLPr("a.data.package")
whenever(PackageManagerServiceUtils.isSystemApp(ps)).thenReturn(true)
whenever(mUserManagerInternal.getUserInfo(1)).thenReturn(UserInfo(1, "test", 0))
+ whenever(mUserManagerInternal.getProfileParentId(1)).thenReturn(1)
val dph = DeletePackageHelper(mPms)
- val result = dph.deletePackageX("a.data.package", 1L, 1, 0, false)
+ val result = dph.deletePackageX("a.data.package", 1L, 1,
+ PackageManager.DELETE_SYSTEM_APP, false)
+
+ assertThat(result).isEqualTo(PackageManager.DELETE_FAILED_USER_RESTRICTED)
+ }
+
+ @Test
+ fun deleteSystemPackageFailsIfProfileOfNonAdmin() {
+ val userId = 1
+ val parentId = 5
+ val ps = mPms.mSettings.getPackageLPr("a.data.package")
+ whenever(PackageManagerServiceUtils.isSystemApp(ps)).thenReturn(true)
+ whenever(mUserManagerInternal.getUserInfo(userId)).thenReturn(
+ UserInfo(userId, "test", UserInfo.FLAG_PROFILE))
+ whenever(mUserManagerInternal.getProfileParentId(userId)).thenReturn(parentId)
+ whenever(mUserManagerInternal.getUserInfo(parentId)).thenReturn(
+ UserInfo(userId, "testparent", 0))
+
+ val dph = DeletePackageHelper(mPms)
+ val result = dph.deletePackageX("a.data.package", 1L, userId,
+ PackageManager.DELETE_SYSTEM_APP, false)
assertThat(result).isEqualTo(PackageManager.DELETE_FAILED_USER_RESTRICTED)
}
@@ -93,4 +114,23 @@ class DeletePackageHelperTest {
assertThat(result).isEqualTo(PackageManager.DELETE_SUCCEEDED)
}
+
+ @Test
+ fun deleteSystemPackageSucceedsIfProfileOfAdmin() {
+ val userId = 1
+ val parentId = 5
+ val ps = mPms.mSettings.getPackageLPr("a.data.package")
+ whenever(PackageManagerServiceUtils.isSystemApp(ps)).thenReturn(true)
+ whenever(mUserManagerInternal.getUserInfo(userId)).thenReturn(
+ UserInfo(userId, "test", UserInfo.FLAG_PROFILE))
+ whenever(mUserManagerInternal.getProfileParentId(userId)).thenReturn(parentId)
+ whenever(mUserManagerInternal.getUserInfo(parentId)).thenReturn(
+ UserInfo(userId, "testparent", UserInfo.FLAG_ADMIN))
+
+ val dph = DeletePackageHelper(mPms)
+ val result = dph.deletePackageX("a.data.package", 1L, userId,
+ PackageManager.DELETE_SYSTEM_APP, false)
+
+ assertThat(result).isEqualTo(PackageManager.DELETE_SUCCEEDED)
+ }
} \ No newline at end of file
diff --git a/services/tests/mockingservicestests/src/com/android/server/sensorprivacy/CameraPrivacyLightControllerTest.java b/services/tests/mockingservicestests/src/com/android/server/sensorprivacy/CameraPrivacyLightControllerTest.java
index fa3e05a6b001..20cfd59973c3 100644
--- a/services/tests/mockingservicestests/src/com/android/server/sensorprivacy/CameraPrivacyLightControllerTest.java
+++ b/services/tests/mockingservicestests/src/com/android/server/sensorprivacy/CameraPrivacyLightControllerTest.java
@@ -24,20 +24,33 @@ import static com.android.dx.mockito.inline.extended.ExtendedMockito.verify;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.Mockito.atLeastOnce;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import android.app.AppOpsManager;
import android.content.Context;
+import android.content.res.Resources;
+import android.hardware.Sensor;
+import android.hardware.SensorEvent;
+import android.hardware.SensorEventListener;
+import android.hardware.SensorManager;
import android.hardware.lights.Light;
+import android.hardware.lights.LightState;
import android.hardware.lights.LightsManager;
import android.hardware.lights.LightsRequest;
+import android.os.Handler;
+import android.os.Looper;
import android.permission.PermissionManager;
import android.util.ArraySet;
import com.android.dx.mockito.inline.extended.ExtendedMockito;
+import com.android.internal.R;
import org.junit.After;
import org.junit.Before;
+import org.junit.Ignore;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
@@ -53,26 +66,43 @@ import java.util.stream.Collectors;
public class CameraPrivacyLightControllerTest {
+ private int mDayColor = 1;
+ private int mNightColor = 0;
+ private int mCameraPrivacyLightAlsAveragingIntervalMillis = 5000;
+ private int mCameraPrivacyLightAlsNightThreshold = (int) getLightSensorValue(15);
+
private MockitoSession mMockitoSession;
@Mock
private Context mContext;
@Mock
+ private Resources mResources;
+
+ @Mock
private LightsManager mLightsManager;
@Mock
private AppOpsManager mAppOpsManager;
@Mock
+ private SensorManager mSensorManager;
+
+ @Mock
private LightsManager.LightsSession mLightsSession;
+ @Mock
+ private Sensor mLightSensor;
+
private ArgumentCaptor<AppOpsManager.OnOpActiveChangedListener> mAppOpsListenerCaptor =
ArgumentCaptor.forClass(AppOpsManager.OnOpActiveChangedListener.class);
private ArgumentCaptor<LightsRequest> mLightsRequestCaptor =
ArgumentCaptor.forClass(LightsRequest.class);
+ private ArgumentCaptor<SensorEventListener> mLightSensorListenerCaptor =
+ ArgumentCaptor.forClass(SensorEventListener.class);
+
private Set<String> mExemptedPackages = new ArraySet<>();
private List<Light> mLights = new ArrayList<>();
@@ -86,11 +116,22 @@ public class CameraPrivacyLightControllerTest {
.spyStatic(PermissionManager.class)
.startMocking();
+ doReturn(mDayColor).when(mContext).getColor(R.color.camera_privacy_light_day);
+ doReturn(mNightColor).when(mContext).getColor(R.color.camera_privacy_light_night);
+
+ doReturn(mResources).when(mContext).getResources();
+ doReturn(mCameraPrivacyLightAlsAveragingIntervalMillis).when(mResources)
+ .getInteger(R.integer.config_cameraPrivacyLightAlsAveragingIntervalMillis);
+ doReturn(mCameraPrivacyLightAlsNightThreshold).when(mResources)
+ .getInteger(R.integer.config_cameraPrivacyLightAlsNightThreshold);
+
doReturn(mLightsManager).when(mContext).getSystemService(LightsManager.class);
doReturn(mAppOpsManager).when(mContext).getSystemService(AppOpsManager.class);
+ doReturn(mSensorManager).when(mContext).getSystemService(SensorManager.class);
doReturn(mLights).when(mLightsManager).getLights();
doReturn(mLightsSession).when(mLightsManager).openSession(anyInt());
+ doReturn(mLightSensor).when(mSensorManager).getDefaultSensor(Sensor.TYPE_LIGHT);
doReturn(mExemptedPackages)
.when(() -> PermissionManager.getIndicatorExemptedPackages(any()));
@@ -107,7 +148,7 @@ public class CameraPrivacyLightControllerTest {
@Test
public void testAppsOpsListenerNotRegisteredWithoutCameraLights() {
mLights.add(getNextLight(false));
- new CameraPrivacyLightController(mContext);
+ createCameraPrivacyLightController();
verify(mAppOpsManager, times(0)).startWatchingActive(any(), any(), any());
}
@@ -116,7 +157,7 @@ public class CameraPrivacyLightControllerTest {
public void testAppsOpsListenerRegisteredWithCameraLight() {
mLights.add(getNextLight(true));
- new CameraPrivacyLightController(mContext);
+ createCameraPrivacyLightController();
verify(mAppOpsManager, times(1)).startWatchingActive(any(), any(), any());
}
@@ -128,14 +169,13 @@ public class CameraPrivacyLightControllerTest {
mLights.add(getNextLight(r.nextBoolean()));
}
- new CameraPrivacyLightController(mContext);
+ createCameraPrivacyLightController();
// Verify no session has been opened at this point.
verify(mLightsManager, times(0)).openSession(anyInt());
// Set camera op as active.
- verify(mAppOpsManager).startWatchingActive(any(), any(), mAppOpsListenerCaptor.capture());
- mAppOpsListenerCaptor.getValue().onOpActiveChanged(OPSTR_CAMERA, 10101, "pkg1", true);
+ openCamera();
// Verify session has been opened exactly once
verify(mLightsManager, times(1)).openSession(anyInt());
@@ -161,7 +201,7 @@ public class CameraPrivacyLightControllerTest {
public void testWillOnlyOpenOnceWhenTwoPackagesStartOp() {
mLights.add(getNextLight(true));
- new CameraPrivacyLightController(mContext);
+ createCameraPrivacyLightController();
verify(mAppOpsManager).startWatchingActive(any(), any(), mAppOpsListenerCaptor.capture());
@@ -176,7 +216,7 @@ public class CameraPrivacyLightControllerTest {
public void testWillCloseOnFinishOp() {
mLights.add(getNextLight(true));
- new CameraPrivacyLightController(mContext);
+ createCameraPrivacyLightController();
verify(mAppOpsManager).startWatchingActive(any(), any(), mAppOpsListenerCaptor.capture());
@@ -192,7 +232,7 @@ public class CameraPrivacyLightControllerTest {
public void testWillCloseOnFinishOpForAllPackages() {
mLights.add(getNextLight(true));
- new CameraPrivacyLightController(mContext);
+ createCameraPrivacyLightController();
int numUids = 100;
List<Integer> uids = new ArrayList<>(numUids);
@@ -226,7 +266,7 @@ public class CameraPrivacyLightControllerTest {
mLights.add(getNextLight(true));
mExemptedPackages.add("pkg1");
- new CameraPrivacyLightController(mContext);
+ createCameraPrivacyLightController();
verify(mAppOpsManager).startWatchingActive(any(), any(), mAppOpsListenerCaptor.capture());
@@ -235,6 +275,147 @@ public class CameraPrivacyLightControllerTest {
verify(mLightsManager, times(0)).openSession(anyInt());
}
+ @Test
+ public void testNoLightSensor() {
+ mLights.add(getNextLight(true));
+ doReturn(null).when(mSensorManager).getDefaultSensor(Sensor.TYPE_LIGHT);
+
+ createCameraPrivacyLightController();
+
+ openCamera();
+
+ verify(mLightsSession).requestLights(mLightsRequestCaptor.capture());
+ LightsRequest lightsRequest = mLightsRequestCaptor.getValue();
+ for (LightState lightState : lightsRequest.getLightStates()) {
+ assertEquals(mDayColor, lightState.getColor());
+ }
+ }
+
+ @Test
+ public void testALSListenerNotRegisteredUntilCameraIsOpened() {
+ mLights.add(getNextLight(true));
+ Sensor sensor = mock(Sensor.class);
+ doReturn(sensor).when(mSensorManager).getDefaultSensor(Sensor.TYPE_LIGHT);
+
+ CameraPrivacyLightController cplc = createCameraPrivacyLightController();
+
+ verify(mSensorManager, never()).registerListener(any(SensorEventListener.class),
+ any(Sensor.class), anyInt(), any(Handler.class));
+
+ openCamera();
+
+ verify(mSensorManager, times(1)).registerListener(mLightSensorListenerCaptor.capture(),
+ any(Sensor.class), anyInt(), any(Handler.class));
+
+ mAppOpsListenerCaptor.getValue().onOpActiveChanged(OPSTR_CAMERA, 10001, "pkg", false);
+ verify(mSensorManager, times(1)).unregisterListener(mLightSensorListenerCaptor.getValue());
+ }
+
+ @Ignore
+ @Test
+ public void testDayColor() {
+ testBrightnessToColor(20, mDayColor);
+ }
+
+ @Ignore
+ @Test
+ public void testNightColor() {
+ testBrightnessToColor(10, mNightColor);
+ }
+
+ private void testBrightnessToColor(int brightnessValue, int color) {
+ mLights.add(getNextLight(true));
+ Sensor sensor = mock(Sensor.class);
+ doReturn(sensor).when(mSensorManager).getDefaultSensor(Sensor.TYPE_LIGHT);
+
+ CameraPrivacyLightController cplc = createCameraPrivacyLightController();
+ cplc.setElapsedRealTime(0);
+
+ openCamera();
+
+ verify(mSensorManager).registerListener(mLightSensorListenerCaptor.capture(),
+ any(Sensor.class), anyInt(), any(Handler.class));
+ SensorEventListener sensorListener = mLightSensorListenerCaptor.getValue();
+ float[] sensorEventValues = new float[1];
+ SensorEvent sensorEvent = new SensorEvent(sensor, 0, 0, sensorEventValues);
+
+ sensorEventValues[0] = getLightSensorValue(brightnessValue);
+ sensorListener.onSensorChanged(sensorEvent);
+
+ verify(mLightsSession, atLeastOnce()).requestLights(mLightsRequestCaptor.capture());
+ for (LightState lightState : mLightsRequestCaptor.getValue().getLightStates()) {
+ assertEquals(color, lightState.getColor());
+ }
+ }
+
+ @Ignore
+ @Test
+ public void testDayToNightTransistion() {
+ mLights.add(getNextLight(true));
+ Sensor sensor = mock(Sensor.class);
+ doReturn(sensor).when(mSensorManager).getDefaultSensor(Sensor.TYPE_LIGHT);
+
+ CameraPrivacyLightController cplc = createCameraPrivacyLightController();
+ cplc.setElapsedRealTime(0);
+
+ openCamera();
+ // There will be an initial call at brightness 0
+ verify(mLightsSession, times(1)).requestLights(any(LightsRequest.class));
+
+ verify(mSensorManager).registerListener(mLightSensorListenerCaptor.capture(),
+ any(Sensor.class), anyInt(), any(Handler.class));
+ SensorEventListener sensorListener = mLightSensorListenerCaptor.getValue();
+
+ onSensorEvent(cplc, sensorListener, sensor, 0, 20);
+
+ // 5 sec avg = 20
+ onSensorEvent(cplc, sensorListener, sensor, 5000, 30);
+
+ verify(mLightsSession, times(2)).requestLights(mLightsRequestCaptor.capture());
+ for (LightState lightState : mLightsRequestCaptor.getValue().getLightStates()) {
+ assertEquals(mDayColor, lightState.getColor());
+ }
+
+ // 5 sec avg = 22
+
+ onSensorEvent(cplc, sensorListener, sensor, 6000, 10);
+
+ // 5 sec avg = 18
+
+ onSensorEvent(cplc, sensorListener, sensor, 8000, 5);
+
+ // Should have always been day
+ verify(mLightsSession, times(2)).requestLights(mLightsRequestCaptor.capture());
+ for (LightState lightState : mLightsRequestCaptor.getValue().getLightStates()) {
+ assertEquals(mDayColor, lightState.getColor());
+ }
+
+ // 5 sec avg = 12
+
+ onSensorEvent(cplc, sensorListener, sensor, 10000, 5);
+
+ // Should now be night
+ verify(mLightsSession, times(3)).requestLights(mLightsRequestCaptor.capture());
+ for (LightState lightState : mLightsRequestCaptor.getValue().getLightStates()) {
+ assertEquals(mNightColor, lightState.getColor());
+ }
+ }
+
+ private void onSensorEvent(CameraPrivacyLightController cplc,
+ SensorEventListener sensorListener, Sensor sensor, long timestamp, int value) {
+ cplc.setElapsedRealTime(timestamp);
+ sensorListener.onSensorChanged(new SensorEvent(sensor, 0, timestamp,
+ new float[] {getLightSensorValue(value)}));
+ }
+
+ // Use the test thread so that the test is deterministic
+ private CameraPrivacyLightController createCameraPrivacyLightController() {
+ if (Looper.myLooper() == null) {
+ Looper.prepare();
+ }
+ return new CameraPrivacyLightController(mContext, Looper.myLooper());
+ }
+
private Light getNextLight(boolean cameraType) {
Light light = ExtendedMockito.mock(Light.class);
if (cameraType) {
@@ -245,4 +426,13 @@ public class CameraPrivacyLightControllerTest {
doReturn(mNextLightId++).when(light).getId();
return light;
}
+
+ private float getLightSensorValue(int i) {
+ return (float) Math.exp(i / CameraPrivacyLightController.LIGHT_VALUE_MULTIPLIER);
+ }
+
+ private void openCamera() {
+ verify(mAppOpsManager).startWatchingActive(any(), any(), mAppOpsListenerCaptor.capture());
+ mAppOpsListenerCaptor.getValue().onOpActiveChanged(OPSTR_CAMERA, 10001, "pkg", true);
+ }
}
diff --git a/services/tests/servicestests/src/com/android/server/am/BroadcastRecordTest.java b/services/tests/servicestests/src/com/android/server/am/BroadcastRecordTest.java
index 18e0f29d4166..bce99a09c6d2 100644
--- a/services/tests/servicestests/src/com/android/server/am/BroadcastRecordTest.java
+++ b/services/tests/servicestests/src/com/android/server/am/BroadcastRecordTest.java
@@ -416,6 +416,7 @@ public class BroadcastRecordTest {
null /* resolvedType */,
null /* requiredPermissions */,
null /* excludedPermissions */,
+ null /* excludedPackages */,
0 /* appOp */,
null /* options */,
new ArrayList<>(receivers), // Make a copy to not affect the original list.
diff --git a/services/tests/servicestests/src/com/android/server/apphibernation/AppHibernationServiceTest.java b/services/tests/servicestests/src/com/android/server/apphibernation/AppHibernationServiceTest.java
index 5b3a1284069e..98f0603ca633 100644
--- a/services/tests/servicestests/src/com/android/server/apphibernation/AppHibernationServiceTest.java
+++ b/services/tests/servicestests/src/com/android/server/apphibernation/AppHibernationServiceTest.java
@@ -339,7 +339,7 @@ public final class AppHibernationServiceTest {
ArgumentCaptor<Intent> intentArgumentCaptor = ArgumentCaptor.forClass(Intent.class);
verify(mIActivityManager, times(2)).broadcastIntentWithFeature(any(), any(),
intentArgumentCaptor.capture(), any(), any(), anyInt(), any(), any(), any(), any(),
- anyInt(), any(), anyBoolean(), anyBoolean(), eq(USER_ID_1));
+ any(), anyInt(), any(), anyBoolean(), anyBoolean(), eq(USER_ID_1));
List<Intent> capturedIntents = intentArgumentCaptor.getAllValues();
assertEquals(capturedIntents.get(0).getAction(), Intent.ACTION_LOCKED_BOOT_COMPLETED);
assertEquals(capturedIntents.get(1).getAction(), Intent.ACTION_BOOT_COMPLETED);
diff --git a/services/tests/servicestests/src/com/android/server/companion/virtual/InputControllerTest.java b/services/tests/servicestests/src/com/android/server/companion/virtual/InputControllerTest.java
index 77cbb3a6398c..5d9d7656aa5b 100644
--- a/services/tests/servicestests/src/com/android/server/companion/virtual/InputControllerTest.java
+++ b/services/tests/servicestests/src/com/android/server/companion/virtual/InputControllerTest.java
@@ -34,6 +34,9 @@ import android.testing.AndroidTestingRunner;
import android.testing.TestableLooper;
import android.view.Display;
import android.view.DisplayInfo;
+import android.view.WindowManager;
+
+import androidx.test.InstrumentationRegistry;
import com.android.server.LocalServices;
@@ -79,7 +82,9 @@ public class InputControllerTest {
// Allow virtual devices to be created on the looper thread for testing.
final InputController.DeviceCreationThreadVerifier threadVerifier = () -> true;
mInputController = new InputController(new Object(), mNativeWrapperMock,
- new Handler(TestableLooper.get(this).getLooper()), threadVerifier);
+ new Handler(TestableLooper.get(this).getLooper()),
+ InstrumentationRegistry.getTargetContext().getSystemService(WindowManager.class),
+ threadVerifier);
}
@Test
diff --git a/services/tests/servicestests/src/com/android/server/companion/virtual/VirtualDeviceManagerServiceTest.java b/services/tests/servicestests/src/com/android/server/companion/virtual/VirtualDeviceManagerServiceTest.java
index cbb9fd7c30dd..f9671e56fe12 100644
--- a/services/tests/servicestests/src/com/android/server/companion/virtual/VirtualDeviceManagerServiceTest.java
+++ b/services/tests/servicestests/src/com/android/server/companion/virtual/VirtualDeviceManagerServiceTest.java
@@ -77,6 +77,7 @@ import android.testing.TestableLooper;
import android.util.ArraySet;
import android.view.DisplayInfo;
import android.view.KeyEvent;
+import android.view.WindowManager;
import androidx.test.InstrumentationRegistry;
@@ -208,7 +209,8 @@ public class VirtualDeviceManagerServiceTest {
// Allow virtual devices to be created on the looper thread for testing.
final InputController.DeviceCreationThreadVerifier threadVerifier = () -> true;
mInputController = new InputController(new Object(), mNativeWrapperMock,
- new Handler(TestableLooper.get(this).getLooper()), threadVerifier);
+ new Handler(TestableLooper.get(this).getLooper()),
+ mContext.getSystemService(WindowManager.class), threadVerifier);
mAssociationInfo = new AssociationInfo(1, 0, null,
MacAddress.BROADCAST_ADDRESS, "", null, true, false, 0, 0);
diff --git a/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java b/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java
index 0fc201eae3d4..ec6b67450a1a 100644
--- a/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java
+++ b/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java
@@ -6996,22 +6996,23 @@ public class DevicePolicyManagerTest extends DpmTestBase {
dpm.setUserControlDisabledPackages(admin1, testPackages);
verify(getServices().packageManagerInternal)
- .setDeviceOwnerProtectedPackages(admin1.getPackageName(), testPackages);
+ .setOwnerProtectedPackages(UserHandle.USER_ALL, testPackages);
assertThat(dpm.getUserControlDisabledPackages(admin1)).isEqualTo(testPackages);
}
@Test
- public void testSetUserControlDisabledPackages_failingAsPO() {
+ public void testSetUserControlDisabledPackages_asPO() {
final List<String> testPackages = new ArrayList<>();
testPackages.add("package_1");
testPackages.add("package_2");
mServiceContext.permissions.add(permission.MANAGE_DEVICE_ADMINS);
setAsProfileOwner(admin1);
- assertExpectException(SecurityException.class, /* messageRegex= */ null,
- () -> dpm.setUserControlDisabledPackages(admin1, testPackages));
- assertExpectException(SecurityException.class, /* messageRegex= */ null,
- () -> dpm.getUserControlDisabledPackages(admin1));
+ dpm.setUserControlDisabledPackages(admin1, testPackages);
+
+ verify(getServices().packageManagerInternal)
+ .setOwnerProtectedPackages(CALLER_USER_HANDLE, testPackages);
+ assertThat(dpm.getUserControlDisabledPackages(admin1)).isEqualTo(testPackages);
}
private void configureProfileOwnerOfOrgOwnedDevice(ComponentName who, int userId) {
@@ -7845,7 +7846,7 @@ public class DevicePolicyManagerTest extends DpmTestBase {
dpm.setUserControlDisabledPackages(admin1, packages);
verify(getServices().packageManagerInternal)
- .setDeviceOwnerProtectedPackages(eq(admin1.getPackageName()), eq(packages));
+ .setOwnerProtectedPackages(eq(UserHandle.USER_ALL), eq(packages));
}
@Test
diff --git a/services/tests/servicestests/src/com/android/server/hdmi/HdmiCecLocalDeviceTvTest.java b/services/tests/servicestests/src/com/android/server/hdmi/HdmiCecLocalDeviceTvTest.java
index f27b8c2f4b3a..8112ca8fbb14 100644
--- a/services/tests/servicestests/src/com/android/server/hdmi/HdmiCecLocalDeviceTvTest.java
+++ b/services/tests/servicestests/src/com/android/server/hdmi/HdmiCecLocalDeviceTvTest.java
@@ -560,8 +560,19 @@ public class HdmiCecLocalDeviceTvTest {
HdmiCecMessage reportArcInitiated = HdmiCecMessageBuilder.buildReportArcInitiated(
ADDR_TV,
ADDR_AUDIO_SYSTEM);
- assertThat(mNativeWrapper.getResultMessages()).contains(reportArcInitiated);
+ // <Report ARC Initiated> should only be sent after SAD querying is done
+ assertThat(mNativeWrapper.getResultMessages()).doesNotContain(reportArcInitiated);
+
+ // Finish querying SADs
assertThat(mNativeWrapper.getResultMessages()).contains(SAD_QUERY);
+ mNativeWrapper.clearResultMessages();
+ mTestLooper.moveTimeForward(HdmiConfig.TIMEOUT_MS);
+ mTestLooper.dispatchAll();
+ assertThat(mNativeWrapper.getResultMessages()).contains(SAD_QUERY);
+ mTestLooper.moveTimeForward(HdmiConfig.TIMEOUT_MS);
+ mTestLooper.dispatchAll();
+
+ assertThat(mNativeWrapper.getResultMessages()).contains(reportArcInitiated);
}
@Test
diff --git a/services/tests/servicestests/src/com/android/server/hdmi/RequestSadActionTest.java b/services/tests/servicestests/src/com/android/server/hdmi/RequestSadActionTest.java
index f7983ca21816..3228e82b566b 100644
--- a/services/tests/servicestests/src/com/android/server/hdmi/RequestSadActionTest.java
+++ b/services/tests/servicestests/src/com/android/server/hdmi/RequestSadActionTest.java
@@ -139,11 +139,12 @@ public class RequestSadActionTest {
}
@Test
- public void noResponse_queryAgain_emptyResult() {
+ public void noResponse_queryAgainOnce_emptyResult() {
RequestSadAction action = new RequestSadAction(mHdmiCecLocalDeviceTv, ADDR_AUDIO_SYSTEM,
mCallback);
action.start();
mTestLooper.dispatchAll();
+ assertThat(mSupportedSads).isNull();
HdmiCecMessage expected1 = HdmiCecMessageBuilder.buildRequestShortAudioDescriptor(
mTvLogicalAddress, Constants.ADDR_AUDIO_SYSTEM,
@@ -153,45 +154,90 @@ public class RequestSadActionTest {
mTestLooper.moveTimeForward(TIMEOUT_MS);
mTestLooper.dispatchAll();
assertThat(mNativeWrapper.getResultMessages()).contains(expected1);
- mNativeWrapper.clearResultMessages();
mTestLooper.moveTimeForward(TIMEOUT_MS);
mTestLooper.dispatchAll();
+ assertThat(mSupportedSads).isNotNull();
+ assertThat(mSupportedSads.size()).isEqualTo(0);
+
HdmiCecMessage expected2 = HdmiCecMessageBuilder.buildRequestShortAudioDescriptor(
mTvLogicalAddress, Constants.ADDR_AUDIO_SYSTEM,
CODECS_TO_QUERY_2.stream().mapToInt(i -> i).toArray());
- assertThat(mNativeWrapper.getResultMessages()).contains(expected2);
- mNativeWrapper.clearResultMessages();
+ HdmiCecMessage expected3 = HdmiCecMessageBuilder.buildRequestShortAudioDescriptor(
+ mTvLogicalAddress, Constants.ADDR_AUDIO_SYSTEM,
+ CODECS_TO_QUERY_3.stream().mapToInt(i -> i).toArray());
+ HdmiCecMessage expected4 = HdmiCecMessageBuilder.buildRequestShortAudioDescriptor(
+ mTvLogicalAddress, Constants.ADDR_AUDIO_SYSTEM,
+ CODECS_TO_QUERY_4.stream().mapToInt(i -> i).toArray());
+
+ mTestLooper.moveTimeForward(TIMEOUT_MS);
+ mTestLooper.dispatchAll();
+ mTestLooper.moveTimeForward(TIMEOUT_MS);
+ mTestLooper.dispatchAll();
mTestLooper.moveTimeForward(TIMEOUT_MS);
mTestLooper.dispatchAll();
- assertThat(mNativeWrapper.getResultMessages()).contains(expected2);
- mNativeWrapper.clearResultMessages();
mTestLooper.moveTimeForward(TIMEOUT_MS);
mTestLooper.dispatchAll();
-
- HdmiCecMessage expected3 = HdmiCecMessageBuilder.buildRequestShortAudioDescriptor(
- mTvLogicalAddress, Constants.ADDR_AUDIO_SYSTEM,
- CODECS_TO_QUERY_3.stream().mapToInt(i -> i).toArray());
- assertThat(mNativeWrapper.getResultMessages()).contains(expected3);
- mNativeWrapper.clearResultMessages();
mTestLooper.moveTimeForward(TIMEOUT_MS);
mTestLooper.dispatchAll();
- assertThat(mNativeWrapper.getResultMessages()).contains(expected3);
- mNativeWrapper.clearResultMessages();
mTestLooper.moveTimeForward(TIMEOUT_MS);
mTestLooper.dispatchAll();
+ assertThat(mNativeWrapper.getResultMessages()).doesNotContain(expected2);
+ assertThat(mNativeWrapper.getResultMessages()).doesNotContain(expected3);
+ assertThat(mNativeWrapper.getResultMessages()).doesNotContain(expected4);
+ assertThat(mSupportedSads.size()).isEqualTo(0);
+ }
+
+ @Test
+ public void unrecognizedOpcode_dontQueryAgain_emptyResult() {
+ RequestSadAction action = new RequestSadAction(mHdmiCecLocalDeviceTv, ADDR_AUDIO_SYSTEM,
+ mCallback);
+ action.start();
+ mTestLooper.dispatchAll();
+ assertThat(mSupportedSads).isNull();
+
+ HdmiCecMessage unrecognizedOpcode = HdmiCecMessageBuilder.buildFeatureAbortCommand(
+ Constants.ADDR_AUDIO_SYSTEM, mTvLogicalAddress,
+ Constants.MESSAGE_REQUEST_SHORT_AUDIO_DESCRIPTOR,
+ Constants.ABORT_UNRECOGNIZED_OPCODE);
+
+ HdmiCecMessage expected1 = HdmiCecMessageBuilder.buildRequestShortAudioDescriptor(
+ mTvLogicalAddress, Constants.ADDR_AUDIO_SYSTEM,
+ CODECS_TO_QUERY_1.stream().mapToInt(i -> i).toArray());
+ assertThat(mNativeWrapper.getResultMessages()).contains(expected1);
+ action.processCommand(unrecognizedOpcode);
+ mTestLooper.dispatchAll();
+
+ assertThat(mSupportedSads).isNotNull();
+ assertThat(mSupportedSads.size()).isEqualTo(0);
+
+ HdmiCecMessage expected2 = HdmiCecMessageBuilder.buildRequestShortAudioDescriptor(
+ mTvLogicalAddress, Constants.ADDR_AUDIO_SYSTEM,
+ CODECS_TO_QUERY_2.stream().mapToInt(i -> i).toArray());
+ HdmiCecMessage expected3 = HdmiCecMessageBuilder.buildRequestShortAudioDescriptor(
+ mTvLogicalAddress, Constants.ADDR_AUDIO_SYSTEM,
+ CODECS_TO_QUERY_3.stream().mapToInt(i -> i).toArray());
HdmiCecMessage expected4 = HdmiCecMessageBuilder.buildRequestShortAudioDescriptor(
mTvLogicalAddress, Constants.ADDR_AUDIO_SYSTEM,
CODECS_TO_QUERY_4.stream().mapToInt(i -> i).toArray());
- assertThat(mNativeWrapper.getResultMessages()).contains(expected4);
- mNativeWrapper.clearResultMessages();
+
+ mTestLooper.moveTimeForward(TIMEOUT_MS);
+ mTestLooper.dispatchAll();
+ mTestLooper.moveTimeForward(TIMEOUT_MS);
+ mTestLooper.dispatchAll();
+ mTestLooper.moveTimeForward(TIMEOUT_MS);
+ mTestLooper.dispatchAll();
+ mTestLooper.moveTimeForward(TIMEOUT_MS);
+ mTestLooper.dispatchAll();
mTestLooper.moveTimeForward(TIMEOUT_MS);
mTestLooper.dispatchAll();
- assertThat(mNativeWrapper.getResultMessages()).contains(expected4);
mTestLooper.moveTimeForward(TIMEOUT_MS);
mTestLooper.dispatchAll();
+ assertThat(mNativeWrapper.getResultMessages()).doesNotContain(expected2);
+ assertThat(mNativeWrapper.getResultMessages()).doesNotContain(expected3);
+ assertThat(mNativeWrapper.getResultMessages()).doesNotContain(expected4);
assertThat(mSupportedSads.size()).isEqualTo(0);
}
@@ -455,11 +501,12 @@ public class RequestSadActionTest {
}
@Test
- public void invalidMessageLength_queryAgain() {
+ public void invalidMessageLength_queryAgainOnce() {
RequestSadAction action = new RequestSadAction(mHdmiCecLocalDeviceTv, ADDR_AUDIO_SYSTEM,
mCallback);
action.start();
mTestLooper.dispatchAll();
+ assertThat(mSupportedSads).isNull();
HdmiCecMessage expected1 = HdmiCecMessageBuilder.buildRequestShortAudioDescriptor(
mTvLogicalAddress, Constants.ADDR_AUDIO_SYSTEM,
@@ -482,63 +529,35 @@ public class RequestSadActionTest {
mTestLooper.moveTimeForward(TIMEOUT_MS);
mTestLooper.dispatchAll();
+ assertThat(mSupportedSads).isNotNull();
+ assertThat(mSupportedSads.size()).isEqualTo(0);
+
HdmiCecMessage expected2 = HdmiCecMessageBuilder.buildRequestShortAudioDescriptor(
mTvLogicalAddress, Constants.ADDR_AUDIO_SYSTEM,
CODECS_TO_QUERY_2.stream().mapToInt(i -> i).toArray());
- byte[] sadsToRespond_2 = new byte[]{
- 0x05, 0x18, 0x4A,
- 0x06, 0x64, 0x5A,
- 0x07,
- 0x08, 0x20, 0x0A};
- HdmiCecMessage response2 = HdmiCecMessageBuilder.buildReportShortAudioDescriptor(
- Constants.ADDR_AUDIO_SYSTEM, mTvLogicalAddress, sadsToRespond_2);
- assertThat(mNativeWrapper.getResultMessages()).contains(expected2);
- mNativeWrapper.clearResultMessages();
- action.processCommand(response2);
- mTestLooper.dispatchAll();
- mTestLooper.moveTimeForward(TIMEOUT_MS);
- mTestLooper.dispatchAll();
- assertThat(mNativeWrapper.getResultMessages()).contains(expected2);
- mNativeWrapper.clearResultMessages();
- mTestLooper.moveTimeForward(TIMEOUT_MS);
- mTestLooper.dispatchAll();
-
HdmiCecMessage expected3 = HdmiCecMessageBuilder.buildRequestShortAudioDescriptor(
mTvLogicalAddress, Constants.ADDR_AUDIO_SYSTEM,
CODECS_TO_QUERY_3.stream().mapToInt(i -> i).toArray());
- byte[] sadsToRespond_3 = new byte[0];
- HdmiCecMessage response3 = HdmiCecMessageBuilder.buildReportShortAudioDescriptor(
- Constants.ADDR_AUDIO_SYSTEM, mTvLogicalAddress, sadsToRespond_3);
- assertThat(mNativeWrapper.getResultMessages()).contains(expected3);
- mNativeWrapper.clearResultMessages();
- action.processCommand(response3);
+ HdmiCecMessage expected4 = HdmiCecMessageBuilder.buildRequestShortAudioDescriptor(
+ mTvLogicalAddress, Constants.ADDR_AUDIO_SYSTEM,
+ CODECS_TO_QUERY_4.stream().mapToInt(i -> i).toArray());
+
+ mTestLooper.moveTimeForward(TIMEOUT_MS);
mTestLooper.dispatchAll();
mTestLooper.moveTimeForward(TIMEOUT_MS);
mTestLooper.dispatchAll();
- assertThat(mNativeWrapper.getResultMessages()).contains(expected3);
- mNativeWrapper.clearResultMessages();
mTestLooper.moveTimeForward(TIMEOUT_MS);
mTestLooper.dispatchAll();
-
- HdmiCecMessage expected4 = HdmiCecMessageBuilder.buildRequestShortAudioDescriptor(
- mTvLogicalAddress, Constants.ADDR_AUDIO_SYSTEM,
- CODECS_TO_QUERY_4.stream().mapToInt(i -> i).toArray());
- byte[] sadsToRespond_4 = new byte[]{
- 0x0D, 0x18, 0x4A,
- 0x0E, 0x64, 0x5A,
- 0x0F, 0x4B};
- HdmiCecMessage response4 = HdmiCecMessageBuilder.buildReportShortAudioDescriptor(
- Constants.ADDR_AUDIO_SYSTEM, mTvLogicalAddress, sadsToRespond_4);
- assertThat(mNativeWrapper.getResultMessages()).contains(expected4);
- mNativeWrapper.clearResultMessages();
- action.processCommand(response4);
+ mTestLooper.moveTimeForward(TIMEOUT_MS);
mTestLooper.dispatchAll();
mTestLooper.moveTimeForward(TIMEOUT_MS);
mTestLooper.dispatchAll();
- assertThat(mNativeWrapper.getResultMessages()).contains(expected4);
mTestLooper.moveTimeForward(TIMEOUT_MS);
mTestLooper.dispatchAll();
+ assertThat(mNativeWrapper.getResultMessages()).doesNotContain(expected2);
+ assertThat(mNativeWrapper.getResultMessages()).doesNotContain(expected3);
+ assertThat(mNativeWrapper.getResultMessages()).doesNotContain(expected4);
assertThat(mSupportedSads.size()).isEqualTo(0);
}
diff --git a/services/tests/servicestests/src/com/android/server/pm/ApexManagerTest.java b/services/tests/servicestests/src/com/android/server/pm/ApexManagerTest.java
index 8f5b0e19f07e..ab292ab5381e 100644
--- a/services/tests/servicestests/src/com/android/server/pm/ApexManagerTest.java
+++ b/services/tests/servicestests/src/com/android/server/pm/ApexManagerTest.java
@@ -546,6 +546,18 @@ public class ApexManagerTest {
assertThat(backingApexFile).isNull();
}
+ @Test
+ public void testActiveApexChanged() throws RemoteException {
+ ApexInfo apex1 = createApexInfo(
+ "com.apex1", 37, true, true, new File("/data/apex/active/com.apex@37.apex"));
+ apex1.activeApexChanged = true;
+ apex1.preinstalledModulePath = apex1.modulePath;
+ when(mApexService.getActivePackages()).thenReturn(new ApexInfo[]{apex1});
+ final ApexManager.ActiveApexInfo activeApex = mApexManager.getActiveApexInfos().get(0);
+ assertThat(activeApex.apexModuleName).isEqualTo("com.apex1");
+ assertThat(activeApex.activeApexChanged).isTrue();
+ }
+
private ApexInfo createApexInfoForTestPkg(boolean isActive, boolean isFactory, int version) {
File apexFile = extractResource(TEST_APEX_PKG, TEST_APEX_FILE_NAME);
ApexInfo apexInfo = new ApexInfo();
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java b/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java
index 80dee10b3b7f..a7dc8518daea 100755
--- a/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java
@@ -9573,6 +9573,8 @@ public class NotificationManagerServiceTest extends UiServiceTestCase {
@Test
public void testMaybeShowReviewPermissionsNotification_unknown() {
+ reset(mMockNm);
+
// Set up various possible states of the settings int and confirm whether or not the
// notification is shown as expected
@@ -9586,6 +9588,8 @@ public class NotificationManagerServiceTest extends UiServiceTestCase {
@Test
public void testMaybeShowReviewPermissionsNotification_shouldShow() {
+ reset(mMockNm);
+
// If state is SHOULD_SHOW, it ... should show
Settings.Global.putInt(mContext.getContentResolver(),
Settings.Global.REVIEW_PERMISSIONS_NOTIFICATION_STATE,
@@ -9598,6 +9602,8 @@ public class NotificationManagerServiceTest extends UiServiceTestCase {
@Test
public void testMaybeShowReviewPermissionsNotification_alreadyShown() {
+ reset(mMockNm);
+
// If state is either USER_INTERACTED or DISMISSED, we should not show this on boot
Settings.Global.putInt(mContext.getContentResolver(),
Settings.Global.REVIEW_PERMISSIONS_NOTIFICATION_STATE,
@@ -9614,6 +9620,8 @@ public class NotificationManagerServiceTest extends UiServiceTestCase {
@Test
public void testMaybeShowReviewPermissionsNotification_reshown() {
+ reset(mMockNm);
+
// If we have re-shown the notification and the user did not subsequently interacted with
// it, then make sure we show when trying on boot
Settings.Global.putInt(mContext.getContentResolver(),
@@ -9627,6 +9635,8 @@ public class NotificationManagerServiceTest extends UiServiceTestCase {
@Test
public void testRescheduledReviewPermissionsNotification() {
+ reset(mMockNm);
+
// when rescheduled, the notification goes through the NotificationManagerInternal service
// this call doesn't need to know anything about previously scheduled state -- if called,
// it should send the notification & write the appropriate int to Settings
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/PermissionHelperTest.java b/services/tests/uiservicestests/src/com/android/server/notification/PermissionHelperTest.java
index 3a352cbe1900..4c7e8433b15b 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/PermissionHelperTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/PermissionHelperTest.java
@@ -17,7 +17,6 @@ package com.android.server.notification;
import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
-import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
import static android.content.pm.PackageManager.GET_PERMISSIONS;
@@ -26,8 +25,6 @@ import static android.content.pm.PackageManager.PERMISSION_GRANTED;
import static com.google.common.truth.Truth.assertThat;
-import static junit.framework.Assert.fail;
-
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyLong;
@@ -54,7 +51,6 @@ import com.android.server.pm.permission.PermissionManagerServiceInternal;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Lists;
import org.junit.Before;
import org.junit.Test;
@@ -62,14 +58,7 @@ import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.lang.reflect.Modifier;
-import java.lang.reflect.Parameter;
-import java.lang.reflect.Type;
-import java.util.List;
import java.util.Map;
-import java.util.Objects;
import java.util.Set;
@SmallTest
@@ -88,7 +77,7 @@ public class PermissionHelperTest extends UiServiceTestCase {
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
- mPermissionHelper = new PermissionHelper(mPmi, mPackageManager, mPermManager, false);
+ mPermissionHelper = new PermissionHelper(mPmi, mPackageManager, mPermManager);
PackageInfo testPkgInfo = new PackageInfo();
testPkgInfo.requestedPermissions = new String[]{ Manifest.permission.POST_NOTIFICATIONS };
when(mPackageManager.getPackageInfo(anyString(), anyLong(), anyInt()))
@@ -97,12 +86,12 @@ public class PermissionHelperTest extends UiServiceTestCase {
@Test
public void testHasPermission() throws Exception {
- when(mPmi.checkPostNotificationsPermissionGrantedOrLegacyAccess(anyInt()))
+ when(mPmi.checkUidPermission(anyInt(), anyString()))
.thenReturn(PERMISSION_GRANTED);
assertThat(mPermissionHelper.hasPermission(1)).isTrue();
- when(mPmi.checkPostNotificationsPermissionGrantedOrLegacyAccess(anyInt()))
+ when(mPmi.checkUidPermission(anyInt(), anyString()))
.thenReturn(PERMISSION_DENIED);
assertThat(mPermissionHelper.hasPermission(1)).isFalse();
@@ -194,79 +183,12 @@ public class PermissionHelperTest extends UiServiceTestCase {
verify(mPermManager).grantRuntimePermission(
"pkg", Manifest.permission.POST_NOTIFICATIONS, 10);
verify(mPermManager).updatePermissionFlags("pkg", Manifest.permission.POST_NOTIFICATIONS,
- FLAG_PERMISSION_USER_SET | FLAG_PERMISSION_REVIEW_REQUIRED,
- FLAG_PERMISSION_USER_SET, true, 10);
- }
-
- @Test
- public void testSetNotificationPermission_grantReviewRequired() throws Exception {
- when(mPmi.checkPermission(anyString(), anyString(), anyInt()))
- .thenReturn(PERMISSION_DENIED);
-
- mPermissionHelper.setNotificationPermission("pkg", 10, true, false, true);
-
- verify(mPermManager, never()).revokeRuntimePermission(
- "pkg", Manifest.permission.POST_NOTIFICATIONS, 10, "PermissionHelper");
- verify(mPermManager).updatePermissionFlags("pkg", Manifest.permission.POST_NOTIFICATIONS,
- FLAG_PERMISSION_REVIEW_REQUIRED, FLAG_PERMISSION_REVIEW_REQUIRED, true, 10);
- }
-
- @Test
- public void testSetNotificationPermission_pkgPerm_grantReviewRequired() throws Exception {
- when(mPmi.checkPermission(anyString(), anyString(), anyInt()))
- .thenReturn(PERMISSION_DENIED);
-
- PermissionHelper.PackagePermission pkgPerm = new PermissionHelper.PackagePermission(
- "pkg", 10, true, false);
- mPermissionHelper.setNotificationPermission(pkgPerm);
-
- verify(mPermManager, never()).revokeRuntimePermission(
- "pkg", Manifest.permission.POST_NOTIFICATIONS, 10, "PermissionHelper");
- verify(mPermManager).updatePermissionFlags("pkg", Manifest.permission.POST_NOTIFICATIONS,
- FLAG_PERMISSION_REVIEW_REQUIRED, FLAG_PERMISSION_REVIEW_REQUIRED, true, 10);
- }
-
- @Test
- public void testSetNotificationPermission_pkgPerm_notUserSet_grantedByDefaultPermNotSet()
- throws Exception {
- when(mPmi.checkPermission(anyString(), anyString(), anyInt()))
- .thenReturn(PERMISSION_DENIED);
- when(mPermManager.getPermissionFlags(anyString(),
- eq(Manifest.permission.POST_NOTIFICATIONS),
- anyInt())).thenReturn(FLAG_PERMISSION_GRANTED_BY_DEFAULT);
- PermissionHelper.PackagePermission pkgPerm = new PermissionHelper.PackagePermission(
- "pkg", 10, true, false);
-
- mPermissionHelper.setNotificationPermission(pkgPerm);
- verify(mPermManager, never()).revokeRuntimePermission(
- anyString(), anyString(), anyInt(), anyString());
- verify(mPermManager, never()).updatePermissionFlags(
- anyString(), anyString(), anyInt(), anyInt(), anyBoolean(), anyInt());
- }
-
- @Test
- public void testSetNotificationPermission_pkgPerm_userSet_grantedByDefaultPermSet()
- throws Exception {
- when(mPmi.checkPermission(anyString(), anyString(), anyInt()))
- .thenReturn(PERMISSION_DENIED);
- when(mPermManager.getPermissionFlags(anyString(),
- eq(Manifest.permission.POST_NOTIFICATIONS),
- anyInt())).thenReturn(FLAG_PERMISSION_GRANTED_BY_DEFAULT);
- PermissionHelper.PackagePermission pkgPerm = new PermissionHelper.PackagePermission(
- "pkg", 10, true, true);
-
- mPermissionHelper.setNotificationPermission(pkgPerm);
- verify(mPermManager).grantRuntimePermission(
- "pkg", Manifest.permission.POST_NOTIFICATIONS, 10);
- verify(mPermManager).updatePermissionFlags("pkg", Manifest.permission.POST_NOTIFICATIONS,
- FLAG_PERMISSION_USER_SET | FLAG_PERMISSION_REVIEW_REQUIRED,
- FLAG_PERMISSION_USER_SET, true, 10);
+ FLAG_PERMISSION_USER_SET, FLAG_PERMISSION_USER_SET, true, 10);
}
@Test
public void testSetNotificationPermission_pkgPerm_grantedByDefaultPermSet_allUserSet()
throws Exception {
- mPermissionHelper = new PermissionHelper(mPmi, mPackageManager, mPermManager, true);
when(mPmi.checkPermission(anyString(), anyString(), anyInt()))
.thenReturn(PERMISSION_DENIED);
when(mPermManager.getPermissionFlags(anyString(),
@@ -279,8 +201,7 @@ public class PermissionHelperTest extends UiServiceTestCase {
verify(mPermManager).grantRuntimePermission(
"pkg", Manifest.permission.POST_NOTIFICATIONS, 10);
verify(mPermManager).updatePermissionFlags("pkg", Manifest.permission.POST_NOTIFICATIONS,
- FLAG_PERMISSION_USER_SET | FLAG_PERMISSION_REVIEW_REQUIRED,
- FLAG_PERMISSION_USER_SET, true, 10);
+ FLAG_PERMISSION_USER_SET, FLAG_PERMISSION_USER_SET, true, 10);
}
@Test
@@ -293,8 +214,7 @@ public class PermissionHelperTest extends UiServiceTestCase {
verify(mPermManager).revokeRuntimePermission(
eq("pkg"), eq(Manifest.permission.POST_NOTIFICATIONS), eq(10), anyString());
verify(mPermManager).updatePermissionFlags("pkg", Manifest.permission.POST_NOTIFICATIONS,
- FLAG_PERMISSION_USER_SET | FLAG_PERMISSION_REVIEW_REQUIRED,
- FLAG_PERMISSION_USER_SET, true, 10);
+ FLAG_PERMISSION_USER_SET, FLAG_PERMISSION_USER_SET, true, 10);
}
@Test
@@ -306,8 +226,8 @@ public class PermissionHelperTest extends UiServiceTestCase {
verify(mPermManager).grantRuntimePermission(
"pkg", Manifest.permission.POST_NOTIFICATIONS, 10);
- verify(mPermManager, never()).updatePermissionFlags(
- anyString(), anyString(), anyInt(), anyInt(), anyBoolean(), anyInt());
+ verify(mPermManager).updatePermissionFlags("pkg", Manifest.permission.POST_NOTIFICATIONS,
+ 0, FLAG_PERMISSION_USER_SET, true, 10);
}
@Test
@@ -319,8 +239,8 @@ public class PermissionHelperTest extends UiServiceTestCase {
verify(mPermManager).revokeRuntimePermission(
eq("pkg"), eq(Manifest.permission.POST_NOTIFICATIONS), eq(10), anyString());
- verify(mPermManager, never()).updatePermissionFlags(
- anyString(), anyString(), anyInt(), anyInt(), anyBoolean(), anyInt());
+ verify(mPermManager).updatePermissionFlags("pkg", Manifest.permission.POST_NOTIFICATIONS,
+ 0, FLAG_PERMISSION_USER_SET, true, 10);
}
@Test
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/PreferencesHelperTest.java b/services/tests/uiservicestests/src/com/android/server/notification/PreferencesHelperTest.java
index a5cec7e01e9a..8d50ceaf74e9 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/PreferencesHelperTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/PreferencesHelperTest.java
@@ -85,6 +85,7 @@ import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
+import android.content.pm.UserInfo;
import android.content.res.Resources;
import android.graphics.Color;
import android.media.AudioAttributes;
@@ -121,6 +122,8 @@ import com.android.os.AtomsProto.PackageNotificationPreferences;
import com.android.server.UiServiceTestCase;
import com.android.server.notification.PermissionHelper.PackagePermission;
+import com.google.common.collect.ImmutableList;
+
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Before;
@@ -3523,8 +3526,37 @@ public class PreferencesHelperTest extends UiServiceTestCase {
@Test
public void testUpdateNotificationChannel_fixedPermission() {
+ List<UserInfo> users = ImmutableList.of(new UserInfo(UserHandle.USER_SYSTEM, "user0", 0));
when(mPermissionHelper.isPermissionFixed(PKG_O, 0)).thenReturn(true);
+ PackageInfo pm = new PackageInfo();
+ pm.packageName = PKG_O;
+ pm.applicationInfo = new ApplicationInfo();
+ pm.applicationInfo.uid = UID_O;
+ List<PackageInfo> packages = ImmutableList.of(pm);
+ when(mPm.getInstalledPackagesAsUser(any(), anyInt())).thenReturn(packages);
+ mHelper.updateFixedImportance(users);
+
+ assertTrue(mHelper.isImportanceLocked(PKG_O, UID_O));
+
+ NotificationChannel a = new NotificationChannel("a", "a", IMPORTANCE_HIGH);
+ mHelper.createNotificationChannel(PKG_O, UID_O, a, true, false);
+
+ NotificationChannel update = new NotificationChannel("a", "a", IMPORTANCE_NONE);
+ update.setAllowBubbles(false);
+
+ mHelper.updateNotificationChannel(PKG_O, UID_O, update, true);
+ assertEquals(IMPORTANCE_HIGH,
+ mHelper.getNotificationChannel(PKG_O, UID_O, a.getId(), false).getImportance());
+ assertEquals(false,
+ mHelper.getNotificationChannel(PKG_O, UID_O, a.getId(), false).canBubble());
+ }
+
+ @Test
+ public void testUpdateNotificationChannel_defaultApp() {
+ ArraySet<Pair<String, Integer>> toAdd = new ArraySet<>();
+ toAdd.add(new Pair(PKG_O, UID_O));
+ mHelper.updateDefaultApps(0, null, toAdd);
NotificationChannel a = new NotificationChannel("a", "a", IMPORTANCE_HIGH);
mHelper.createNotificationChannel(PKG_O, UID_O, a, true, false);
@@ -3595,6 +3627,58 @@ public class PreferencesHelperTest extends UiServiceTestCase {
}
@Test
+ public void testUpdateFixedImportance_multiUser() {
+ NotificationChannel a = new NotificationChannel("a", "a", IMPORTANCE_HIGH);
+ NotificationChannel b = new NotificationChannel("b", "b", IMPORTANCE_LOW);
+ NotificationChannel c = new NotificationChannel("c", "c", IMPORTANCE_DEFAULT);
+ // different uids, same package
+ mHelper.createNotificationChannel(PKG_O, UID_O, a, true, false);
+ mHelper.createNotificationChannel(PKG_O, UID_O, b, false, false);
+ mHelper.createNotificationChannel(PKG_O, UserHandle.PER_USER_RANGE + 1, c, true, true);
+
+ UserInfo user = new UserInfo();
+ user.id = 0;
+ List<UserInfo> users = ImmutableList.of(user);
+ when(mPermissionHelper.isPermissionFixed(PKG_O, 0)).thenReturn(true);
+ PackageInfo pm = new PackageInfo();
+ pm.packageName = PKG_O;
+ pm.applicationInfo = new ApplicationInfo();
+ pm.applicationInfo.uid = UID_O;
+ List<PackageInfo> packages = ImmutableList.of(pm);
+ when(mPm.getInstalledPackagesAsUser(any(), eq(0))).thenReturn(packages);
+ mHelper.updateFixedImportance(users);
+
+ assertTrue(mHelper.getNotificationChannel(PKG_O, UID_O, a.getId(), false)
+ .isImportanceLockedByCriticalDeviceFunction());
+ assertTrue(mHelper.getNotificationChannel(PKG_O, UID_O, b.getId(), false)
+ .isImportanceLockedByCriticalDeviceFunction());
+ assertFalse(mHelper.getNotificationChannel(
+ PKG_O, UserHandle.PER_USER_RANGE + 1, c.getId(), false)
+ .isImportanceLockedByCriticalDeviceFunction());
+ }
+
+ @Test
+ public void testUpdateFixedImportance_channelDoesNotExistYet() {
+ UserInfo user = new UserInfo();
+ user.id = 0;
+ List<UserInfo> users = ImmutableList.of(user);
+ when(mPermissionHelper.isPermissionFixed(PKG_O, 0)).thenReturn(true);
+ PackageInfo pm = new PackageInfo();
+ pm.packageName = PKG_O;
+ pm.applicationInfo = new ApplicationInfo();
+ pm.applicationInfo.uid = UID_O;
+ List<PackageInfo> packages = ImmutableList.of(pm);
+ when(mPm.getInstalledPackagesAsUser(any(), eq(0))).thenReturn(packages);
+ mHelper.updateFixedImportance(users);
+
+ NotificationChannel a = new NotificationChannel("a", "a", IMPORTANCE_HIGH);
+ mHelper.createNotificationChannel(PKG_O, UID_O, a, true, false);
+
+ assertTrue(mHelper.getNotificationChannel(PKG_O, UID_O, a.getId(), false)
+ .isImportanceLockedByCriticalDeviceFunction());
+ }
+
+ @Test
public void testUpdateDefaultApps_add_multiUser() {
NotificationChannel a = new NotificationChannel("a", "a", IMPORTANCE_HIGH);
NotificationChannel b = new NotificationChannel("b", "b", IMPORTANCE_LOW);
@@ -3759,6 +3843,62 @@ public class PreferencesHelperTest extends UiServiceTestCase {
}
@Test
+ public void testUpdateFixedImportance_thenDefaultAppsRemoves() {
+ UserInfo user = new UserInfo();
+ user.id = 0;
+ List<UserInfo> users = ImmutableList.of(user);
+ when(mPermissionHelper.isPermissionFixed(PKG_O, 0)).thenReturn(true);
+ PackageInfo pm = new PackageInfo();
+ pm.packageName = PKG_O;
+ pm.applicationInfo = new ApplicationInfo();
+ pm.applicationInfo.uid = UID_O;
+ List<PackageInfo> packages = ImmutableList.of(pm);
+ when(mPm.getInstalledPackagesAsUser(any(), eq(0))).thenReturn(packages);
+ mHelper.updateFixedImportance(users);
+
+ ArraySet<String> toRemove = new ArraySet<>();
+ toRemove.add(PKG_O);
+ mHelper.updateDefaultApps(0, toRemove, null);
+
+ assertTrue(mHelper.isImportanceLocked(PKG_O, UID_O));
+
+ NotificationChannel a = new NotificationChannel("a", "a", IMPORTANCE_HIGH);
+ mHelper.createNotificationChannel(PKG_O, UID_O, a, true, false);
+
+ // Still locked by permission if not role
+ assertTrue(mHelper.getNotificationChannel(PKG_O, UID_O, a.getId(), false)
+ .isImportanceLockedByCriticalDeviceFunction());
+ }
+
+ @Test
+ public void testUpdateDefaultApps_thenNotFixedPermission() {
+ ArraySet<Pair<String, Integer>> toAdd = new ArraySet<>();
+ toAdd.add(new Pair(PKG_O, UID_O));
+ mHelper.updateDefaultApps(0, null, toAdd);
+
+ UserInfo user = new UserInfo();
+ user.id = 0;
+ List<UserInfo> users = ImmutableList.of(user);
+ when(mPermissionHelper.isPermissionFixed(PKG_O, 0)).thenReturn(false);
+ PackageInfo pm = new PackageInfo();
+ pm.packageName = PKG_O;
+ pm.applicationInfo = new ApplicationInfo();
+ pm.applicationInfo.uid = UID_O;
+ List<PackageInfo> packages = ImmutableList.of(pm);
+ when(mPm.getInstalledPackagesAsUser(any(), eq(0))).thenReturn(packages);
+ mHelper.updateFixedImportance(users);
+
+ assertTrue(mHelper.isImportanceLocked(PKG_O, UID_O));
+
+ NotificationChannel a = new NotificationChannel("a", "a", IMPORTANCE_HIGH);
+ mHelper.createNotificationChannel(PKG_O, UID_O, a, true, false);
+
+ // Still locked by role if not permission
+ assertTrue(mHelper.getNotificationChannel(PKG_O, UID_O, a.getId(), false)
+ .isImportanceLockedByCriticalDeviceFunction());
+ }
+
+ @Test
public void testChannelXml_backupDefaultApp() throws Exception {
NotificationChannel channel1 =
new NotificationChannel("id1", "name1", NotificationManager.IMPORTANCE_HIGH);
diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java
index 2c0986884ca6..3f260fe66a8e 100644
--- a/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java
@@ -611,10 +611,9 @@ public class ActivityRecordTests extends WindowTestsBase {
activity.setRequestedOrientation(activityCurOrientation == ORIENTATION_LANDSCAPE
? SCREEN_ORIENTATION_PORTRAIT : SCREEN_ORIENTATION_LANDSCAPE);
- // Asserts fixed orientation request is ignored, and the orientation is not changed
- // (fill Task).
- assertEquals(activityCurOrientation, activity.getConfiguration().orientation);
- assertFalse(activity.isLetterboxedForFixedOrientationAndAspectRatio());
+ // Asserts fixed orientation request is not ignored, and the orientation is changed.
+ assertNotEquals(activityCurOrientation, activity.getConfiguration().orientation);
+ assertTrue(activity.isLetterboxedForFixedOrientationAndAspectRatio());
}
@Test
@@ -1787,13 +1786,16 @@ public class ActivityRecordTests extends WindowTestsBase {
public void testActivityOnCancelFixedRotationTransform() {
final ActivityRecord activity = createActivityWithTask();
final DisplayRotation displayRotation = activity.mDisplayContent.getDisplayRotation();
+ final RemoteDisplayChangeController remoteDisplayChangeController = activity
+ .mDisplayContent.mRemoteDisplayChangeController;
spyOn(displayRotation);
+ spyOn(remoteDisplayChangeController);
final DisplayContent display = activity.mDisplayContent;
final int originalRotation = display.getRotation();
// Make {@link DisplayContent#sendNewConfiguration} not apply rotation immediately.
- doReturn(true).when(displayRotation).isWaitingForRemoteRotation();
+ doReturn(true).when(remoteDisplayChangeController).isWaitingForRemoteDisplayChange();
doReturn((originalRotation + 1) % 4).when(displayRotation).rotationForOrientation(
anyInt() /* orientation */, anyInt() /* lastRotation */);
// Set to visible so the activity can freeze the screen.
@@ -1831,7 +1833,7 @@ public class ActivityRecordTests extends WindowTestsBase {
// Simulate the remote rotation has completed and the configuration doesn't change, then
// the rotated activity should also be restored by clearing the transform.
displayRotation.updateRotationUnchecked(true /* forceUpdate */);
- doReturn(false).when(displayRotation).isWaitingForRemoteRotation();
+ doReturn(false).when(remoteDisplayChangeController).isWaitingForRemoteDisplayChange();
clearInvocations(activity);
display.setFixedRotationLaunchingAppUnchecked(activity);
display.sendNewConfiguration();
@@ -2821,6 +2823,11 @@ public class ActivityRecordTests extends WindowTestsBase {
assertTrue(activity2.isResizeable());
activity1.reparent(taskFragment1, POSITION_TOP);
+ // Adds an Activity which doesn't have shared starting data, and verify if it blocks
+ // starting window removal.
+ final ActivityRecord activity3 = new ActivityBuilder(mAtm).build();
+ taskFragment2.addChild(activity3, POSITION_TOP);
+
verify(activity1.getSyncTransaction()).reparent(eq(startingWindow.mSurfaceControl),
eq(task.mSurfaceControl));
assertEquals(activity1.mStartingData, startingWindow.mStartingData);
diff --git a/services/tests/wmtests/src/com/android/server/wm/AppTransitionControllerTest.java b/services/tests/wmtests/src/com/android/server/wm/AppTransitionControllerTest.java
index 0a13a36e11d4..00e1ed226d7e 100644
--- a/services/tests/wmtests/src/com/android/server/wm/AppTransitionControllerTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/AppTransitionControllerTest.java
@@ -1157,6 +1157,41 @@ public class AppTransitionControllerTest extends WindowTestsBase {
verify(activity).setDropInputMode(DropInputMode.NONE);
}
+ /**
+ * We don't need to drop input for fully trusted embedding (system app, and embedding in the
+ * same app). This will allow users to do fast tapping.
+ */
+ @Test
+ public void testOverrideTaskFragmentAdapter_noInputProtectedForFullyTrustedAnimation() {
+ final Task task = createTask(mDisplayContent);
+ final TaskFragmentOrganizer organizer = new TaskFragmentOrganizer(Runnable::run);
+ final TestRemoteAnimationRunner remoteAnimationRunner = new TestRemoteAnimationRunner();
+ setupTaskFragmentRemoteAnimation(organizer, task.mTaskId, remoteAnimationRunner);
+
+ // Create a TaskFragment with only trusted embedded activity
+ final TaskFragment taskFragment = new TaskFragmentBuilder(mAtm)
+ .setParentTask(task)
+ .createActivityCount(1)
+ .setOrganizer(organizer)
+ .build();
+ final ActivityRecord activity = taskFragment.getChildAt(0).asActivityRecord();
+ prepareActivityForAppTransition(activity);
+ final int uid = mAtm.mTaskFragmentOrganizerController.getTaskFragmentOrganizerUid(
+ getITaskFragmentOrganizer(organizer));
+ doReturn(true).when(task).isFullyTrustedEmbedding(uid);
+ spyOn(mDisplayContent.mAppTransition);
+
+ // Prepare and start transition.
+ prepareAndTriggerAppTransition(activity, null /* closingActivity */, taskFragment);
+ mWm.mAnimator.executeAfterPrepareSurfacesRunnables();
+
+ // The animation will be animated remotely by client, but input should not be dropped for
+ // fully trusted.
+ assertTrue(remoteAnimationRunner.isAnimationStarted());
+ verify(activity, never()).setDropInputForAnimation(true);
+ verify(activity, never()).setDropInputMode(DropInputMode.ALL);
+ }
+
@Test
public void testTransitionGoodToGoForTaskFragments() {
final TaskFragmentOrganizer organizer = new TaskFragmentOrganizer(Runnable::run);
@@ -1226,8 +1261,7 @@ public class AppTransitionControllerTest extends WindowTestsBase {
TestRemoteAnimationRunner remoteAnimationRunner) {
final RemoteAnimationAdapter adapter = new RemoteAnimationAdapter(
remoteAnimationRunner, 10, 1);
- final ITaskFragmentOrganizer iOrganizer =
- ITaskFragmentOrganizer.Stub.asInterface(organizer.getOrganizerToken().asBinder());
+ final ITaskFragmentOrganizer iOrganizer = getITaskFragmentOrganizer(organizer);
final RemoteAnimationDefinition definition = new RemoteAnimationDefinition();
definition.addRemoteAnimation(TRANSIT_OLD_TASK_FRAGMENT_CHANGE, adapter);
definition.addRemoteAnimation(TRANSIT_OLD_TASK_FRAGMENT_OPEN, adapter);
@@ -1237,6 +1271,11 @@ public class AppTransitionControllerTest extends WindowTestsBase {
definition);
}
+ private static ITaskFragmentOrganizer getITaskFragmentOrganizer(
+ TaskFragmentOrganizer organizer) {
+ return ITaskFragmentOrganizer.Stub.asInterface(organizer.getOrganizerToken().asBinder());
+ }
+
private void prepareAndTriggerAppTransition(@Nullable ActivityRecord openingActivity,
@Nullable ActivityRecord closingActivity, @Nullable TaskFragment changingTaskFragment) {
if (openingActivity != null) {
diff --git a/services/tests/wmtests/src/com/android/server/wm/DimmerTests.java b/services/tests/wmtests/src/com/android/server/wm/DimmerTests.java
index 3beb7f2049df..55a7c1ba0bca 100644
--- a/services/tests/wmtests/src/com/android/server/wm/DimmerTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/DimmerTests.java
@@ -64,6 +64,11 @@ public class DimmerTests extends WindowTestsBase {
}
@Override
+ public SurfaceControl.Transaction getSyncTransaction() {
+ return mTransaction;
+ }
+
+ @Override
public SurfaceControl.Transaction getPendingTransaction() {
return mTransaction;
}
@@ -102,6 +107,11 @@ public class DimmerTests extends WindowTestsBase {
}
@Override
+ public SurfaceControl.Transaction getSyncTransaction() {
+ return mHostTransaction;
+ }
+
+ @Override
public SurfaceControl.Transaction getPendingTransaction() {
return mHostTransaction;
}
diff --git a/services/tests/wmtests/src/com/android/server/wm/DisplayContentTests.java b/services/tests/wmtests/src/com/android/server/wm/DisplayContentTests.java
index 89dfffb532ea..4716d15a1aca 100644
--- a/services/tests/wmtests/src/com/android/server/wm/DisplayContentTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/DisplayContentTests.java
@@ -124,8 +124,8 @@ import android.view.ContentRecordingSession;
import android.view.DisplayCutout;
import android.view.DisplayInfo;
import android.view.Gravity;
-import android.view.IDisplayWindowRotationCallback;
-import android.view.IDisplayWindowRotationController;
+import android.view.IDisplayChangeWindowCallback;
+import android.view.IDisplayChangeWindowController;
import android.view.ISystemGestureExclusionListener;
import android.view.IWindowManager;
import android.view.InsetsState;
@@ -136,6 +136,7 @@ import android.view.SurfaceControl;
import android.view.SurfaceControl.Transaction;
import android.view.View;
import android.view.WindowManager;
+import android.window.DisplayAreaInfo;
import android.window.IDisplayAreaOrganizer;
import android.window.WindowContainerToken;
@@ -1801,15 +1802,16 @@ public class DisplayContentTests extends WindowTestsBase {
return true;
}).when(dc).updateDisplayOverrideConfigurationLocked();
final boolean[] called = new boolean[1];
- mWm.mDisplayRotationController =
- new IDisplayWindowRotationController.Stub() {
+ mWm.mDisplayChangeController =
+ new IDisplayChangeWindowController.Stub() {
@Override
- public void onRotateDisplay(int displayId, int fromRotation, int toRotation,
- IDisplayWindowRotationCallback callback) {
+ public void onDisplayChange(int displayId, int fromRotation, int toRotation,
+ DisplayAreaInfo newDisplayAreaInfo,
+ IDisplayChangeWindowCallback callback) throws RemoteException {
called[0] = true;
try {
- callback.continueRotateDisplay(toRotation, null);
+ callback.continueDisplayChange(null);
} catch (RemoteException e) {
assertTrue(false);
}
@@ -1843,13 +1845,14 @@ public class DisplayContentTests extends WindowTestsBase {
// Rotate 180 degree so the display doesn't have configuration change. This condition is
// used for the later verification of stop-freezing (without setting mWaitingForConfig).
doReturn((dr.getRotation() + 2) % 4).when(dr).rotationForOrientation(anyInt(), anyInt());
- mWm.mDisplayRotationController =
- new IDisplayWindowRotationController.Stub() {
+ mWm.mDisplayChangeController =
+ new IDisplayChangeWindowController.Stub() {
@Override
- public void onRotateDisplay(int displayId, int fromRotation, int toRotation,
- IDisplayWindowRotationCallback callback) {
+ public void onDisplayChange(int displayId, int fromRotation, int toRotation,
+ DisplayAreaInfo newDisplayAreaInfo,
+ IDisplayChangeWindowCallback callback) throws RemoteException {
try {
- callback.continueRotateDisplay(toRotation, null);
+ callback.continueDisplayChange(null);
} catch (RemoteException e) {
assertTrue(false);
}
@@ -2212,23 +2215,28 @@ public class DisplayContentTests extends WindowTestsBase {
*/
@Test
public void testCreateTestDisplayContentFromDimensions() {
- final int displayWidth = 1000;
- final int displayHeight = 2000;
+ final int displayWidth = 540;
+ final int displayHeight = 960;
+ final int density = 192;
+ final int expectedWidthDp = 450; // = 540/(192/160)
+ final int expectedHeightDp = 800; // = 960/(192/160)
final int windowingMode = WINDOWING_MODE_FULLSCREEN;
final boolean ignoreOrientationRequests = false;
final float fixedOrientationLetterboxRatio = 0;
final DisplayContent testDisplayContent = new TestDisplayContent.Builder(mAtm, displayWidth,
- displayHeight).build();
+ displayHeight).setDensityDpi(density).build();
// test display info
final DisplayInfo di = testDisplayContent.getDisplayInfo();
assertEquals(displayWidth, di.logicalWidth);
assertEquals(displayHeight, di.logicalHeight);
- assertEquals(TestDisplayContent.DEFAULT_LOGICAL_DISPLAY_DENSITY, di.logicalDensityDpi);
+ assertEquals(density, di.logicalDensityDpi);
// test configuration
- final WindowConfiguration windowConfig = testDisplayContent.getConfiguration()
- .windowConfiguration;
+ final Configuration config = testDisplayContent.getConfiguration();
+ assertEquals(expectedWidthDp, config.screenWidthDp);
+ assertEquals(expectedHeightDp, config.screenHeightDp);
+ final WindowConfiguration windowConfig = config.windowConfiguration;
assertEquals(displayWidth, windowConfig.getBounds().width());
assertEquals(displayHeight, windowConfig.getBounds().height());
assertEquals(windowingMode, windowConfig.getWindowingMode());
diff --git a/services/tests/wmtests/src/com/android/server/wm/InsetsStateControllerTest.java b/services/tests/wmtests/src/com/android/server/wm/InsetsStateControllerTest.java
index 6d022262b720..ffa21fadff6b 100644
--- a/services/tests/wmtests/src/com/android/server/wm/InsetsStateControllerTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/InsetsStateControllerTest.java
@@ -449,6 +449,36 @@ public class InsetsStateControllerTest extends WindowTestsBase {
assertNotNull(app.getInsetsState().peekSource(ITYPE_NAVIGATION_BAR));
}
+ @UseTestDisplay(addWindows = W_INPUT_METHOD)
+ @Test
+ public void testGetInsetsHintForNewControl() {
+ final WindowState app1 = createTestWindow("app1");
+ final WindowState app2 = createTestWindow("app2");
+
+ makeWindowVisible(mImeWindow);
+ final InsetsSourceProvider imeInsetsProvider = getController().getSourceProvider(ITYPE_IME);
+ imeInsetsProvider.setWindowContainer(mImeWindow, null, null);
+ imeInsetsProvider.updateSourceFrame(mImeWindow.getFrame());
+
+ imeInsetsProvider.updateControlForTarget(app1, false);
+ imeInsetsProvider.onPostLayout();
+ final InsetsSourceControl control1 = imeInsetsProvider.getControl(app1);
+ assertNotNull(control1);
+ assertEquals(imeInsetsProvider.getSource().getFrame().height(),
+ control1.getInsetsHint().bottom);
+
+ // Simulate the IME control target updated from app1 to app2 when IME insets was invisible.
+ imeInsetsProvider.setServerVisible(false);
+ imeInsetsProvider.updateControlForTarget(app2, false);
+
+ // Verify insetsHint of the new control is same as last IME source frame after the layout.
+ imeInsetsProvider.onPostLayout();
+ final InsetsSourceControl control2 = imeInsetsProvider.getControl(app2);
+ assertNotNull(control2);
+ assertEquals(imeInsetsProvider.getSource().getFrame().height(),
+ control2.getInsetsHint().bottom);
+ }
+
private WindowState createTestWindow(String name) {
final WindowState win = createWindow(null, TYPE_APPLICATION, name);
win.setHasSurface(true);
diff --git a/services/tests/wmtests/src/com/android/server/wm/LetterboxTest.java b/services/tests/wmtests/src/com/android/server/wm/LetterboxTest.java
index 1e86522a2307..e502f2fbd173 100644
--- a/services/tests/wmtests/src/com/android/server/wm/LetterboxTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/LetterboxTest.java
@@ -63,7 +63,7 @@ public class LetterboxTest {
mLetterbox = new Letterbox(mSurfaces, StubTransaction::new,
() -> mAreCornersRounded, () -> Color.valueOf(mColor),
() -> mHasWallpaperBackground, () -> mBlurRadius, () -> mDarkScrimAlpha,
- /* doubleTapCallback= */ x -> {});
+ /* doubleTapCallbackX= */ x -> {}, /* doubleTapCallbackY= */ y -> {});
mTransaction = spy(StubTransaction.class);
}
diff --git a/services/tests/wmtests/src/com/android/server/wm/LockTaskControllerTest.java b/services/tests/wmtests/src/com/android/server/wm/LockTaskControllerTest.java
index 9fc9489e3c2e..1d14dc31fa26 100644
--- a/services/tests/wmtests/src/com/android/server/wm/LockTaskControllerTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/LockTaskControllerTest.java
@@ -82,6 +82,7 @@ import android.util.Pair;
import androidx.test.filters.SmallTest;
import com.android.internal.statusbar.IStatusBarService;
+import com.android.internal.telephony.CellBroadcastUtils;
import com.android.internal.widget.LockPatternUtils;
import com.android.server.LocalServices;
import com.android.server.statusbar.StatusBarManagerInternal;
@@ -297,6 +298,22 @@ public class LockTaskControllerTest {
}
@Test
+ public void testLockTaskViolation_wirelessEmergencyAlerts() {
+ // GIVEN one task record with allowlisted auth that is in lock task mode
+ Task tr = getTask(LOCK_TASK_AUTH_ALLOWLISTED);
+ mLockTaskController.startLockTaskMode(tr, false, TEST_UID);
+
+ // GIVEN cellbroadcast task necessary for emergency warning alerts
+ Task cellbroadcastreceiver = getTask(
+ new Intent().setComponent(
+ CellBroadcastUtils.getDefaultCellBroadcastAlertDialogComponent(mContext)),
+ LOCK_TASK_AUTH_PINNABLE);
+
+ // THEN the cellbroadcast task should all be allowed
+ assertFalse(mLockTaskController.isLockTaskModeViolation(cellbroadcastreceiver));
+ }
+
+ @Test
public void testStopLockTaskMode() throws Exception {
// GIVEN one task record with allowlisted auth that is in lock task mode
Task tr = getTask(LOCK_TASK_AUTH_ALLOWLISTED);
diff --git a/services/tests/wmtests/src/com/android/server/wm/RecentsAnimationControllerTest.java b/services/tests/wmtests/src/com/android/server/wm/RecentsAnimationControllerTest.java
index 021568dd97b4..eba276f99225 100644
--- a/services/tests/wmtests/src/com/android/server/wm/RecentsAnimationControllerTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/RecentsAnimationControllerTest.java
@@ -61,6 +61,7 @@ import android.platform.test.annotations.Presubmit;
import android.util.SparseBooleanArray;
import android.view.IRecentsAnimationRunner;
import android.view.SurfaceControl;
+import android.view.WindowManager.LayoutParams;
import android.window.TaskSnapshot;
import androidx.test.filters.SmallTest;
@@ -162,6 +163,30 @@ public class RecentsAnimationControllerTest extends WindowTestsBase {
}
@Test
+ public void testLaunchAndStartRecents_expectTargetAndVisible() throws Exception {
+ mWm.setRecentsAnimationController(mController);
+ final ActivityRecord homeActivity = createHomeActivity();
+ final Task task = createTask(mDefaultDisplay);
+ // Emulate that activity1 has just launched activity2, but app transition has not yet been
+ // executed.
+ final ActivityRecord activity1 = createActivityRecord(task);
+ activity1.setVisible(true);
+ activity1.mVisibleRequested = false;
+ activity1.addWindow(createWindowState(new LayoutParams(TYPE_BASE_APPLICATION), activity1));
+
+ final ActivityRecord activity2 = createActivityRecord(task);
+ activity2.setVisible(false);
+ activity2.mVisibleRequested = true;
+
+ mDefaultDisplay.getConfiguration().windowConfiguration.setRotation(
+ mDefaultDisplay.getRotation());
+ initializeRecentsAnimationController(mController, homeActivity);
+ mController.startAnimation();
+ verify(mMockRunner, never()).onAnimationCanceled(null /* taskIds */,
+ null /* taskSnapshots */);
+ }
+
+ @Test
public void testWallpaperIncluded_expectTarget() throws Exception {
mWm.setRecentsAnimationController(mController);
final ActivityRecord homeActivity = createHomeActivity();
diff --git a/services/tests/wmtests/src/com/android/server/wm/SizeCompatTests.java b/services/tests/wmtests/src/com/android/server/wm/SizeCompatTests.java
index 76fb7ff2e6f8..9dc51976d22f 100644
--- a/services/tests/wmtests/src/com/android/server/wm/SizeCompatTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/SizeCompatTests.java
@@ -1876,6 +1876,28 @@ public class SizeCompatTests extends WindowTestsBase {
}
@Test
+ public void testResizableFixedOrientationAppInSplitScreen_letterboxForDifferentOrientation() {
+ setUpDisplaySizeWithApp(1000, 2800);
+ final TestSplitOrganizer organizer =
+ new TestSplitOrganizer(mAtm, mActivity.getDisplayContent());
+
+ // Resizable landscape-only activity.
+ prepareLimitedBounds(mActivity, SCREEN_ORIENTATION_LANDSCAPE, /* isUnresizable= */ false);
+
+ final Rect originalBounds = new Rect(mActivity.getBounds());
+
+ // Move activity to split screen which takes half of the screen.
+ mTask.reparent(organizer.mPrimary, POSITION_TOP, /* moveParents= */ false , "test");
+ organizer.mPrimary.setBounds(0, 0, 1000, 1400);
+ assertEquals(WINDOWING_MODE_MULTI_WINDOW, mTask.getWindowingMode());
+ assertEquals(WINDOWING_MODE_MULTI_WINDOW, mActivity.getWindowingMode());
+
+ // Resizable activity is not in size compat mode but in the letterbox for fixed orientation.
+ assertFitted();
+ assertTrue(mActivity.isLetterboxedForFixedOrientationAndAspectRatio());
+ }
+
+ @Test
public void testSupportsNonResizableInSplitScreen_fillTaskForSameOrientation() {
// Support non resizable in multi window
mAtm.mDevEnableNonResizableMultiWindow = true;
@@ -1928,7 +1950,7 @@ public class SizeCompatTests extends WindowTestsBase {
prepareUnresizable(mActivity, /* maxAspect */ 1.1f, SCREEN_ORIENTATION_UNSPECIFIED);
// Bounds are letterboxed to respect the provided max aspect ratio.
- assertEquals(mActivity.getBounds(), new Rect(0, 0, 1000, 1100));
+ assertEquals(mActivity.getBounds(), new Rect(0, 850, 1000, 1950));
// Move activity to split screen which has landscape size.
mTask.reparent(organizer.mPrimary, POSITION_TOP, /* moveParents */ false, "test");
@@ -2045,19 +2067,14 @@ public class SizeCompatTests extends WindowTestsBase {
mActivity.mWmService.mLetterboxConfiguration.setLetterboxHorizontalPositionMultiplier(
letterboxHorizontalPositionMultiplier);
prepareUnresizable(mActivity, SCREEN_ORIENTATION_PORTRAIT);
-
assertEquals(fixedOrientationLetterbox, mActivity.getBounds());
-
// Rotate to put activity in size compat mode.
rotateDisplay(mActivity.mDisplayContent, ROTATION_90);
-
assertTrue(mActivity.inSizeCompatMode());
// Activity is in size compat mode but not scaled.
assertEquals(sizeCompatUnscaled, mActivity.getBounds());
-
// Force activity to scaled down for size compat mode.
resizeDisplay(mTask.mDisplayContent, 700, 1400);
-
assertTrue(mActivity.inSizeCompatMode());
assertScaled();
assertEquals(sizeCompatScaled, mActivity.getBounds());
@@ -2075,6 +2092,109 @@ public class SizeCompatTests extends WindowTestsBase {
}
@Test
+ public void testUpdateResolvedBoundsVerticalPosition_top() {
+ // Display configured as (1400, 2800).
+ assertVerticalPositionForDifferentDisplayConfigsForLandscapeActivity(
+ /* letterboxVerticalPositionMultiplier */ 0.0f,
+ // At launch.
+ /* fixedOrientationLetterbox */ new Rect(0, 0, 1400, 700),
+ // After 90 degree rotation.
+ /* sizeCompatUnscaled */ new Rect(700, 0, 2100, 700),
+ // After the display is resized to (1400, 700).
+ /* sizeCompatScaled */ new Rect(0, 0, 700, 350));
+ }
+
+ @Test
+ public void testUpdateResolvedBoundsVerticalPosition_center() {
+ // Display configured as (1400, 2800).
+ assertVerticalPositionForDifferentDisplayConfigsForLandscapeActivity(
+ /* letterboxVerticalPositionMultiplier */ 0.5f,
+ // At launch.
+ /* fixedOrientationLetterbox */ new Rect(0, 1050, 1400, 1750),
+ // After 90 degree rotation.
+ /* sizeCompatUnscaled */ new Rect(700, 350, 2100, 1050),
+ // After the display is resized to (1400, 700).
+ /* sizeCompatScaled */ new Rect(0, 525, 700, 875));
+ }
+
+ @Test
+ public void testUpdateResolvedBoundsVerticalPosition_invalidMultiplier_defaultToCenter() {
+ // Display configured as (1400, 2800).
+
+ // Below 0.0.
+ assertVerticalPositionForDifferentDisplayConfigsForLandscapeActivity(
+ /* letterboxVerticalPositionMultiplier */ -1.0f,
+ // At launch.
+ /* fixedOrientationLetterbox */ new Rect(0, 1050, 1400, 1750),
+ // After 90 degree rotation.
+ /* sizeCompatUnscaled */ new Rect(700, 350, 2100, 1050),
+ // After the display is resized to (1400, 700).
+ /* sizeCompatScaled */ new Rect(0, 525, 700, 875));
+
+ // Above 1.0
+ assertVerticalPositionForDifferentDisplayConfigsForLandscapeActivity(
+ /* letterboxVerticalPositionMultiplier */ 2.0f,
+ // At launch.
+ /* fixedOrientationLetterbox */ new Rect(0, 1050, 1400, 1750),
+ // After 90 degree rotation.
+ /* sizeCompatUnscaled */ new Rect(700, 350, 2100, 1050),
+ // After the display is resized to (1400, 700).
+ /* sizeCompatScaled */ new Rect(0, 525, 700, 875));
+ }
+
+ @Test
+ public void testUpdateResolvedBoundsVerticalPosition_bottom() {
+ // Display configured as (1400, 2800).
+ assertVerticalPositionForDifferentDisplayConfigsForLandscapeActivity(
+ /* letterboxVerticalPositionMultiplier */ 1.0f,
+ // At launch.
+ /* fixedOrientationLetterbox */ new Rect(0, 2100, 1400, 2800),
+ // After 90 degree rotation.
+ /* sizeCompatUnscaled */ new Rect(700, 700, 2100, 1400),
+ // After the display is resized to (1400, 700).
+ /* sizeCompatScaled */ new Rect(0, 1050, 700, 1400));
+ }
+
+ private void assertVerticalPositionForDifferentDisplayConfigsForLandscapeActivity(
+ float letterboxVerticalPositionMultiplier, Rect fixedOrientationLetterbox,
+ Rect sizeCompatUnscaled, Rect sizeCompatScaled) {
+ // Set up a display in portrait and ignoring orientation request.
+ setUpDisplaySizeWithApp(1400, 2800);
+ mActivity.mDisplayContent.setIgnoreOrientationRequest(true /* ignoreOrientationRequest */);
+
+ mActivity.mWmService.mLetterboxConfiguration.setLetterboxVerticalPositionMultiplier(
+ letterboxVerticalPositionMultiplier);
+ prepareUnresizable(mActivity, SCREEN_ORIENTATION_LANDSCAPE);
+
+ assertEquals(fixedOrientationLetterbox, mActivity.getBounds());
+
+ // Rotate to put activity in size compat mode.
+ rotateDisplay(mActivity.mDisplayContent, ROTATION_90);
+
+ assertTrue(mActivity.inSizeCompatMode());
+ // Activity is in size compat mode but not scaled.
+ assertEquals(sizeCompatUnscaled, mActivity.getBounds());
+
+ // Force activity to scaled down for size compat mode.
+ resizeDisplay(mTask.mDisplayContent, 1400, 700);
+
+ assertTrue(mActivity.inSizeCompatMode());
+ assertScaled();
+ assertEquals(sizeCompatScaled, mActivity.getBounds());
+ }
+
+ @Test
+ public void testUpdateResolvedBoundsVerticalPosition_activityFillParentHeight() {
+ // When activity height equals parent height, multiplier shouldn't have any effect.
+ assertVerticalPositionForDifferentDisplayConfigsForPortraitActivity(
+ /* letterboxVerticalPositionMultiplier */ 0.0f);
+ assertVerticalPositionForDifferentDisplayConfigsForPortraitActivity(
+ /* letterboxVerticalPositionMultiplier */ 0.5f);
+ assertVerticalPositionForDifferentDisplayConfigsForPortraitActivity(
+ /* letterboxVerticalPositionMultiplier */ 1.0f);
+ }
+
+ @Test
public void testAreBoundsLetterboxed_letterboxedForAspectRatio_returnsTrue() {
setUpDisplaySizeWithApp(1000, 2500);
@@ -2367,6 +2487,23 @@ public class SizeCompatTests extends WindowTestsBase {
mActivity.mWmService.mLetterboxConfiguration.setLetterboxHorizontalPositionMultiplier(
letterboxHorizontalPositionMultiplier);
prepareUnresizable(mActivity, SCREEN_ORIENTATION_LANDSCAPE);
+ assertFitted();
+ // Rotate to put activity in size compat mode.
+ rotateDisplay(mActivity.mDisplayContent, ROTATION_90);
+ assertTrue(mActivity.inSizeCompatMode());
+ // Activity is in size compat mode but not scaled.
+ assertEquals(new Rect(0, 1050, 1400, 1750), mActivity.getBounds());
+ }
+
+ private void assertVerticalPositionForDifferentDisplayConfigsForPortraitActivity(
+ float letterboxVerticalPositionMultiplier) {
+ // Set up a display in portrait and ignoring orientation request.
+ setUpDisplaySizeWithApp(1400, 2800);
+ mActivity.mDisplayContent.setIgnoreOrientationRequest(true /* ignoreOrientationRequest */);
+
+ mActivity.mWmService.mLetterboxConfiguration.setLetterboxVerticalPositionMultiplier(
+ letterboxVerticalPositionMultiplier);
+ prepareUnresizable(mActivity, SCREEN_ORIENTATION_PORTRAIT);
assertFitted();
@@ -2375,7 +2512,7 @@ public class SizeCompatTests extends WindowTestsBase {
assertTrue(mActivity.inSizeCompatMode());
// Activity is in size compat mode but not scaled.
- assertEquals(new Rect(0, 1050, 1400, 1750), mActivity.getBounds());
+ assertEquals(new Rect(1050, 0, 1750, 1400), mActivity.getBounds());
}
private static WindowState addWindowToActivity(ActivityRecord activity) {
diff --git a/services/tests/wmtests/src/com/android/server/wm/SurfaceAnimatorTest.java b/services/tests/wmtests/src/com/android/server/wm/SurfaceAnimatorTest.java
index 79ba1759f4c4..ff0063c4ffa0 100644
--- a/services/tests/wmtests/src/com/android/server/wm/SurfaceAnimatorTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/SurfaceAnimatorTest.java
@@ -338,6 +338,11 @@ public class SurfaceAnimatorTest extends WindowTestsBase {
}
@Override
+ public SurfaceControl.Transaction getSyncTransaction() {
+ return mTransaction;
+ }
+
+ @Override
public Transaction getPendingTransaction() {
return mTransaction;
}
diff --git a/services/tests/wmtests/src/com/android/server/wm/TaskFragmentOrganizerControllerTest.java b/services/tests/wmtests/src/com/android/server/wm/TaskFragmentOrganizerControllerTest.java
index 75b5e73a604e..5340a79f4b94 100644
--- a/services/tests/wmtests/src/com/android/server/wm/TaskFragmentOrganizerControllerTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/TaskFragmentOrganizerControllerTest.java
@@ -511,11 +511,12 @@ public class TaskFragmentOrganizerControllerTest extends WindowTestsBase {
@Test
public void testApplyTransaction_reparentActivityToTaskFragment_triggerLifecycleUpdate()
throws RemoteException {
- final ActivityRecord activity = createActivityRecord(mDefaultDisplay);
+ final Task task = createTask(mDisplayContent);
+ final ActivityRecord activity = createActivityRecord(task);
mOrganizer.applyTransaction(mTransaction);
mController.registerOrganizer(mIOrganizer);
mTaskFragment = new TaskFragmentBuilder(mAtm)
- .setCreateParentTask()
+ .setParentTask(task)
.setFragmentToken(mFragmentToken)
.build();
mAtm.mWindowOrganizerController.mLaunchTaskFragments
diff --git a/services/tests/wmtests/src/com/android/server/wm/TransitionTests.java b/services/tests/wmtests/src/com/android/server/wm/TransitionTests.java
index 16adffdba6c3..d9d819b5f00f 100644
--- a/services/tests/wmtests/src/com/android/server/wm/TransitionTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/TransitionTests.java
@@ -821,8 +821,11 @@ public class TransitionTests extends WindowTestsBase {
player.onTransactionReady(mDisplayContent.getSyncTransaction());
final DisplayRotation displayRotation = mDisplayContent.getDisplayRotation();
+ final RemoteDisplayChangeController displayChangeController = mDisplayContent
+ .mRemoteDisplayChangeController;
spyOn(displayRotation);
- doReturn(true).when(displayRotation).isWaitingForRemoteRotation();
+ spyOn(displayChangeController);
+ doReturn(true).when(displayChangeController).isWaitingForRemoteDisplayChange();
doReturn(prevRotation + 1).when(displayRotation).rotationForOrientation(
anyInt() /* orientation */, anyInt() /* lastRotation */);
// Rotation update is skipped while the recents animation is running.
diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowProcessControllerTests.java b/services/tests/wmtests/src/com/android/server/wm/WindowProcessControllerTests.java
index 746f2b50ac3a..3abf7ce665ae 100644
--- a/services/tests/wmtests/src/com/android/server/wm/WindowProcessControllerTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/WindowProcessControllerTests.java
@@ -21,6 +21,7 @@ import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
import static android.content.res.Configuration.ORIENTATION_LANDSCAPE;
import static android.content.res.Configuration.ORIENTATION_PORTRAIT;
+import static com.android.dx.mockito.inline.extended.ExtendedMockito.doNothing;
import static com.android.dx.mockito.inline.extended.ExtendedMockito.never;
import static com.android.dx.mockito.inline.extended.ExtendedMockito.spyOn;
import static com.android.dx.mockito.inline.extended.ExtendedMockito.verify;
@@ -39,24 +40,30 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.when;
import android.Manifest;
+import android.app.ActivityManager;
+import android.app.ClientTransactionHandler;
import android.app.IApplicationThread;
+import android.app.servertransaction.ConfigurationChangeItem;
import android.content.ComponentName;
import android.content.pm.ApplicationInfo;
import android.content.pm.ServiceInfo;
import android.content.res.Configuration;
import android.graphics.Rect;
import android.os.LocaleList;
+import android.os.RemoteException;
import android.platform.test.annotations.Presubmit;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.mockito.Mockito;
@@ -282,6 +289,39 @@ public class WindowProcessControllerTests extends WindowTestsBase {
}
@Test
+ public void testCachedStateConfigurationChange() throws RemoteException {
+ final ClientLifecycleManager clientManager = mAtm.getLifecycleManager();
+ doNothing().when(clientManager).scheduleTransaction(any(), any());
+ final IApplicationThread thread = mWpc.getThread();
+ final Configuration newConfig = new Configuration(mWpc.getConfiguration());
+ newConfig.densityDpi += 100;
+ // Non-cached state will send the change directly.
+ mWpc.setReportedProcState(ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND);
+ clearInvocations(clientManager);
+ mWpc.onConfigurationChanged(newConfig);
+ verify(clientManager).scheduleTransaction(eq(thread), any());
+
+ // Cached state won't send the change.
+ clearInvocations(clientManager);
+ mWpc.setReportedProcState(ActivityManager.PROCESS_STATE_CACHED_ACTIVITY);
+ newConfig.densityDpi += 100;
+ mWpc.onConfigurationChanged(newConfig);
+ verify(clientManager, never()).scheduleTransaction(eq(thread), any());
+
+ // Cached -> non-cached will send the previous deferred config immediately.
+ mWpc.setReportedProcState(ActivityManager.PROCESS_STATE_RECEIVER);
+ final ArgumentCaptor<ConfigurationChangeItem> captor =
+ ArgumentCaptor.forClass(ConfigurationChangeItem.class);
+ verify(clientManager).scheduleTransaction(eq(thread), captor.capture());
+ final ClientTransactionHandler client = mock(ClientTransactionHandler.class);
+ captor.getValue().preExecute(client, null /* token */);
+ final ArgumentCaptor<Configuration> configCaptor =
+ ArgumentCaptor.forClass(Configuration.class);
+ verify(client).updatePendingConfiguration(configCaptor.capture());
+ assertEquals(newConfig, configCaptor.getValue());
+ }
+
+ @Test
public void testComputeOomAdjFromActivities() {
final ActivityRecord activity = createActivityRecord(mWpc);
activity.mVisibleRequested = true;
diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowTestsBase.java b/services/tests/wmtests/src/com/android/server/wm/WindowTestsBase.java
index 9957d05d0a52..e138d52b8ef6 100644
--- a/services/tests/wmtests/src/com/android/server/wm/WindowTestsBase.java
+++ b/services/tests/wmtests/src/com/android/server/wm/WindowTestsBase.java
@@ -229,14 +229,22 @@ class WindowTestsBase extends SystemServiceTestsBase {
// {@link com.android.internal.R.dimen.config_fixedOrientationLetterboxAspectRatio}, is set
// on some device form factors.
mAtm.mWindowManager.mLetterboxConfiguration.setFixedOrientationLetterboxAspectRatio(0);
- // Ensure letterbox position multiplier is not overridden on any device target.
+ // Ensure letterbox horizontal position multiplier is not overridden on any device target.
// {@link com.android.internal.R.dimen.config_letterboxHorizontalPositionMultiplier},
// may be set on some device form factors.
mAtm.mWindowManager.mLetterboxConfiguration.setLetterboxHorizontalPositionMultiplier(0.5f);
- // Ensure letterbox reachability treatment isn't overridden on any device target.
- // {@link com.android.internal.R.bool.config_letterboxIsReachabilityEnabled},
+ // Ensure letterbox vertical position multiplier is not overridden on any device target.
+ // {@link com.android.internal.R.dimen.config_letterboxHorizontalPositionMultiplier},
+ // may be set on some device form factors.
+ mAtm.mWindowManager.mLetterboxConfiguration.setLetterboxVerticalPositionMultiplier(0.5f);
+ // Ensure letterbox horizontal reachability treatment isn't overridden on any device target.
+ // {@link com.android.internal.R.bool.config_letterboxIsHorizontalReachabilityEnabled},
+ // may be set on some device form factors.
+ mAtm.mWindowManager.mLetterboxConfiguration.setIsHorizontalReachabilityEnabled(false);
+ // Ensure letterbox vertical reachability treatment isn't overridden on any device target.
+ // {@link com.android.internal.R.bool.config_letterboxIsVerticalReachabilityEnabled},
// may be set on some device form factors.
- mAtm.mWindowManager.mLetterboxConfiguration.setIsReachabilityEnabled(false);
+ mAtm.mWindowManager.mLetterboxConfiguration.setIsVerticalReachabilityEnabled(false);
checkDeviceSpecificOverridesNotApplied();
}
@@ -246,7 +254,8 @@ class WindowTestsBase extends SystemServiceTestsBase {
// Revert back to device overrides.
mAtm.mWindowManager.mLetterboxConfiguration.resetFixedOrientationLetterboxAspectRatio();
mAtm.mWindowManager.mLetterboxConfiguration.resetLetterboxHorizontalPositionMultiplier();
- mAtm.mWindowManager.mLetterboxConfiguration.resetIsReachabilityEnabled();
+ mAtm.mWindowManager.mLetterboxConfiguration.resetIsHorizontalReachabilityEnabled();
+ mAtm.mWindowManager.mLetterboxConfiguration.resetIsVerticalReachabilityEnabled();
}
/**
diff --git a/services/usb/java/com/android/server/usb/UsbDirectMidiDevice.java b/services/usb/java/com/android/server/usb/UsbDirectMidiDevice.java
index 2893f807c8a8..dc96c66bff29 100644
--- a/services/usb/java/com/android/server/usb/UsbDirectMidiDevice.java
+++ b/services/usb/java/com/android/server/usb/UsbDirectMidiDevice.java
@@ -89,38 +89,36 @@ public final class UsbDirectMidiDevice implements Closeable {
private final Object mLock = new Object();
private boolean mIsOpen;
+ private boolean mServerAvailable;
private UsbMidiPacketConverter mUsbMidiPacketConverter;
private final MidiDeviceServer.Callback mCallback = new MidiDeviceServer.Callback() {
-
@Override
public void onDeviceStatusChanged(MidiDeviceServer server, MidiDeviceStatus status) {
MidiDeviceInfo deviceInfo = status.getDeviceInfo();
int numInputPorts = deviceInfo.getInputPortCount();
int numOutputPorts = deviceInfo.getOutputPortCount();
- boolean hasOpenPorts = false;
+ int numOpenPorts = 0;
for (int i = 0; i < numInputPorts; i++) {
if (status.isInputPortOpen(i)) {
- hasOpenPorts = true;
- break;
+ numOpenPorts++;
}
}
- if (!hasOpenPorts) {
- for (int i = 0; i < numOutputPorts; i++) {
- if (status.getOutputPortOpenCount(i) > 0) {
- hasOpenPorts = true;
- break;
- }
+ for (int i = 0; i < numOutputPorts; i++) {
+ if (status.getOutputPortOpenCount(i) > 0) {
+ numOpenPorts += status.getOutputPortOpenCount(i);
}
}
synchronized (mLock) {
- if (hasOpenPorts && !mIsOpen) {
+ Log.d(TAG, "numOpenPorts: " + numOpenPorts + " isOpen: " + mIsOpen
+ + " mServerAvailable: " + mServerAvailable);
+ if ((numOpenPorts > 0) && !mIsOpen && mServerAvailable) {
openLocked();
- } else if (!hasOpenPorts && mIsOpen) {
+ } else if ((numOpenPorts == 0) && mIsOpen) {
closeLocked();
}
}
@@ -348,7 +346,7 @@ public final class UsbDirectMidiDevice implements Closeable {
final UsbRequest response = connectionFinal.requestWait();
if (response != request) {
Log.w(TAG, "Unexpected response");
- continue;
+ break;
}
int bytesRead = byteBuffer.position();
@@ -462,7 +460,7 @@ public final class UsbDirectMidiDevice implements Closeable {
mContext = context;
MidiManager midiManager = context.getSystemService(MidiManager.class);
if (midiManager == null) {
- Log.e(TAG, "No MidiManager in UsbDirectMidiDevice.create()");
+ Log.e(TAG, "No MidiManager in UsbDirectMidiDevice.register()");
return false;
}
@@ -499,6 +497,7 @@ public final class UsbDirectMidiDevice implements Closeable {
mUsbDevice.getSerialNumber());
properties.putParcelable(MidiDeviceInfo.PROPERTY_USB_DEVICE, mUsbDevice);
+ mServerAvailable = true;
mServer = midiManager.createDeviceServer(mMidiInputPortReceivers, mNumInputs,
null, null, properties, MidiDeviceInfo.TYPE_USB, mDefaultMidiProtocol, mCallback);
if (mServer == null) {
@@ -514,6 +513,7 @@ public final class UsbDirectMidiDevice implements Closeable {
if (mIsOpen) {
closeLocked();
}
+ mServerAvailable = false;
}
if (mServer != null) {
diff --git a/services/usb/java/com/android/server/usb/UsbMidiDevice.java b/services/usb/java/com/android/server/usb/UsbMidiDevice.java
index 275f21755141..67955e155f19 100644
--- a/services/usb/java/com/android/server/usb/UsbMidiDevice.java
+++ b/services/usb/java/com/android/server/usb/UsbMidiDevice.java
@@ -71,40 +71,38 @@ public final class UsbMidiDevice implements Closeable {
private final Object mLock = new Object();
private boolean mIsOpen;
+ private boolean mServerAvailable;
// pipe file descriptor for signalling input thread to exit
// only accessed from JNI code
private int mPipeFD = -1;
private final MidiDeviceServer.Callback mCallback = new MidiDeviceServer.Callback() {
-
@Override
public void onDeviceStatusChanged(MidiDeviceServer server, MidiDeviceStatus status) {
MidiDeviceInfo deviceInfo = status.getDeviceInfo();
- int inputPorts = deviceInfo.getInputPortCount();
- int outputPorts = deviceInfo.getOutputPortCount();
- boolean hasOpenPorts = false;
+ int numInputPorts = deviceInfo.getInputPortCount();
+ int numOutputPorts = deviceInfo.getOutputPortCount();
+ int numOpenPorts = 0;
- for (int i = 0; i < inputPorts; i++) {
+ for (int i = 0; i < numInputPorts; i++) {
if (status.isInputPortOpen(i)) {
- hasOpenPorts = true;
- break;
+ numOpenPorts++;
}
}
- if (!hasOpenPorts) {
- for (int i = 0; i < outputPorts; i++) {
- if (status.getOutputPortOpenCount(i) > 0) {
- hasOpenPorts = true;
- break;
- }
+ for (int i = 0; i < numOutputPorts; i++) {
+ if (status.getOutputPortOpenCount(i) > 0) {
+ numOpenPorts += status.getOutputPortOpenCount(i);
}
}
synchronized (mLock) {
- if (hasOpenPorts && !mIsOpen) {
+ Log.d(TAG, "numOpenPorts: " + numOpenPorts + " isOpen: " + mIsOpen
+ + " mServerAvailable: " + mServerAvailable);
+ if ((numOpenPorts > 0) && !mIsOpen && mServerAvailable) {
openLocked();
- } else if (!hasOpenPorts && mIsOpen) {
+ } else if ((numOpenPorts == 0) && mIsOpen) {
closeLocked();
}
}
@@ -298,10 +296,11 @@ public final class UsbMidiDevice implements Closeable {
private boolean register(Context context, Bundle properties) {
MidiManager midiManager = (MidiManager)context.getSystemService(Context.MIDI_SERVICE);
if (midiManager == null) {
- Log.e(TAG, "No MidiManager in UsbMidiDevice.create()");
+ Log.e(TAG, "No MidiManager in UsbMidiDevice.register()");
return false;
}
+ mServerAvailable = true;
mServer = midiManager.createDeviceServer(mMidiInputPortReceivers, mNumInputs,
null, null, properties, MidiDeviceInfo.TYPE_USB,
MidiDeviceInfo.PROTOCOL_UNKNOWN, mCallback);
@@ -318,6 +317,7 @@ public final class UsbMidiDevice implements Closeable {
if (mIsOpen) {
closeLocked();
}
+ mServerAvailable = false;
}
if (mServer != null) {
diff --git a/services/voiceinteraction/java/com/android/server/voiceinteraction/HotwordDetectionConnection.java b/services/voiceinteraction/java/com/android/server/voiceinteraction/HotwordDetectionConnection.java
index 3610d8362d6a..2a1a6462d933 100644
--- a/services/voiceinteraction/java/com/android/server/voiceinteraction/HotwordDetectionConnection.java
+++ b/services/voiceinteraction/java/com/android/server/voiceinteraction/HotwordDetectionConnection.java
@@ -122,6 +122,10 @@ final class HotwordDetectionConnection {
private static final long RESET_DEBUG_HOTWORD_LOGGING_TIMEOUT_MILLIS = 60 * 60 * 1000; // 1 hour
private static final int MAX_ISOLATED_PROCESS_NUMBER = 10;
+ // The error codes are used for onError callback
+ private static final int HOTWORD_DETECTION_SERVICE_DIED = -1;
+ private static final int CALLBACK_ONDETECTED_GOT_SECURITY_EXCEPTION = -2;
+
// Hotword metrics
private static final int METRICS_INIT_UNKNOWN_TIMEOUT =
HOTWORD_DETECTION_SERVICE_INIT_RESULT_REPORTED__RESULT__CALLBACK_INIT_STATE_UNKNOWN_TIMEOUT;
@@ -418,19 +422,24 @@ final class HotwordDetectionConnection {
Slog.d(TAG, "onDetected");
}
synchronized (mLock) {
- if (mPerformingSoftwareHotwordDetection) {
+ if (!mPerformingSoftwareHotwordDetection) {
+ Slog.i(TAG, "Hotword detection has already completed");
+ return;
+ }
+ mPerformingSoftwareHotwordDetection = false;
+ try {
enforcePermissionsForDataDelivery();
- mSoftwareCallback.onDetected(result, null, null);
- mPerformingSoftwareHotwordDetection = false;
- if (result != null) {
- Slog.i(TAG, "Egressed " + HotwordDetectedResult.getUsageSize(result)
- + " bits from hotword trusted process");
- if (mDebugHotwordLogging) {
- Slog.i(TAG, "Egressed detected result: " + result);
- }
+ } catch (SecurityException e) {
+ mSoftwareCallback.onError();
+ return;
+ }
+ mSoftwareCallback.onDetected(result, null, null);
+ if (result != null) {
+ Slog.i(TAG, "Egressed " + HotwordDetectedResult.getUsageSize(result)
+ + " bits from hotword trusted process");
+ if (mDebugHotwordLogging) {
+ Slog.i(TAG, "Egressed detected result: " + result);
}
- } else {
- Slog.i(TAG, "Hotword detection has already completed");
}
}
}
@@ -511,19 +520,24 @@ final class HotwordDetectionConnection {
public void onDetected(HotwordDetectedResult result) throws RemoteException {
Slog.v(TAG, "onDetected");
synchronized (mLock) {
- if (mValidatingDspTrigger) {
- mValidatingDspTrigger = false;
+ if (!mValidatingDspTrigger) {
+ Slog.i(TAG, "Ignored hotword detected since trigger has been handled");
+ return;
+ }
+ mValidatingDspTrigger = false;
+ try {
enforcePermissionsForDataDelivery();
- externalCallback.onKeyphraseDetected(recognitionEvent, result);
- if (result != null) {
- Slog.i(TAG, "Egressed " + HotwordDetectedResult.getUsageSize(result)
- + " bits from hotword trusted process");
- if (mDebugHotwordLogging) {
- Slog.i(TAG, "Egressed detected result: " + result);
- }
+ } catch (SecurityException e) {
+ externalCallback.onError(CALLBACK_ONDETECTED_GOT_SECURITY_EXCEPTION);
+ return;
+ }
+ externalCallback.onKeyphraseDetected(recognitionEvent, result);
+ if (result != null) {
+ Slog.i(TAG, "Egressed " + HotwordDetectedResult.getUsageSize(result)
+ + " bits from hotword trusted process");
+ if (mDebugHotwordLogging) {
+ Slog.i(TAG, "Egressed detected result: " + result);
}
- } else {
- Slog.i(TAG, "Ignored hotword detected since trigger has been handled");
}
}
}
@@ -593,7 +607,8 @@ final class HotwordDetectionConnection {
HotwordMetricsLogger.writeKeyphraseTriggerEvent(
mDetectorType,
METRICS_KEYPHRASE_TRIGGERED_DETECT_SECURITY_EXCEPTION);
- throw e;
+ externalCallback.onError(CALLBACK_ONDETECTED_GOT_SECURITY_EXCEPTION);
+ return;
}
externalCallback.onKeyphraseDetected(recognitionEvent, result);
if (result != null) {
@@ -883,7 +898,13 @@ final class HotwordDetectionConnection {
throws RemoteException {
bestEffortClose(serviceAudioSink);
bestEffortClose(serviceAudioSource);
- enforcePermissionsForDataDelivery();
+ try {
+ enforcePermissionsForDataDelivery();
+ } catch (SecurityException e) {
+ bestEffortClose(audioSource);
+ callback.onError();
+ return;
+ }
callback.onDetected(triggerResult, null /* audioFormat */,
null /* audioStream */);
if (triggerResult != null) {
@@ -982,7 +1003,7 @@ final class HotwordDetectionConnection {
Slog.w(TAG, "binderDied");
try {
- mCallback.onError(-1);
+ mCallback.onError(HOTWORD_DETECTION_SERVICE_DIED);
} catch (RemoteException e) {
Slog.w(TAG, "Failed to report onError status: " + e);
}
diff --git a/telecomm/java/android/telecom/Call.java b/telecomm/java/android/telecom/Call.java
index 980ea5cd7f8c..432af3aa1aa0 100644
--- a/telecomm/java/android/telecom/Call.java
+++ b/telecomm/java/android/telecom/Call.java
@@ -2895,7 +2895,19 @@ public final class Call {
if (key != null) {
final Object value = bundle.get(key);
final Object newValue = newBundle.get(key);
- if (!Objects.equals(value, newValue)) {
+ if (!newBundle.containsKey(key)) {
+ return false;
+ }
+ if (value instanceof Bundle && newValue instanceof Bundle) {
+ if (!areBundlesEqual((Bundle) value, (Bundle) newValue)) {
+ return false;
+ }
+ }
+ if (value instanceof byte[] && newValue instanceof byte[]) {
+ if (!Arrays.equals((byte[]) value, (byte[]) newValue)) {
+ return false;
+ }
+ } else if (!Objects.equals(value, newValue)) {
return false;
}
}
diff --git a/telephony/common/android/telephony/LocationAccessPolicy.java b/telephony/common/android/telephony/LocationAccessPolicy.java
index 85d59a216f25..d4b6c91eb7a0 100644
--- a/telephony/common/android/telephony/LocationAccessPolicy.java
+++ b/telephony/common/android/telephony/LocationAccessPolicy.java
@@ -316,9 +316,11 @@ public final class LocationAccessPolicy {
return LocationPermissionResult.ALLOWED;
}
- // Check the system-wide requirements. If the location main switch is off or
- // the app's profile isn't in foreground, return a soft denial.
- if (!checkSystemLocationAccess(context, query.callingUid, query.callingPid)) {
+ // Check the system-wide requirements. If the location main switch is off and the caller is
+ // not in the allowlist of apps that always have loation access or the app's profile
+ // isn't in the foreground, return a soft denial.
+ if (!checkSystemLocationAccess(context, query.callingUid, query.callingPid,
+ query.callingPackage)) {
return LocationPermissionResult.DENIED_SOFT;
}
@@ -344,15 +346,16 @@ public final class LocationAccessPolicy {
return LocationPermissionResult.ALLOWED;
}
-
private static boolean checkManifestPermission(Context context, int pid, int uid,
String permissionToCheck) {
return context.checkPermission(permissionToCheck, pid, uid)
== PackageManager.PERMISSION_GRANTED;
}
- private static boolean checkSystemLocationAccess(@NonNull Context context, int uid, int pid) {
- if (!isLocationModeEnabled(context, UserHandle.getUserHandleForUid(uid).getIdentifier())) {
+ private static boolean checkSystemLocationAccess(@NonNull Context context, int uid, int pid,
+ @NonNull String callingPackage) {
+ if (!isLocationModeEnabled(context, UserHandle.getUserHandleForUid(uid).getIdentifier())
+ && !isLocationBypassAllowed(context, callingPackage)) {
if (DBG) Log.w(TAG, "Location disabled, failed, (" + uid + ")");
return false;
}
@@ -361,7 +364,10 @@ public final class LocationAccessPolicy {
return isCurrentProfile(context, uid) || checkInteractAcrossUsersFull(context, pid, uid);
}
- private static boolean isLocationModeEnabled(@NonNull Context context, @UserIdInt int userId) {
+ /**
+ * @return Whether location is enabled for the given user.
+ */
+ public static boolean isLocationModeEnabled(@NonNull Context context, @UserIdInt int userId) {
LocationManager locationManager = context.getSystemService(LocationManager.class);
if (locationManager == null) {
Log.w(TAG, "Couldn't get location manager, denying location access");
@@ -370,6 +376,24 @@ public final class LocationAccessPolicy {
return locationManager.isLocationEnabledForUser(UserHandle.of(userId));
}
+ private static boolean isLocationBypassAllowed(@NonNull Context context,
+ @NonNull String callingPackage) {
+ for (String bypassPackage : getLocationBypassPackages(context)) {
+ if (callingPackage.equals(bypassPackage)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * @return An array of packages that are always allowed to access location.
+ */
+ public static @NonNull String[] getLocationBypassPackages(@NonNull Context context) {
+ return context.getResources().getStringArray(
+ com.android.internal.R.array.config_serviceStateLocationAllowedPackages);
+ }
+
private static boolean checkInteractAcrossUsersFull(
@NonNull Context context, int pid, int uid) {
return checkManifestPermission(context, pid, uid,
diff --git a/telephony/common/com/android/internal/telephony/CellBroadcastUtils.java b/telephony/common/com/android/internal/telephony/CellBroadcastUtils.java
index 6c6375586225..6181329bcb2a 100644
--- a/telephony/common/com/android/internal/telephony/CellBroadcastUtils.java
+++ b/telephony/common/com/android/internal/telephony/CellBroadcastUtils.java
@@ -16,6 +16,7 @@
package com.android.internal.telephony;
+import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
@@ -62,4 +63,17 @@ public class CellBroadcastUtils {
return packageName;
}
+
+ /**
+ * Utility method to get cellbroadcast alert dialog component name
+ */
+ public static ComponentName getDefaultCellBroadcastAlertDialogComponent(Context context) {
+ String cellBroadcastReceiverPackageName =
+ getDefaultCellBroadcastReceiverPackageName(context);
+ if (TextUtils.isEmpty(cellBroadcastReceiverPackageName)) {
+ return null;
+ }
+ return ComponentName.createRelative(cellBroadcastReceiverPackageName,
+ "com.android.cellbroadcastreceiver.CellBroadcastAlertDialog");
+ }
}
diff --git a/telephony/common/com/android/internal/telephony/SmsApplication.java b/telephony/common/com/android/internal/telephony/SmsApplication.java
index 78b0b844865d..4924a82c385f 100644
--- a/telephony/common/com/android/internal/telephony/SmsApplication.java
+++ b/telephony/common/com/android/internal/telephony/SmsApplication.java
@@ -68,7 +68,6 @@ import java.util.stream.Collectors;
public final class SmsApplication {
static final String LOG_TAG = "SmsApplication";
public static final String PHONE_PACKAGE_NAME = "com.android.phone";
- public static final String BLUETOOTH_PACKAGE_NAME = "com.android.bluetooth.services";
public static final String MMS_SERVICE_PACKAGE_NAME = "com.android.mms.service";
public static final String TELEPHONY_PROVIDER_PACKAGE_NAME = "com.android.providers.telephony";
@@ -541,11 +540,13 @@ public final class SmsApplication {
PackageManager packageManager = context.getPackageManager();
AppOpsManager appOps = context.getSystemService(AppOpsManager.class);
+ final String bluetoothPackageName = context.getResources()
+ .getString(com.android.internal.R.string.config_systemBluetoothStack);
// Assign permission to special system apps
assignExclusiveSmsPermissionsToSystemApp(context, packageManager, appOps,
PHONE_PACKAGE_NAME, true);
assignExclusiveSmsPermissionsToSystemApp(context, packageManager, appOps,
- BLUETOOTH_PACKAGE_NAME, true);
+ bluetoothPackageName, false);
assignExclusiveSmsPermissionsToSystemApp(context, packageManager, appOps,
MMS_SERVICE_PACKAGE_NAME, true);
assignExclusiveSmsPermissionsToSystemApp(context, packageManager, appOps,
@@ -1128,8 +1129,11 @@ public final class SmsApplication {
return false;
}
final String defaultSmsPackage = getDefaultSmsApplicationPackageName(context);
+ final String bluetoothPackageName = context.getResources()
+ .getString(com.android.internal.R.string.config_systemBluetoothStack);
+
if ((defaultSmsPackage != null && defaultSmsPackage.equals(packageName))
- || BLUETOOTH_PACKAGE_NAME.equals(packageName)) {
+ || bluetoothPackageName.equals(packageName)) {
return true;
}
return false;
diff --git a/telephony/java/android/telephony/NetworkRegistrationInfo.java b/telephony/java/android/telephony/NetworkRegistrationInfo.java
index c701e443a426..1d6798b7fc6e 100644
--- a/telephony/java/android/telephony/NetworkRegistrationInfo.java
+++ b/telephony/java/android/telephony/NetworkRegistrationInfo.java
@@ -183,8 +183,17 @@ public final class NetworkRegistrationInfo implements Parcelable {
@TransportType
private final int mTransportType;
+ /**
+ * The initial registration state
+ */
+ @RegistrationState
+ private final int mInitialRegistrationState;
+
+ /**
+ * The registration state that might have been overridden by config
+ */
@RegistrationState
- private final int mRegistrationState;
+ private int mRegistrationState;
/**
* Save the {@link ServiceState.RoamingType roaming type}. it can be overridden roaming type
@@ -255,6 +264,7 @@ public final class NetworkRegistrationInfo implements Parcelable {
mDomain = domain;
mTransportType = transportType;
mRegistrationState = registrationState;
+ mInitialRegistrationState = registrationState;
mRoamingType = (registrationState == REGISTRATION_STATE_ROAMING)
? ServiceState.ROAMING_TYPE_UNKNOWN : ServiceState.ROAMING_TYPE_NOT_ROAMING;
setAccessNetworkTechnology(accessNetworkTechnology);
@@ -310,6 +320,7 @@ public final class NetworkRegistrationInfo implements Parcelable {
mDomain = source.readInt();
mTransportType = source.readInt();
mRegistrationState = source.readInt();
+ mInitialRegistrationState = source.readInt();
mRoamingType = source.readInt();
mAccessNetworkTechnology = source.readInt();
mRejectCause = source.readInt();
@@ -336,6 +347,7 @@ public final class NetworkRegistrationInfo implements Parcelable {
mDomain = nri.mDomain;
mTransportType = nri.mTransportType;
mRegistrationState = nri.mRegistrationState;
+ mInitialRegistrationState = nri.mInitialRegistrationState;
mRoamingType = nri.mRoamingType;
mAccessNetworkTechnology = nri.mAccessNetworkTechnology;
mIsUsingCarrierAggregation = nri.mIsUsingCarrierAggregation;
@@ -398,6 +410,15 @@ public final class NetworkRegistrationInfo implements Parcelable {
}
/**
+ * @return The initial registration state.
+ *
+ * @hide
+ */
+ public @RegistrationState int getInitialRegistrationState() {
+ return mInitialRegistrationState;
+ }
+
+ /**
* @return {@code true} if registered on roaming or home network, {@code false} otherwise.
*/
public boolean isRegistered() {
@@ -451,6 +472,17 @@ public final class NetworkRegistrationInfo implements Parcelable {
*/
public void setRoamingType(@ServiceState.RoamingType int roamingType) {
mRoamingType = roamingType;
+
+ // make sure mRegistrationState to be consistent in case of any roaming type override
+ if (isRoaming()) {
+ if (mRegistrationState == REGISTRATION_STATE_HOME) {
+ mRegistrationState = REGISTRATION_STATE_ROAMING;
+ }
+ } else {
+ if (mRegistrationState == REGISTRATION_STATE_ROAMING) {
+ mRegistrationState = REGISTRATION_STATE_HOME;
+ }
+ }
}
/**
@@ -634,6 +666,8 @@ public final class NetworkRegistrationInfo implements Parcelable {
.append(" transportType=").append(
AccessNetworkConstants.transportTypeToString(mTransportType))
.append(" registrationState=").append(registrationStateToString(mRegistrationState))
+ .append(" mInitialRegistrationState=")
+ .append(registrationStateToString(mInitialRegistrationState))
.append(" roamingType=").append(ServiceState.roamingTypeToString(mRoamingType))
.append(" accessNetworkTechnology=")
.append(TelephonyManager.getNetworkTypeName(mAccessNetworkTechnology))
@@ -654,10 +688,10 @@ public final class NetworkRegistrationInfo implements Parcelable {
@Override
public int hashCode() {
- return Objects.hash(mDomain, mTransportType, mRegistrationState, mRoamingType,
- mAccessNetworkTechnology, mRejectCause, mEmergencyOnly, mAvailableServices,
- mCellIdentity, mVoiceSpecificInfo, mDataSpecificInfo, mNrState, mRplmn,
- mIsUsingCarrierAggregation);
+ return Objects.hash(mDomain, mTransportType, mRegistrationState, mInitialRegistrationState,
+ mRoamingType, mAccessNetworkTechnology, mRejectCause, mEmergencyOnly,
+ mAvailableServices, mCellIdentity, mVoiceSpecificInfo, mDataSpecificInfo, mNrState,
+ mRplmn, mIsUsingCarrierAggregation);
}
@Override
@@ -672,6 +706,7 @@ public final class NetworkRegistrationInfo implements Parcelable {
return mDomain == other.mDomain
&& mTransportType == other.mTransportType
&& mRegistrationState == other.mRegistrationState
+ && mInitialRegistrationState == other.mInitialRegistrationState
&& mRoamingType == other.mRoamingType
&& mAccessNetworkTechnology == other.mAccessNetworkTechnology
&& mRejectCause == other.mRejectCause
@@ -694,6 +729,7 @@ public final class NetworkRegistrationInfo implements Parcelable {
dest.writeInt(mDomain);
dest.writeInt(mTransportType);
dest.writeInt(mRegistrationState);
+ dest.writeInt(mInitialRegistrationState);
dest.writeInt(mRoamingType);
dest.writeInt(mAccessNetworkTechnology);
dest.writeInt(mRejectCause);
@@ -790,7 +826,7 @@ public final class NetworkRegistrationInfo implements Parcelable {
private int mTransportType;
@RegistrationState
- private int mRegistrationState;
+ private int mInitialRegistrationState;
@NetworkType
private int mAccessNetworkTechnology;
@@ -851,7 +887,7 @@ public final class NetworkRegistrationInfo implements Parcelable {
* @return The same instance of the builder.
*/
public @NonNull Builder setRegistrationState(@RegistrationState int registrationState) {
- mRegistrationState = registrationState;
+ mInitialRegistrationState = registrationState;
return this;
}
@@ -970,7 +1006,7 @@ public final class NetworkRegistrationInfo implements Parcelable {
*/
@SystemApi
public @NonNull NetworkRegistrationInfo build() {
- return new NetworkRegistrationInfo(mDomain, mTransportType, mRegistrationState,
+ return new NetworkRegistrationInfo(mDomain, mTransportType, mInitialRegistrationState,
mAccessNetworkTechnology, mRejectCause, mEmergencyOnly, mAvailableServices,
mCellIdentity, mRplmn, mVoiceSpecificRegistrationInfo,
mDataSpecificRegistrationInfo);
diff --git a/telephony/java/android/telephony/TelephonyManager.java b/telephony/java/android/telephony/TelephonyManager.java
index 71ffd6e2ec9f..b6f86527b747 100644
--- a/telephony/java/android/telephony/TelephonyManager.java
+++ b/telephony/java/android/telephony/TelephonyManager.java
@@ -9290,6 +9290,7 @@ public class TelephonyManager {
try {
ITelephony telephony = getITelephony();
if (telephony != null) {
+ networkTypeBitmask = checkNetworkTypeBitmask(networkTypeBitmask);
return telephony.setAllowedNetworkTypesForReason(getSubId(),
TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_USER, networkTypeBitmask);
}
@@ -9300,6 +9301,20 @@ public class TelephonyManager {
}
/**
+ * If {@link #NETWORK_TYPE_BITMASK_LTE_CA} bit is set, convert it to NETWORK_TYPE_BITMASK_LTE.
+ *
+ * @param networkTypeBitmask The networkTypeBitmask being checked
+ * @return The checked/converted networkTypeBitmask
+ */
+ private long checkNetworkTypeBitmask(@NetworkTypeBitMask long networkTypeBitmask) {
+ if ((networkTypeBitmask & NETWORK_TYPE_BITMASK_LTE_CA) != 0) {
+ networkTypeBitmask ^= NETWORK_TYPE_BITMASK_LTE_CA;
+ networkTypeBitmask |= NETWORK_TYPE_BITMASK_LTE;
+ }
+ return networkTypeBitmask;
+ }
+
+ /**
* Set the allowed network types of the device. This is for carrier or privileged apps to
* enable/disable certain network types on the device. The user preferred network types should
* be set through {@link #setPreferredNetworkTypeBitmask}.
@@ -9325,6 +9340,7 @@ public class TelephonyManager {
try {
ITelephony telephony = getITelephony();
if (telephony != null) {
+ allowedNetworkTypes = checkNetworkTypeBitmask(allowedNetworkTypes);
return telephony.setAllowedNetworkTypesForReason(getSubId(),
TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_CARRIER, allowedNetworkTypes);
}
@@ -9410,6 +9426,7 @@ public class TelephonyManager {
try {
ITelephony telephony = getITelephony();
if (telephony != null) {
+ allowedNetworkTypes = checkNetworkTypeBitmask(allowedNetworkTypes);
telephony.setAllowedNetworkTypesForReason(getSubId(), reason,
allowedNetworkTypes);
} else {
@@ -13727,7 +13744,11 @@ public class TelephonyManager {
*/
public static final long NETWORK_TYPE_BITMASK_LTE = (1 << (NETWORK_TYPE_LTE -1));
/**
+ * NOT USED; this bitmask is exposed accidentally, will be deprecated in U.
+ * If used, will be converted to {@link #NETWORK_TYPE_BITMASK_LTE}.
* network type bitmask indicating the support of radio tech LTE CA (carrier aggregation).
+ *
+ * @see #NETWORK_TYPE_BITMASK_LTE
*/
public static final long NETWORK_TYPE_BITMASK_LTE_CA = (1 << (NETWORK_TYPE_LTE_CA -1));
@@ -16985,4 +17006,41 @@ public class TelephonyManager {
}
mTelephonyRegistryMgr.removeCarrierPrivilegesCallback(callback);
}
+
+ /**
+ * set removable eSIM as default eUICC.
+ *
+ * @hide
+ */
+ @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
+ @RequiresFeature(PackageManager.FEATURE_TELEPHONY_EUICC)
+ public void setRemovableEsimAsDefaultEuicc(boolean isDefault) {
+ try {
+ ITelephony telephony = getITelephony();
+ if (telephony != null) {
+ telephony.setRemovableEsimAsDefaultEuicc(isDefault, getOpPackageName());
+ }
+ } catch (RemoteException e) {
+ Log.e(TAG, "Error in setRemovableEsimAsDefault: " + e);
+ }
+ }
+
+ /**
+ * Returns whether the removable eSIM is default eUICC or not.
+ *
+ * @hide
+ */
+ @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
+ @RequiresFeature(PackageManager.FEATURE_TELEPHONY_EUICC)
+ public boolean isRemovableEsimDefaultEuicc() {
+ try {
+ ITelephony telephony = getITelephony();
+ if (telephony != null) {
+ return telephony.isRemovableEsimDefaultEuicc(getOpPackageName());
+ }
+ } catch (RemoteException e) {
+ Log.e(TAG, "Error in isRemovableEsimDefaultEuicc: " + e);
+ }
+ return false;
+ }
}
diff --git a/telephony/java/android/telephony/euicc/EuiccManager.java b/telephony/java/android/telephony/euicc/EuiccManager.java
index eede9dc474f8..a673807a3f97 100644
--- a/telephony/java/android/telephony/euicc/EuiccManager.java
+++ b/telephony/java/android/telephony/euicc/EuiccManager.java
@@ -25,18 +25,17 @@ import android.annotation.SdkConstant;
import android.annotation.SystemApi;
import android.app.Activity;
import android.app.PendingIntent;
-import android.app.compat.CompatChanges;
import android.compat.annotation.ChangeId;
import android.compat.annotation.EnabledSince;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageManager;
-import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.os.RemoteException;
import android.telephony.SubscriptionInfo;
+import android.telephony.SubscriptionManager;
import android.telephony.TelephonyFrameworkInitializer;
import android.telephony.TelephonyManager;
import android.telephony.UiccCardInfo;
@@ -1209,18 +1208,16 @@ public class EuiccManager {
return;
}
try {
- // TODO: Uncomment below compat change code once callers are ported to use
- // switchToSubscription with portIndex for disable operation.
- // if (subscriptionId == SubscriptionManager.INVALID_SUBSCRIPTION_ID
- // && getIEuiccController().isCompatChangeEnabled(mContext.getOpPackageName(),
- // SWITCH_WITHOUT_PORT_INDEX_EXCEPTION_ON_DISABLE)) {
- // // Apps targeting on Android T and beyond will get exception whenever
- // // switchToSubscription without portIndex is called with INVALID_SUBSCRIPTION_ID.
- // Log.e(TAG, "switchToSubscription without portIndex is not allowed for"
- // + " disable operation");
- // throw new IllegalArgumentException("Must use switchToSubscription with portIndex"
- // + " API for disable operation");
- // }
+ if (subscriptionId == SubscriptionManager.INVALID_SUBSCRIPTION_ID
+ && getIEuiccController().isCompatChangeEnabled(mContext.getOpPackageName(),
+ SWITCH_WITHOUT_PORT_INDEX_EXCEPTION_ON_DISABLE)) {
+ // Apps targeting on Android T and beyond will get exception whenever
+ // switchToSubscription without portIndex is called with INVALID_SUBSCRIPTION_ID.
+ Log.e(TAG, "switchToSubscription without portIndex is not allowed for"
+ + " disable operation");
+ throw new IllegalArgumentException("Must use switchToSubscription with portIndex"
+ + " API for disable operation");
+ }
getIEuiccController().switchToSubscription(mCardId,
subscriptionId, mContext.getOpPackageName(), callbackIntent);
} catch (RemoteException e) {
diff --git a/telephony/java/android/telephony/ims/feature/RcsFeature.java b/telephony/java/android/telephony/ims/feature/RcsFeature.java
index 843827befb65..186241217588 100644
--- a/telephony/java/android/telephony/ims/feature/RcsFeature.java
+++ b/telephony/java/android/telephony/ims/feature/RcsFeature.java
@@ -118,8 +118,10 @@ public class RcsFeature extends ImsFeature {
@Override
public void setCapabilityExchangeEventListener(
@Nullable ICapabilityExchangeEventListener listener) throws RemoteException {
- CapabilityExchangeEventListener listenerWrapper =
- new CapabilityExchangeAidlWrapper(listener);
+ // Set the listener wrapper to null if the listener passed in is null. This will notify
+ // the RcsFeature to trigger the destruction of active capability exchange interface.
+ CapabilityExchangeEventListener listenerWrapper = listener != null
+ ? new CapabilityExchangeAidlWrapper(listener) : null;
executeMethodAsync(() -> mReference.setCapabilityExchangeEventListener(listenerWrapper),
"setCapabilityExchangeEventListener");
}
diff --git a/telephony/java/com/android/internal/telephony/ITelephony.aidl b/telephony/java/com/android/internal/telephony/ITelephony.aidl
index 7d116f9d5063..0ce6b14ce3b0 100644
--- a/telephony/java/com/android/internal/telephony/ITelephony.aidl
+++ b/telephony/java/com/android/internal/telephony/ITelephony.aidl
@@ -2553,4 +2553,18 @@ interface ITelephony {
* for the slot, or {@code null} if none is resolved
*/
String getCarrierServicePackageNameForLogicalSlot(int logicalSlotIndex);
+
+ /**
+ * set removable eSIM as default eUICC.
+ *
+ * @hide
+ */
+ void setRemovableEsimAsDefaultEuicc(boolean isDefault, String callingPackage);
+
+ /**
+ * Returns whether the removable eSIM is default eUICC or not.
+ *
+ * @hide
+ */
+ boolean isRemovableEsimDefaultEuicc(String callingPackage);
}
diff --git a/tests/TelephonyCommonTests/src/com/android/internal/telephony/tests/SmsApplicationTest.java b/tests/TelephonyCommonTests/src/com/android/internal/telephony/tests/SmsApplicationTest.java
index 7ee19fb37244..052ce3a902c1 100644
--- a/tests/TelephonyCommonTests/src/com/android/internal/telephony/tests/SmsApplicationTest.java
+++ b/tests/TelephonyCommonTests/src/com/android/internal/telephony/tests/SmsApplicationTest.java
@@ -22,6 +22,7 @@ import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNotNull;
import static org.mockito.ArgumentMatchers.isNull;
+import static org.mockito.ArgumentMatchers.matches;
import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doAnswer;
@@ -214,7 +215,7 @@ public class SmsApplicationTest {
ApplicationInfo bluetoothApplicationInfo = new ApplicationInfo();
bluetoothApplicationInfo.uid = FAKE_BT_UID;
bluetoothPackageInfo.applicationInfo = bluetoothApplicationInfo;
- when(mPackageManager.getPackageInfo(eq(SmsApplication.BLUETOOTH_PACKAGE_NAME), anyInt()))
+ when(mPackageManager.getPackageInfo(matches(".*android.bluetooth.services"), anyInt()))
.thenReturn(bluetoothPackageInfo);
PackageInfo telephonyProviderPackageInfo = new PackageInfo();
diff --git a/tests/vcn/java/com/android/server/vcn/util/PersistableBundleUtilsTest.java b/tests/vcn/java/com/android/server/vcn/util/PersistableBundleUtilsTest.java
index 294f5c1f4842..9c6d85238b77 100644
--- a/tests/vcn/java/com/android/server/vcn/util/PersistableBundleUtilsTest.java
+++ b/tests/vcn/java/com/android/server/vcn/util/PersistableBundleUtilsTest.java
@@ -268,6 +268,15 @@ public class PersistableBundleUtilsTest {
}
@Test
+ public void testToFromDiskStableBytes() throws Exception {
+ final PersistableBundle testBundle = getTestBundle();
+ final PersistableBundle result =
+ PersistableBundleUtils.fromDiskStableBytes(
+ PersistableBundleUtils.toDiskStableBytes(testBundle));
+ assertTrue(PersistableBundleUtils.isEqual(testBundle, result));
+ }
+
+ @Test
public void testEquality_identical() throws Exception {
final PersistableBundle left = getTestBundle();
final PersistableBundle right = getTestBundle();